jcifs-0.9.0p6 from tgz
authorFelix Schumacher <p0354740@isib001.(none)>
Wed, 6 Aug 2008 14:16:52 +0000 (16:16 +0200)
committerFelix Schumacher <p0354740@isib001.(none)>
Wed, 6 Aug 2008 14:16:52 +0000 (16:16 +0200)
Sun May  2 22:57:30 EDT 2004

Started to add additional WINS entry support but still only the first entry is used.

Most SMB signature code has been moved into jcifs/smb/SigningDigest.java where it's state can more easily be tracked. This is more favorable for
dealing with issues such as failure during signature initialization or the scenario where NULL creds to IPC$ should not use signing after
LOGON_FAILURE with previous session setup.
The behavior of SmbNamedPipe.getOutputStream has changed. If PIPE_TYPE_TRANSACT and PIPE_TYPE_CALL are NOT specified a TRANS_WAIT_NAMED_PIPE will be
issued before the file is opened. This emulates a WaitNamedPipe follow by CreateFile client.
The return value of readWriteFormat is now checked against the NBT header length (from in.available()). If it does not match it is skip()'d and a log
message is written. This should allow jCIFS to get by the OS/400 bug in the Negotiate response.
The ssnLimit property will now cause new transports to be created to accomodate new sessions as opposed to the previous behavior of closing stale
sessions when the ssnLimit is reached. Values can be 0 meaning unlimited, 1 meaning strict 1:1 sessions:transports, and N for N sessions per
transport. A value of 1 should permit the NTLM HTTP Filter to operated with domain controllers that require SMB signatures. This functionality should
prove to be useful for a variety of other reasons as well.
Added additional checks to close NbtSocket in connect() in the event of an error. This should curb the CLOSE_WAIT sockets reported by Gary but
apparently this is not enough to completely eliminate them as traces show even an ACK'd FIN can still leave a socket in this state.
The SmbFiles resulting from listing a workgroup could result in those files have type TYPE_WORKGROUP when they should have been TYPE_SERVER.
Several bugs in the SMB signatures code have been fixed; 1) a concurrency flaw could result in the signing digest being updated inappropriately 2)
the signature of an errant session setup should be ignored 3) a padding byte was not properly considered that could sporatically result in
"Unverifiable signature" errors reading files (this is the outstanding mystery bug mentioned in the 0.7.19 release).
Fixed some incorrect path handling in the DFS referral code.
Two property defaults have been changed; jcifs.smb.client.listSize from 1200 to 65535 and jcifs.smb.client.listCount from 15 to 200. For high latency
networks I recommend changing the values back.
All access specifiers have been reviewed and changed to private or protected wherever possible and appropriate.
The NetBIOS socket OutputStream has been reduced to a virtually useless shell. The NetBIOS header is now handled within ServerMessageBlock.java.
Unfortunately it does not appear to have improved performance considerably. It's hard to tell from the testing performed.
The MpxControl inner class has been removed in favor of something much simpler. It no longer creates Integer objects with each transmission.
Unfortunately it does not appear to have improved performance either.

204 files changed:
CHANGES.txt
README.txt
build.bat [deleted file]
build.sh [deleted file]
build.xml
examples/AllocInfo.java
examples/Append.java
examples/AuthListFiles.java
examples/CallNamedPipe.java
examples/CifsTime.java
examples/CopyTo.java
examples/CreateFile.java
examples/Delete.java
examples/Equals.java
examples/Exists.java
examples/FileInfo.java
examples/FileOps.java
examples/FilterFiles.java
examples/Format.java
examples/Get.java
examples/GetDate.java
examples/GetDfsPath.java
examples/GetType.java
examples/GetURL.java
examples/GrowWrite.java
examples/HttpURL.java
examples/Interleave.java
examples/IsDir.java
examples/Length.java
examples/List.java
examples/ListFiles.java
examples/ListTypes.java
examples/LogTest.java [deleted file]
examples/Makefile
examples/Mkdir.java
examples/NodeStatus.java
examples/NtlmHttpAuthExample.java
examples/NtlmHttpClient.java
examples/OpenExclusive.java
examples/PeekNamedPipe.java
examples/PipeTalk.java
examples/Put.java
examples/Query.java
examples/RenameTo.java
examples/SetAttrs.java
examples/SetTime.java
examples/SlowRead.java
examples/SlowWrite.java
examples/SmbCrawler.java
examples/SmbShell.java
examples/SmbTableFile.java
examples/SmbTableFileRecord.java
examples/SsnLimit.java [new file with mode: 0644]
examples/T2Crawler.java
examples/TestRandomAccess.java
examples/TestSmbURL.java
examples/TestUnicode.java
examples/ThreadedNbtQuery.java
examples/ThreadedSmbCrawler.java
examples/ThreadedUniQuery.java
examples/Torture1.java
examples/Torture2.java
examples/TortureTest5.java
examples/TransactNamedPipe.java
examples/URLTest.java
examples/VerifyGuest.java
examples/VerifyIO.java
examples/VerifyReads.java
examples/WaitNamedPipe.java [new file with mode: 0644]
examples/jcifs.prp
examples/ntlm.prp
examples/pipes/callnp.c
examples/pipes/createf.c
examples/pipes/createnp.c
examples/runtests.sh
src/jcifs/Config.java
src/jcifs/UniAddress.java
src/jcifs/http/Handler.java
src/jcifs/http/NetworkExplorer.java
src/jcifs/http/NtlmHttpFilter.java
src/jcifs/http/NtlmHttpServletRequest.java
src/jcifs/http/NtlmHttpURLConnection.java
src/jcifs/http/NtlmServlet.java
src/jcifs/http/NtlmSsp.java
src/jcifs/https/Handler.java
src/jcifs/netbios/Lmhosts.java
src/jcifs/netbios/Log.java [deleted file]
src/jcifs/netbios/Name.java
src/jcifs/netbios/NameQueryRequest.java
src/jcifs/netbios/NameQueryResponse.java
src/jcifs/netbios/NameServiceClient.java
src/jcifs/netbios/NameServicePacket.java
src/jcifs/netbios/NbtAddress.java
src/jcifs/netbios/NbtException.java
src/jcifs/netbios/NbtSocket.java
src/jcifs/netbios/NodeStatusRequest.java
src/jcifs/netbios/NodeStatusResponse.java
src/jcifs/netbios/SessionRequestPacket.java
src/jcifs/netbios/SessionRetargetResponsePacket.java
src/jcifs/netbios/SessionServicePacket.java
src/jcifs/netbios/SocketInputStream.java
src/jcifs/netbios/SocketOutputStream.java
src/jcifs/ntlmssp/NtlmMessage.java
src/jcifs/ntlmssp/Type1Message.java
src/jcifs/ntlmssp/Type2Message.java
src/jcifs/ntlmssp/Type3Message.java
src/jcifs/smb/AllocInfo.java
src/jcifs/smb/AndXServerMessageBlock.java
src/jcifs/smb/BufferCache.java
src/jcifs/smb/DfsReferral.java
src/jcifs/smb/DosError.java [new file with mode: 0644]
src/jcifs/smb/DosFileFilter.java
src/jcifs/smb/FileEntry.java
src/jcifs/smb/Handler.java
src/jcifs/smb/Info.java
src/jcifs/smb/Log.java [deleted file]
src/jcifs/smb/NetServerEnum2.java
src/jcifs/smb/NetServerEnum2Response.java
src/jcifs/smb/NetShareEnum.java
src/jcifs/smb/NetShareEnumResponse.java
src/jcifs/smb/NtStatus.java [new file with mode: 0644]
src/jcifs/smb/NtlmAuthenticator.java
src/jcifs/smb/NtlmPasswordAuthentication.java
src/jcifs/smb/ServerMessageBlock.java
src/jcifs/smb/SigningDigest.java [new file with mode: 0644]
src/jcifs/smb/SmbAuthException.java
src/jcifs/smb/SmbComBlankResponse.java
src/jcifs/smb/SmbComCheckDirectory.jav
src/jcifs/smb/SmbComClose.java
src/jcifs/smb/SmbComCreateDirectory.java
src/jcifs/smb/SmbComDelete.java
src/jcifs/smb/SmbComDeleteDirectory.java
src/jcifs/smb/SmbComEcho.jav
src/jcifs/smb/SmbComEchoResponse.jav
src/jcifs/smb/SmbComFindClose2.java
src/jcifs/smb/SmbComLogoffAndX.java
src/jcifs/smb/SmbComMove.jav
src/jcifs/smb/SmbComMoveResponse.jav
src/jcifs/smb/SmbComNTCreateAndX.java
src/jcifs/smb/SmbComNTCreateAndXResponse.java
src/jcifs/smb/SmbComNegotiate.java
src/jcifs/smb/SmbComNegotiateResponse.java
src/jcifs/smb/SmbComOpenAndX.java
src/jcifs/smb/SmbComOpenAndXResponse.java
src/jcifs/smb/SmbComQueryInformation.java
src/jcifs/smb/SmbComQueryInformationResponse.java
src/jcifs/smb/SmbComReadAndX.java
src/jcifs/smb/SmbComReadAndXResponse.java
src/jcifs/smb/SmbComRename.java
src/jcifs/smb/SmbComSessionSetupAndX.java
src/jcifs/smb/SmbComSessionSetupAndXResponse.java
src/jcifs/smb/SmbComTransaction.java
src/jcifs/smb/SmbComTransactionResponse.java
src/jcifs/smb/SmbComTreeConnectAndX.java
src/jcifs/smb/SmbComTreeConnectAndXResponse.java
src/jcifs/smb/SmbComTreeDisconnect.java
src/jcifs/smb/SmbComWrite.java
src/jcifs/smb/SmbComWriteAndX.java
src/jcifs/smb/SmbComWriteAndXResponse.java
src/jcifs/smb/SmbComWriteResponse.java
src/jcifs/smb/SmbException.java
src/jcifs/smb/SmbFile.java
src/jcifs/smb/SmbFileFilter.java
src/jcifs/smb/SmbFileInputStream.java
src/jcifs/smb/SmbFileOutputStream.java
src/jcifs/smb/SmbFilenameFilter.java
src/jcifs/smb/SmbNamedPipe.java
src/jcifs/smb/SmbRandomAccessFile.java
src/jcifs/smb/SmbSession.java
src/jcifs/smb/SmbTransport.java
src/jcifs/smb/SmbTree.java
src/jcifs/smb/Trans2FindFirst2.java
src/jcifs/smb/Trans2FindFirst2Response.java
src/jcifs/smb/Trans2FindNext2.java
src/jcifs/smb/Trans2GetDfsReferral.java
src/jcifs/smb/Trans2GetDfsReferralResponse.java
src/jcifs/smb/Trans2QueryFSInformation.java
src/jcifs/smb/Trans2QueryFSInformationResponse.java
src/jcifs/smb/Trans2QueryPathInformation.java
src/jcifs/smb/Trans2QueryPathInformationResponse.java
src/jcifs/smb/Trans2SetFileInformation.java
src/jcifs/smb/Trans2SetFileInformationResponse.java
src/jcifs/smb/TransCallNamedPipe.java
src/jcifs/smb/TransCallNamedPipeResponse.java
src/jcifs/smb/TransPeekNamedPipe.java
src/jcifs/smb/TransPeekNamedPipeResponse.java
src/jcifs/smb/TransTransactNamedPipe.java
src/jcifs/smb/TransTransactNamedPipeResponse.java
src/jcifs/smb/TransWaitNamedPipe.java
src/jcifs/smb/TransWaitNamedPipeResponse.java
src/jcifs/smb/TransactNamedPipeInputStream.java
src/jcifs/smb/TransactNamedPipeOutputStream.java
src/jcifs/smb/WinError.java [new file with mode: 0644]
src/jcifs/util/Base64.java
src/jcifs/util/Config.java [deleted file]
src/jcifs/util/DES.java
src/jcifs/util/Encdec.java
src/jcifs/util/HMACT64.java
src/jcifs/util/Hexdump.java [new file with mode: 0644]
src/jcifs/util/Log.java [deleted file]
src/jcifs/util/LogStream.java [new file with mode: 0644]
src/jcifs/util/LogWriter.java [deleted file]
src/jcifs/util/MimeMap.java
src/jcifs/util/PropertiesTree.java [deleted file]

index 6b42e95..eddd740 100644 (file)
@@ -1,33 +1,19 @@
-Mon Apr 19 20:23:10 EDT 2004
-jcifs-0.8.3 released / File Corruption with HotSpot
-
-A  serious  bug was discovered in the HotSpot VM on Linux that can cause an
-offset  field to be encoded incorrectly resulting in file corruption. A bug
-report  has  been  submitted  and the code in question has been modified to
-avoid  the  problem.  If you are using the <tt>-server</tt> option on Linux
-you  must  upgrade to this version of jCIFS. Big thanks to Richard Heap for
-diagnosing and fixing this very elusive issue. 
-
-Sun Mar 14 18:54:14 EST 2004
-jcifs-0.8.2 released
-
-The DST adjustement used may not be correct. It has been commented out. The
-problem regarding SmbFile.getParent has been fixed. 
-
-Thu Feb 26 19:26:14 EST 2004
-jcifs-0.8.1 released
-
-The  decision  to  exclude ATTR_HIDDEN files in generic list operations has
-been  revoked.  All  list methods now include all files unless specifically
-filtered.
-
-The following bugs have been fixed:
-
-  o Previously querying the last modified time or file size immediately
-       following    a    SmbFileOutputStream.write   call   returned   old
-       information.
-  o The createNewFile method did not use the correct open mode.
-  o The setLastModified method set the create time to an invalid value.
+Sun May  2 22:57:30 EDT 2004
+
+Started to add additional WINS entry support but still only the first entry is used.
+
+Most SMB signature code has been moved into jcifs/smb/SigningDigest.java where it's state can more easily be tracked. This is more favorable for dealing with issues such as failure during signature initialization or the scenario where NULL creds to IPC$ should not use signing after LOGON_FAILURE with previous session setup.
+The behavior of SmbNamedPipe.getOutputStream has changed. If PIPE_TYPE_TRANSACT and PIPE_TYPE_CALL are NOT specified a TRANS_WAIT_NAMED_PIPE will be issued before the file is opened. This emulates a WaitNamedPipe follow by CreateFile client.
+The return value of readWriteFormat is now checked against the NBT header length (from in.available()). If it does not match it is skip()'d and a log message is written. This should allow jCIFS to get by the OS/400 bug in the Negotiate response.
+The ssnLimit property will now cause new transports to be created to accomodate new sessions as opposed to the previous behavior of closing stale sessions when the ssnLimit is reached. Values can be 0 meaning unlimited, 1 meaning strict 1:1 sessions:transports, and N for N sessions per transport. A value of 1 should permit the NTLM HTTP Filter to operated with domain controllers that require SMB signatures. This functionality should prove to be useful for a variety of other reasons as well.
+Added additional checks to close NbtSocket in connect() in the event of an error. This should curb the CLOSE_WAIT sockets reported by Gary but apparently this is not enough to completely eliminate them as traces show even an ACK'd FIN can still leave a socket in this state.
+The SmbFiles resulting from listing a workgroup could result in those files have type TYPE_WORKGROUP when they should have been TYPE_SERVER.
+Several bugs in the SMB signatures code have been fixed; 1) a concurrency flaw could result in the signing digest being updated inappropriately 2) the signature of an errant session setup should be ignored 3) a padding byte was not properly considered that could sporatically result in "Unverifiable signature" errors reading files (this is the outstanding mystery bug mentioned in the 0.7.19 release).
+Fixed some incorrect path handling in the DFS referral code.
+Two property defaults have been changed; jcifs.smb.client.listSize from 1200 to 65535 and jcifs.smb.client.listCount from 15 to 200. For high latency networks I recommend changing the values back.
+All access specifiers have been reviewed and changed to private or protected wherever possible and appropriate.
+The NetBIOS socket OutputStream has been reduced to a virtually useless shell. The NetBIOS header is now handled within ServerMessageBlock.java. Unfortunately it does not appear to have improved performance considerably. It's hard to tell from the testing performed.
+The MpxControl inner class has been removed in favor of something much simpler. It no longer creates Integer objects with each transmission. Unfortunately it does not appear to have improved performance either.
 
 Tue Feb 10 23:44:45 EST 2004
 jcifs-0.8.0 released
index 5ee5a1a..fd30bf5 100644 (file)
@@ -1,27 +1,3 @@
-Mon Apr 19 20:23:10 EDT 2004
-jcifs-0.8.3 released / File Corruption with HotSpot
-
-A serious bug was discovered in the HotSpot VM on Linux that can cause file
-corruption. It has been fixed. 
-
-Sun Mar 14 18:54:14 EST 2004
-jcifs-0.8.2 released
-
-The DST adjustement used may not be correct. It has been commented out. The
-problem regarding SmbFile.getParent has been fixed. 
-
-Thu Feb 26 19:26:14 EST 2004
-jcifs-0.8.1 released
-
-Hidden  files  are  included  in  all  list  operations unless specifically
-filtered.  A  attribute  caching bug, createNewFile open mode bug, and time
-setting method bugs have been fixed. 
-
-Tue Feb 10 23:44:45 EST 2004
-jcifs-0.8.0 released
-
-This completes the 0.8 beta cycle. There is no technical difference between
-this release and 0.8.0b1. 
 Tue Feb 10 23:44:45 EST 2004
 jcifs-0.8.0 released
 
diff --git a/build.bat b/build.bat
deleted file mode 100644 (file)
index 90a8966..0000000
--- a/build.bat
+++ /dev/null
@@ -1,10 +0,0 @@
-@echo off
-
-REM set JAVA_HOME=C:\Program Files\JavaSoft\JRE\1.2
-set JAVA_HOME=C:\jdk1.2.2
-
-set JAVA=%JAVA_HOME%\bin\java
-set CLASSPATH=ant\ant.jar;ant\jaxp.jar;ant\parser.jar
-
-"%JAVA%" -classpath "%CLASSPATH%" -Dant.home=ant org.apache.tools.ant.Main %1 %2 %3 %4 %5 %6 %7 %8 %9 -buildfile build.xml
-
diff --git a/build.sh b/build.sh
deleted file mode 100644 (file)
index 1924c4a..0000000
--- a/build.sh
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/bin/sh
-
-JAVA_HOME=/usr/local/java
-CLASSPATH=ant/ant.jar:ant/jaxp.jar:ant/parser.jar:${JAVA_HOME}/lib/tools.jar:/usr/local/lib/servlet.jar
-#CLASSPATH=ant/ant.jar:ant/jaxp.jar:ant/parser.jar:/usr/local/resin/lib/jsdk23.jar:.
-
-$JAVA_HOME/bin/java -classpath $CLASSPATH org.apache.tools.ant.Main -buildfile build.xml $@
index b21b08a..babab71 100644 (file)
--- a/build.xml
+++ b/build.xml
-<?xml version="1.0"?>
-<!--
-
-       This is an "Ant" build file. See http://jakarta.apache.org/ant/index.html for details.
-
---> 
-<project name="jcifs" default="main" basedir=".">
-       <target name="main">
-               <echo message="    TARGETS:"/>
-               <echo message="        smb &lt;-- to build jcifs"/>
-               <echo message="        netbios"/>
-               <echo message="        util"/>
-               <echo message="        clean"/>
-               <echo message="        jar"/>
-               <echo message="        tgz"/>
-               <echo message="        zip"/>
-               <echo message="        javadoc"/>
-       </target>
-
-       <target name="comm">
-               <mkdir dir="build"/>
-               <javac srcdir="src"
-                               destdir="build"
-                               includes="jcifs/*.java"
-                               debug="on"/>
-       </target>
-       <target name="util">
-               <mkdir dir="build"/>
-               <javac srcdir="src"
-                               destdir="build"
-                               includes="jcifs/util/*.java"
-                               debug="on"/>
-       </target>
-       <target name="netbios" depends="util">
-               <mkdir dir="build"/>
-               <javac srcdir="src"
-                               destdir="build"
-                               includes="jcifs/netbios/*.java"
-                               debug="on"/>
-       </target>
-       <target name="http">
-               <mkdir dir="build"/>
-               <javac srcdir="src"
-                               destdir="build"
-                               includes="jcifs/http/*.java"
-                               debug="on"/>
-       </target>
-       <target name="https">
-               <mkdir dir="build"/>
-               <javac srcdir="src"
-                               destdir="build"
-                               includes="jcifs/https/*.java"
-                               debug="on"/>
-       </target>
-       <target name="smb" depends="comm,netbios,util,http,https">
-               <mkdir dir="build"/>
-               <javac srcdir="src"
-                               destdir="build"
-                               includes="jcifs/smb/*.java"
-                               debug="on"/>
-       </target>
-
-       <target name="clean">
-               <delete dir="build"/>
-       </target>
-       <target name="jar" depends="smb">
-               <copy file="src/jcifs/util/mime.map" tofile="build/jcifs/util/mime.map" overwrite="yes"/>
-               <copy file="src/jcifs/http/ne.css" tofile="build/jcifs/http/ne.css" overwrite="yes"/>
-               <jar jarfile="jcifs-0.8.3.jar" basedir="build"/>
-       </target>
-
-       <target name="tgz">
-               <copy todir="dist_tmp/jcifs_0.8.3">
-                       <fileset dir="." excludes="ant,**/.*,build,jcifs.prp,**/*.tgz,**/*.zip"/>
-               </copy>
-               <tar tarfile="jcifs-0.8.3.tar" basedir="dist_tmp"/>
-               <gzip src="jcifs-0.8.3.tar" zipfile="jcifs-0.8.3.tgz"/>
-               <delete file="jcifs-0.8.3.tar"/>
-               <delete dir="dist_tmp"/>
-       </target>
-       <target name="zip">
-               <copy todir="dist_tmp/jcifs_0.8.3">
-                       <fileset dir="." excludes="ant,**/.*,build,jcifs.prp,**/*.tgz,**/*.zip"/>
-               </copy>
-               <fixcrlf srcdir="dist_tmp" cr="add" tab="remove" tablength="4" excludes="**/*.jar,**/*.exe"/>
-               <zip zipfile="jcifs-0.8.3.zip" basedir="dist_tmp"/>
-               <delete dir="dist_tmp"/>
-       </target>
-
-       <target name="javadoc">
-               <delete dir="docs/api"/>
-               <mkdir dir="docs/api"/>
-               <javadoc sourcefiles="jcifs/netbios/NbtAddress,jcifs/smb/SmbFile,jcifs/smb/SmbException,jcifs/smb/SmbAuthException,jcifs/smb/SmbNamedPipe,jcifs/smb/SmbFileInputStream,jcifs/smb/SmbFileOutputStream,jcifs/UniAddress,jcifs/Config,jcifs/util/PropertiesTree,jcifs/util/Log,jcifs/smb/SmbSession,jcifs/smb/NtlmPasswordAuthentication,jcifs/http/NtlmSsp,jcifs/http/NtlmHttpFilter,jcifs/http/NetworkExplorer,jcifs/http/NtlmServlet,jcifs/smb/NtlmAuthenticator,jcifs/smb/DosFileFilter,jcifs/smb/SmbRandomAccessFile,jcifs/smb/SmbFilenameFilter,jcifs/smb/SmbFileFilter"
-                               sourcepath="src"
-                               destdir="docs/api"
-                               overview="docs/overview.html"
-                               author="true"
-                               version="true"
-                               use="true"
-                               windowtitle="jCIFS API">
-                       <!-- link href="http://java.sun.com/products/jdk/1.2/docs/api/"/-->
-               </javadoc>
-               <copy file="docs/allclasses-frame.html" tofile="docs/api/allclasses-frame.html" overwrite="yes"/>
-       </target>
+<project name="jcifs" default="usage" basedir=".">
+
+    <property name="version" value="0.9.0p6"/>
+
+    <target name="usage">
+        <echo>
+Available Build Targets:
+
+dependencies: Checks that all class dependencies are met.
+     compile: Builds the jCIFS classes.
+         jar: Packages the jCIFS classes into a .jar file.
+     javadoc: Creates the Javadoc API documentation.
+         all: Performs all of the above.
+
+       clean: Removes build artifacts.
+    allclean: Removes distribution and build artifacts.  This
+              includes the .jar file, .class files, and
+              the Javadoc API documentation.
+
+       jcifs: Builds the "all" target, followed by "clean".  This
+              reproduces the distribution package contents.
+     distrib: Builds the "jcifs" target, and additionally
+              recreates the .zip and .tgz downloadable
+              distributions.
+    checksum: Creates MD5 checksums of the .zip and .tgz
+              distributions.
+
+       usage: Displays this message.</echo>
+    </target>
+
+    <target name="hasServlet" unless="hasServlet">
+        <fail>
+
+    The Java Servlet API classes could not be found.  These files can be
+    obtained from:
+
+        http://java.sun.com/products/servlet/download.html
+        </fail>
+    </target>
+
+    <target name="dependencies">
+        <available classname="javax.servlet.Servlet" property="hasServlet"/>
+        <antcall target="hasServlet"/>
+    </target>
+
+    <target name="compile" depends="dependencies">
+        <mkdir dir="build"/>
+        <javac srcdir="src" destdir="build" debug="on"/>
+        <copy file="src/jcifs/util/mime.map" tofile="build/jcifs/util/mime.map" overwrite="yes"/>
+        <copy file="src/jcifs/http/ne.css" tofile="build/jcifs/http/ne.css" overwrite="yes"/>
+    </target>
+
+    <target name="jar" depends="compile">
+        <jar jarfile="jcifs-${version}.jar">
+            <fileset dir="build"/>
+        </jar>
+    </target>
+
+    <target name="javadoc">
+        <delete dir="docs/api" quiet="true"/>
+        <mkdir dir="docs/api"/>
+        <javadoc destdir="docs/api"
+            overview="docs/overview.html"
+            author="true"
+            version="true"
+            use="true"
+            sourcefiles="src/jcifs/Config.java,src/jcifs/UniAddress.java,src/jcifs/http/NetworkExplorer.java,src/jcifs/http/NtlmHttpFilter.java,src/jcifs/http/NtlmServlet.java,src/jcifs/http/NtlmSsp.java,src/jcifs/netbios/NbtAddress.java,src/jcifs/smb/DosFileFilter.java,src/jcifs/smb/NtlmAuthenticator.java,src/jcifs/smb/NtlmPasswordAuthentication.java,src/jcifs/smb/SmbAuthException.java,src/jcifs/smb/SmbException.java,src/jcifs/smb/SmbFile.java,src/jcifs/smb/SmbFileFilter.java,src/jcifs/smb/SmbFileInputStream.java,src/jcifs/smb/SmbFilenameFilter.java,src/jcifs/smb/SmbFileOutputStream.java,src/jcifs/smb/SmbNamedPipe.java,src/jcifs/smb/SmbRandomAccessFile.java,src/jcifs/smb/SmbSession.java"
+            windowtitle="jCIFS API">
+            <sourcepath path="src"/>
+            <classpath>
+                <pathelement path="${java.class.path}"/>
+                <fileset dir=".">
+                    <include name="**/*.jar"/>
+                </fileset>
+            </classpath>
+        </javadoc>
+        <copy file="docs/allclasses-frame.html" tofile="docs/api/allclasses-frame.html" overwrite="yes"/>
+    </target>
+
+    <target name="all" depends="jar,javadoc"/>
+
+    <target name="clean">
+        <delete dir="build" quiet="true"/>
+    </target>
+
+    <target name="allclean" depends="clean">
+        <delete quiet="true">
+            <fileset dir=".">
+                <include name="jcifs-${version}.zip"/>
+                <include name="jcifs-${version}.zip.MD5"/>
+                <include name="jcifs-${version}.tgz"/>
+                <include name="jcifs-${version}.tgz.MD5"/>
+                <include name="jcifs-${version}.jar"/>
+            </fileset>
+        </delete>
+        <delete dir="docs/api" quiet="true"/>
+    </target>
+
+    <target name="jcifs" depends="all,clean"/>
+
+    <target name="distrib" depends="jcifs">
+        <delete dir="dist_tmp" quiet="true"/>
+        <copy todir="dist_tmp/jcifs_${version}">
+            <fileset dir=".">
+                <include name="build.xml"/>
+                <include name="jcifs-${version}.jar"/>
+                <include name="CHANGES.txt"/>
+                <include name="README.txt"/>
+                <include name="docs/**"/>
+                <include name="examples/**"/>
+                <include name="src/**"/>
+            </fileset>
+        </copy>
+        <fixcrlf srcdir="dist_tmp" tab="remove" tablength="4">
+            <include name="**/*.java"/>
+            <include name="**/*.c"/>
+            <include name="**/*.h"/>
+            <include name="**/*.css"/>
+            <include name="**/*.html"/>
+            <include name="**/*.xml"/>
+            <include name="**/*.txt"/>
+            <include name="**/*.jav"/>
+            <include name="**/*.bak"/>
+            <include name="**/*.prp"/>
+            <include name="**/*.map"/>
+        </fixcrlf>
+        <fixcrlf srcdir="dist_tmp" eol="crlf">
+            <include name="**/*.java"/>
+            <include name="**/*.c"/>
+            <include name="**/*.h"/>
+            <include name="**/*.css"/>
+            <include name="**/*.html"/>
+            <include name="**/*.xml"/>
+            <include name="**/*.txt"/>
+            <include name="**/*.jav"/>
+            <include name="**/*.bak"/>
+            <include name="**/*.prp"/>
+            <include name="**/*.map"/>
+            <include name="**/Makefile"/>
+        </fixcrlf>
+        <zip zipfile="jcifs-${version}.zip" basedir="dist_tmp"/>
+        <fixcrlf srcdir="dist_tmp" eol="lf">
+            <include name="**/*.java"/>
+            <include name="**/*.c"/>
+            <include name="**/*.h"/>
+            <include name="**/*.css"/>
+            <include name="**/*.html"/>
+            <include name="**/*.xml"/>
+            <include name="**/*.txt"/>
+            <include name="**/*.jav"/>
+            <include name="**/*.bak"/>
+            <include name="**/*.prp"/>
+            <include name="**/*.map"/>
+            <include name="**/Makefile"/>
+        </fixcrlf>
+        <tar tarfile="jcifs-${version}.tar" basedir="dist_tmp"/>
+        <delete dir="dist_tmp" quiet="true"/>
+        <gzip src="jcifs-${version}.tar" zipfile="jcifs-${version}.tgz"/>
+        <delete file="jcifs-${version}.tar" quiet="true"/>
+    </target>
+
+    <target name="checksum">
+        <checksum file="jcifs-${version}.zip"/>
+        <checksum file="jcifs-${version}.tgz"/>
+    </target>
+
 </project>
index 842f764..641d153 100644 (file)
@@ -2,10 +2,10 @@ import jcifs.smb.SmbFile;
 
 public class AllocInfo {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFile f = new SmbFile( argv[0] );
-               System.out.println( f.getDiskFreeSpace() );
-       }
+        SmbFile f = new SmbFile( argv[0] );
+        System.out.println( f.getDiskFreeSpace() );
+    }
 }
 
index 8021d88..5a8031b 100644 (file)
@@ -3,20 +3,20 @@ import jcifs.smb.SmbFileOutputStream;
 
 public class Append {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFile f = new SmbFile( argv[0] );
-               SmbFileOutputStream out = new SmbFileOutputStream( f, true );
+        SmbFile f = new SmbFile( argv[0] );
+        SmbFileOutputStream out = new SmbFileOutputStream( f, true );
 
-               byte[] msg;
-               int i = 0;
-               while( i++ < 5 ) {
-                       msg = new String( "this is msg #" + i ).getBytes();
-                       out.write( msg );
-                       System.out.write( msg );
-                       Thread.sleep( 17000 );
-               }
+        byte[] msg;
+        int i = 0;
+        while( i++ < 5 ) {
+            msg = new String( "this is msg #" + i ).getBytes();
+            out.write( msg );
+            System.out.write( msg );
+            Thread.sleep( 17000 );
+        }
 
-               out.close();
-       }
+        out.close();
+    }
 }
index eb3d2d1..9958fad 100644 (file)
@@ -1,7 +1,6 @@
 import jcifs.netbios.NbtAddress;
 import jcifs.util.*;
 import jcifs.smb.*;
-import jcifs.util.Log;
 import java.util.Date;
 
 public class AuthListFiles extends NtlmAuthenticator {
@@ -10,50 +9,50 @@ public class AuthListFiles extends NtlmAuthenticator {
         int c;
         StringBuffer sb = new StringBuffer();
         while(( c = System.in.read() ) != '\n' ) {
-                       if( c == -1 ) return "";
+            if( c == -1 ) return "";
             sb.append( (char)c );
         }
         return sb.toString().trim();
     }
 
-       public AuthListFiles( String[] argv ) throws Exception {
-               NtlmAuthenticator.setDefault( this );
-
-               SmbFile file = new SmbFile( argv[0] );
-
-               SmbFile[] files = file.listFiles();
-
-               for( int i = 0; i < files.length; i++ ) {
-                       System.out.print( " " + files[i].getName() );
-               }
-               System.out.println();
-       }
-
-       protected NtlmPasswordAuthentication getNtlmPasswordAuthentication() {
-               System.out.println( getRequestingException().getMessage() + " for " + getRequestingURL() );
-               System.out.print( "username: " );
-               try {
-                       int i;
-                       String username = readLine();
-                       String domain = null, password;
-
-                       if(( i = username.indexOf( '\\' )) != -1 ) {
-                               domain = username.substring( 0, i );
-                               username = username.substring( i + 1 );
-                       }
-                       System.out.print( "password: " );
-                       password = readLine();
-                       if( password.length() == 0 ) {
-                               return null;
-                       }
-                       return new NtlmPasswordAuthentication( domain, username, password );
-               } catch( Exception e ) {
-               }
-               return null;
-       }
-
-
-       public static void main( String[] argv ) throws Exception {
-               new AuthListFiles( argv );
-       }
+    public AuthListFiles( String[] argv ) throws Exception {
+        NtlmAuthenticator.setDefault( this );
+
+        SmbFile file = new SmbFile( argv[0] );
+
+        SmbFile[] files = file.listFiles();
+
+        for( int i = 0; i < files.length; i++ ) {
+            System.out.print( " " + files[i].getName() );
+        }
+        System.out.println();
+    }
+
+    protected NtlmPasswordAuthentication getNtlmPasswordAuthentication() {
+        System.out.println( getRequestingException().getMessage() + " for " + getRequestingURL() );
+        System.out.print( "username: " );
+        try {
+            int i;
+            String username = readLine();
+            String domain = null, password;
+
+            if(( i = username.indexOf( '\\' )) != -1 ) {
+                domain = username.substring( 0, i );
+                username = username.substring( i + 1 );
+            }
+            System.out.print( "password: " );
+            password = readLine();
+            if( password.length() == 0 ) {
+                return null;
+            }
+            return new NtlmPasswordAuthentication( domain, username, password );
+        } catch( Exception e ) {
+        }
+        return null;
+    }
+
+
+    public static void main( String[] argv ) throws Exception {
+        new AuthListFiles( argv );
+    }
 }
index 1d97ae2..04f49b3 100644 (file)
@@ -6,30 +6,30 @@ import java.io.FileOutputStream;
 
 public class CallNamedPipe {
 
-       public static void main( String[] argv ) throws Exception {
+    public static void main( String[] argv ) throws Exception {
 
-               if( argv.length < 2 ) {
-                       throw new IllegalArgumentException( "args: <smburl> <filedatatosend> <filetowriterecvdata>" );
-               }
+        if( argv.length < 2 ) {
+            throw new IllegalArgumentException( "args: <smburl> <filedatatosend> <filetowriterecvdata>" );
+        }
 
-               byte[] b = new byte[65535];
-               FileInputStream fin = new FileInputStream( argv[1] );
-               FileOutputStream fos = new FileOutputStream( argv[2] );
+        byte[] b = new byte[65535];
+        FileInputStream fin = new FileInputStream( argv[1] );
+        FileOutputStream fos = new FileOutputStream( argv[2] );
 
-               SmbNamedPipe pipe = new SmbNamedPipe( argv[0],
-                               SmbNamedPipe.PIPE_TYPE_RDWR | SmbNamedPipe.PIPE_TYPE_CALL );
-               OutputStream out = pipe.getNamedPipeOutputStream();
-               InputStream in = pipe.getNamedPipeInputStream();
+        SmbNamedPipe pipe = new SmbNamedPipe( argv[0],
+                SmbNamedPipe.PIPE_TYPE_RDWR | SmbNamedPipe.PIPE_TYPE_CALL );
+        OutputStream out = pipe.getNamedPipeOutputStream();
+        InputStream in = pipe.getNamedPipeInputStream();
 
-               int n = fin.read( b );
-               System.out.println( "writing " + n + " bytes" );
-               out.write( b, 0, n );
-               n = in.read(b);
-               System.out.println( "read " + n + " bytes" );
-               fos.write(b, 0, n );
+        int n = fin.read( b );
+        System.out.println( "writing " + n + " bytes" );
+        out.write( b, 0, n );
+        n = in.read(b);
+        System.out.println( "read " + n + " bytes" );
+        fos.write(b, 0, n );
 
-               fin.close();
-               fos.close();
-               out.close();
-       }
+        fin.close();
+        fos.close();
+        out.close();
+    }
 }
index 7755f12..0331b17 100644 (file)
@@ -3,45 +3,45 @@ import java.util.TimeZone;
 
 public class CifsTime {
 
-       // Observed dates reporting ServerTimeZone=240
-       // file last modified date = { low, high };
-
-       // Mon Mar 26 23:14:42 EST 2001 (no DST)
-       static final int[] D = { 0x10BE3D00, 0x01C0B66C };
-
-       // Mon Apr 30 03:17:14 EST 2001 (in DST)
-       //static final int[] D = { 0x9474B900, 0x01C0D145 };
-
-       static final long MILLISECONDS_BETWEEN_1970_AND_1601 = 11644473600000L;
-
-       static long calcDate() {
-               int lo, hi;
-               long t;
-
-               t = ((long)D[1] << 32 ) | ( (long)D[0] & 0xFFFFFFFFL );
-               t = ( t / 10000L - MILLISECONDS_BETWEEN_1970_AND_1601 );
-
-               if( TimeZone.getDefault().inDaylightTime( new Date() )) {
-                       // in dst
-
-                       if( TimeZone.getDefault().inDaylightTime( new Date( t ))) {
-                               // t was also generated in dst too so no correction
-                               return t;
-                       }
-                       // t was not generated during dst so add 1 hour
-                       return t + 3600000L;
-               } else {
-                       // not in dst
-
-                       if( TimeZone.getDefault().inDaylightTime( new Date( t ))) {
-                               // t was generated in dst so subtract 1 hour
-                               return t - 3600000L;
-                       }
-                       // t was also not generated in dst so no correction
-                       return t;
-               }
-       }
-       public static void main( String[] argv ) throws Exception {
-               System.out.println( new Date( calcDate() ));
-       }
+    // Observed dates reporting ServerTimeZone=240
+    // file last modified date = { low, high };
+
+    // Mon Mar 26 23:14:42 EST 2001 (no DST)
+    static final int[] D = { 0x10BE3D00, 0x01C0B66C };
+
+    // Mon Apr 30 03:17:14 EST 2001 (in DST)
+    //static final int[] D = { 0x9474B900, 0x01C0D145 };
+
+    static final long MILLISECONDS_BETWEEN_1970_AND_1601 = 11644473600000L;
+
+    static long calcDate() {
+        int lo, hi;
+        long t;
+
+        t = ((long)D[1] << 32 ) | ( (long)D[0] & 0xFFFFFFFFL );
+        t = ( t / 10000L - MILLISECONDS_BETWEEN_1970_AND_1601 );
+
+        if( TimeZone.getDefault().inDaylightTime( new Date() )) {
+            // in dst
+
+            if( TimeZone.getDefault().inDaylightTime( new Date( t ))) {
+                // t was also generated in dst too so no correction
+                return t;
+            }
+            // t was not generated during dst so add 1 hour
+            return t + 3600000L;
+        } else {
+            // not in dst
+
+            if( TimeZone.getDefault().inDaylightTime( new Date( t ))) {
+                // t was generated in dst so subtract 1 hour
+                return t - 3600000L;
+            }
+            // t was also not generated in dst so no correction
+            return t;
+        }
+    }
+    public static void main( String[] argv ) throws Exception {
+        System.out.println( new Date( calcDate() ));
+    }
 }
index a4fdc42..2eec40f 100644 (file)
@@ -2,11 +2,11 @@ import jcifs.smb.SmbFile;
 
 public class CopyTo {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFile from = new SmbFile( argv[0] );
-               SmbFile to = new SmbFile( argv[1] );
-               from.copyTo( to );
-       }
+        SmbFile from = new SmbFile( argv[0] );
+        SmbFile to = new SmbFile( argv[1] );
+        from.copyTo( to );
+    }
 }
 
index a7d4685..9556bed 100644 (file)
@@ -2,10 +2,10 @@ import jcifs.smb.SmbFileOutputStream;
 
 public class CreateFile {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFileOutputStream out = new SmbFileOutputStream( argv[0], false );
-               out.close();
-       }
+        SmbFileOutputStream out = new SmbFileOutputStream( argv[0], false );
+        out.close();
+    }
 }
 
index 8c313de..133eb9f 100644 (file)
@@ -2,9 +2,9 @@ import jcifs.smb.*;
 
 public class Delete {
 
-       public static void main( String argv[] ) throws Exception {
-               SmbFile f = new SmbFile( argv[0] );
-               f.delete();
-       }
+    public static void main( String argv[] ) throws Exception {
+        SmbFile f = new SmbFile( argv[0] );
+        f.delete();
+    }
 }
 
index 6fbe616..6f7d04a 100644 (file)
@@ -2,11 +2,11 @@ import jcifs.smb.SmbFile;
 
 public class Equals {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFile f1 = new SmbFile( argv[0] );
-               SmbFile f2 = new SmbFile( argv[1] );
-               System.err.println( f1.equals( f2 ));
-       }
+        SmbFile f1 = new SmbFile( argv[0] );
+        SmbFile f2 = new SmbFile( argv[1] );
+        System.err.println( f1.equals( f2 ));
+    }
 }
 
index 009e210..c04d77c 100644 (file)
@@ -2,14 +2,14 @@ import jcifs.smb.SmbFile;
 
 public class Exists {
 
-       public static void main( String argv[] ) throws Exception {
-
-               SmbFile f = new SmbFile( argv[0] );
-               if( f.exists() ) {
-                       System.out.println( argv[0] + " exists" );
-               } else {
-                       System.out.println( argv[0] + " does not exist" );
-               }
-       }
+    public static void main( String argv[] ) throws Exception {
+
+        SmbFile f = new SmbFile( argv[0] );
+        if( f.exists() ) {
+            System.out.println( argv[0] + " exists" );
+        } else {
+            System.out.println( argv[0] + " does not exist" );
+        }
+    }
 }
 
index bfc9bfb..34320eb 100644 (file)
@@ -5,127 +5,115 @@ import jcifs.smb.SmbFile;
 
 public class FileInfo {
 
-       static String getTypeName(int type) {
-               switch( type ) {
-                       case SmbFile.TYPE_FILESYSTEM:
-                               return "TYPE_FILESYSTEM";
-                       case SmbFile.TYPE_WORKGROUP:
-                               return "TYPE_WORKGROUP";
-                       case SmbFile.TYPE_SERVER:
-                               return "TYPE_SERVER";
-                       case SmbFile.TYPE_SHARE:
-                               return "TYPE_SHARE";
-                       case SmbFile.TYPE_NAMED_PIPE:
-                               return "TYPE_NAMED_PIPE";
-                       case SmbFile.TYPE_PRINTER:
-                               return "TYPE_PRINTER";
-                       default:
-                               return "UNKNOWN: " + type;
-               }
-       }
+    static final String TYPES[] = {
+        "TYPE_COMM",
+        "TYPE_FILESYSTEM",
+        "TYPE_NAMED_PIPE",
+        "TYPE_PRINTER",
+        "TYPE_SERVER",
+        "TYPE_SHARE",
+        "TYPE_WORKGROUP"
+    };
 
-       public static void main( String argv[] ) throws Exception {
-               int i, start, end;;
-               SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yy hh:mm:ss a" );
-               GregorianCalendar cal = new GregorianCalendar();
-               SmbFile f;
+    public static void main( String argv[] ) throws Exception {
+        int i, start, end;;
+        SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yy hh:mm:ss a" );
+        GregorianCalendar cal = new GregorianCalendar();
+        SmbFile f;
 
-               if( argv.length < 2 ) {
-                       throw new IllegalArgumentException( "usage: FileInfo <url> <opindex>" );
-               }
+        if( argv.length < 2 ) {
+            throw new IllegalArgumentException( "usage: FileInfo <url> <opindex>" );
+        }
 
-               if( argv.length == 3 ) {
-                       SmbFile tmp = new SmbFile( argv[0] );
-                       f = new SmbFile( tmp.toString(), argv[1] );
-                       start = Integer.parseInt( argv[2] );
-               } else {
-                       f = new SmbFile( argv[0] );
-                       start = Integer.parseInt( argv[1] );
-               }
+        if( argv.length == 3 ) {
+            SmbFile tmp = new SmbFile( argv[0] );
+            f = new SmbFile( tmp.toString(), argv[1] );
+            start = Integer.parseInt( argv[2] );
+        } else {
+            f = new SmbFile( argv[0] );
+            start = Integer.parseInt( argv[1] );
+        }
 
-               sdf.setCalendar( cal );
+        sdf.setCalendar( cal );
 
-               i = end = start;
-               do {
-                       switch( i ) {
-                               case 0:
-                                       System.out.println( "        toString: " + f.toString() );
-                                       break;
-                               case 1:
-                                       System.out.println( "           toURL: " + f.toURL() );
-                                       break;
-                               case 2:
-                                       System.out.println( "         getName: " + f.getName() );
-                                       break;
-                               case 3:
-                                       System.out.println( "          length: " + f.length() );
-                                       break;
-                               case 4:
-                                       System.out.println( " getLastModified: " + sdf.format( new Date( f.getLastModified() )));
-                                       break;
-                               case 5:
-                                       System.out.println( "        isHidden: " + f.isHidden() );
-                                       break;
-                               case 6:
-                                       System.out.println( "          isFile: " + f.isFile() );
-                                       break;
-                               case 7:
-                                       System.out.println( "     isDirectory: " + f.isDirectory() );
-                                       break;
-                               case 8:
-                                       System.out.println( "        hashCode: " + f.hashCode() );
-                                       break;
-                               case 9:
-                                       System.out.println( "      getUncPath: " + f.getUncPath() );
-                                       break;
-                               case 10:
-                                       System.out.println( "         getType: " + getTypeName(f.getType()));
-                                       break;
-                               case 11:
-                                       System.out.println( "        getShare: " + f.getShare() );
-                                       break;
-                               case 12:
-                                       System.out.println( "       getServer: " + f.getServer() );
-                                       break;
-                               case 13:
-                                       System.out.println( "         getPath: " + f.getPath() );
-                                       break;
-                               case 14:
-                                       System.out.println( "       getParent: " + f.getParent() );
-                                       break;
-                               case 15:
-                                       System.out.println( "    lastModified: " + + f.lastModified() + ": " + sdf.format( new Date( f.lastModified() )));
-                                       break;
-                               case 16:
-                                       System.out.println( "getDiskFreeSpace: " + f.getDiskFreeSpace() );
-                                       break;
-                               case 17:
-                                       System.out.println( "         getDate: " + sdf.format( new Date( f.getDate() )));
-                                       break;
-                               case 18:
-                                       System.out.println( "getContentLength: " + f.getContentLength() );
-                                       break;
-                               case 19:
-                                       System.out.println( "getCanonicalPath: " + f.getCanonicalPath() );
-                                       break;
-                               case 20:
-                                       System.out.println( "          exists: " + f.exists() );
-                                       break;
-                               case 21:
-                                       System.out.println( "         canRead: " + f.canRead() );
-                                       break;
-                               case 22:
-                                       System.out.println( "        canWrite: " + f.canWrite() );
-                                       break;
-                               case 23:
-                                       System.out.println( "      createTime: " + + f.createTime() + ": " + sdf.format( new Date( f.createTime() )));
-                                       break;
-                       }
-                       i++;
-                       if( i == 24 ) {
-                               i = 0;
-                       }
-               } while( i != end );
-       }
+        i = end = start;
+        do {
+            switch( i ) {
+                case 0:
+                    System.out.println( "        toString: " + f.toString() );
+                    break;
+                case 1:
+                    System.out.println( "           toURL: " + f.toURL() );
+                    break;
+                case 2:
+                    System.out.println( "         getName: " + f.getName() );
+                    break;
+                case 3:
+                    System.out.println( "          length: " + f.length() );
+                    break;
+                case 4:
+                    System.out.println( " getLastModified: " + sdf.format( new Date( f.getLastModified() )));
+                    break;
+                case 5:
+                    System.out.println( "        isHidden: " + f.isHidden() );
+                    break;
+                case 6:
+                    System.out.println( "          isFile: " + f.isFile() );
+                    break;
+                case 7:
+                    System.out.println( "     isDirectory: " + f.isDirectory() );
+                    break;
+                case 8:
+                    System.out.println( "        hashCode: " + f.hashCode() );
+                    break;
+                case 9:
+                    System.out.println( "      getUncPath: " + f.getUncPath() );
+                    break;
+                case 10:
+                    System.out.println( "         getType: " + TYPES[f.getType()] );
+                    break;
+                case 11:
+                    System.out.println( "        getShare: " + f.getShare() );
+                    break;
+                case 12:
+                    System.out.println( "       getServer: " + f.getServer() );
+                    break;
+                case 13:
+                    System.out.println( "         getPath: " + f.getPath() );
+                    break;
+                case 14:
+                    System.out.println( "       getParent: " + f.getParent() );
+                    break;
+                case 15:
+                    System.out.println( "    lastModified: " + sdf.format( new Date( f.lastModified() )));
+                    break;
+                case 16:
+                    System.out.println( "getDiskFreeSpace: " + f.getDiskFreeSpace() );
+                    break;
+                case 17:
+                    System.out.println( "         getDate: " + sdf.format( new Date( f.getDate() )));
+                    break;
+                case 18:
+                    System.out.println( "getContentLength: " + f.getContentLength() );
+                    break;
+                case 19:
+                    System.out.println( "getCanonicalPath: " + f.getCanonicalPath() );
+                    break;
+                case 20:
+                    System.out.println( "          exists: " + f.exists() );
+                    break;
+                case 21:
+                    System.out.println( "         canRead: " + f.canRead() );
+                    break;
+                case 22:
+                    System.out.println( "        canWrite: " + f.canWrite() );
+                    break;
+            }
+            i++;
+            if( i == 23 ) {
+                i = 0;
+            }
+        } while( i != end );
+    }
 }
 
index 931accf..e26dc00 100644 (file)
@@ -26,7 +26,7 @@
  * length
  *     the file was created to be no larger than ~2G and reports back the size specified
  * mkdir
- *     true  - a directory was created successfully
+ *     true  - a directory was created successfuly
  *     false - the directory could not be created
  * renameTo
  *     true  - the target was renamed
 
 import jcifs.smb.*;
 import java.io.IOException;
+import java.util.Date;
 
 public class FileOps {
 
-       public static void main( String argv[] ) throws Exception {
+    static final int ATTR_ALL = SmbFile.ATTR_ARCHIVE | SmbFile.ATTR_HIDDEN | SmbFile.ATTR_READONLY | SmbFile.ATTR_SYSTEM;
 
-               if( argv.length != 1 ) {
-                       System.out.println( "Must provide an SMB URL of a remote location on which tests will be conducted." );
-                       System.exit( 1 );
-               }
-
-               SmbFile s = new SmbFile( argv[0] );
-               SmbFile d = new SmbFile( s, "JcifsTestOpsDir/" );
+    public static void main( String argv[] ) throws Exception {
 
-       // delete - Delete the directory if it exists
+        if( argv.length != 1 ) {
+            System.out.println( "Must provide an SMB URL of a remote location on which tests will be conducted." );
+            System.exit( 1 );
+        }
+
+        SmbFile s = new SmbFile( argv[0] );
+        SmbFile d = new SmbFile( s, "JcifsTestOpsDir/" );
+
+    // delete - Delete the directory if it exists
 
-               try {
-                       d.delete();
-               } catch( SmbException se ) {
-                       System.out.println( "okay - delete " + d + " failed: " + se.getMessage() );
-               }
-               System.out.println( "okay - delete " + d + " successfull" );
-
-       // exists - Test the directory that should not exist
-
-               if( d.exists() ) {
-                       System.out.println( "fail - " + d + " still exists" );
-                       System.exit( 1 );
-               } else {
-                       System.out.println( "okay - " + d + " does not exist" );
-               }
-
-       // mkdir - Create the directory
+        try {
+            d.delete();
+        } catch( SmbException se ) {
+            System.out.println( "okay - delete " + d + " failed: " + se.getMessage() );
+        }
+        System.out.println( "okay - delete " + d + " successful" );
+
+    // exists - Test the directory that should not exist
+
+        if( d.exists() ) {
+            System.out.println( "fail - " + d + " still exists" );
+            System.exit( 1 );
+        } else {
+            System.out.println( "okay - " + d + " does not exist" );
+        }
+
+    // mkdir - Create the directory
+
+        d.mkdir();
+        System.out.println( "okay - mkdir " + d + " successful" );
+
+    // exist - Test the directory which should exist now
+
+        if( d.exists() ) {
+            System.out.println( "okay - " + d + " exists" );
+        } else {
+            System.out.println( "fail - " + d + " was not successfuly created" );
+            System.exit( 1 );
+        }
+
+    // mkdir - Try to create a directory even though it already exists
+
+        try {
+            d.mkdir();
+            System.out.println( "fail - mkdir " + d + " successful" );
+            System.exit( 1 );
+        } catch( SmbException se ) {
+            System.out.println( "okay - mkdir " + d + " failed: " + se.getMessage() );
+        }
+
+    // Create a file to test against
+
+    SmbFile f = null;
+    try {
+        f = new SmbFile( d, "foo.txt" );
+        SmbFileOutputStream o = new SmbFileOutputStream( f );
+        o.write( "The Common Internet File System (CIFS) is the de-facto file sharing protocol on the Microsoft Windows platform. It is the underlying networking protocol used when accessing shares with Windows Explorer, the Network Neighborhood, via a Map Network Drive...  dialog, the C:\\> net use * \\\\server\\share commands, or smbclient on UNIX, smbfs on Linux, and elsewhere.\r\n".getBytes() );
+        o.close();
+    } catch( IOException ioe ) {
+        System.out.println( "fail - could not create file " + d + "foo.txt: " + ioe.getMessage() );
+    }
+    System.out.println( "okay - created file " + d + "foo.txt" );
+
+    // canRead - Test to see if the new file can be read
+
+        if( f.canRead() ) {
+            System.out.println( "okay - canRead " + f + " successful" );
+        } else {
+            System.out.println( "fail - canRead " + f + " failed" );
+            System.exit( 1 );
+        }
+
+    // canWrite, getAttributes - Test the file for writing
+
+        if( f.canWrite() && (f.getAttributes() & SmbFile.ATTR_READONLY) == 0 ) {
+            System.out.println( "okay - canWrite " + f + " successful" );
+        } else {
+            System.out.println( "fail - canWrite " + f + " failed" );
+            System.exit( 1 );
+        }
+
+    // setReadOnly
+
+        try {
+            f.setReadOnly();
+            System.out.println( "okay - setReadOnly " + f + " successful" );
+        } catch( SmbException se ) {
+            System.out.println( "fail - setReadOnly " + f + " failed: " + se.getMessage() );
+        }
+
+    // canWrite - Test the file for writing
+
+        if( f.canWrite() ) {
+            System.out.println( "fail - canWrite " + f + " returned true but it should have been marked read-only ... continuing on" );
+        } else {
+            System.out.println( "okay - canWrite " + f + " failed" );
+        }
+
+    // Try to open the file for writing
+
+        try {
+            SmbFileOutputStream w = new SmbFileOutputStream( f );
+            w.close();
+            System.out.println( "fail - successfuly opened " + f + " for writing even though it should be marked read-only ... continuing on" );
+        } catch( IOException ioe ) {
+            System.out.println( "okay - correctly failed to open " + f + " for writing: " + ioe.getMessage() );
+        }
+
+    // renameTo - rename the file to bar.txt
+
+        SmbFile b = new SmbFile( d, "bar.txt" );
+
+        try {
+            f.renameTo( b );
+            System.out.println( "okay - renameTo " + f + " to " + b + " successful even with read-only" );
+            try {
+                b.renameTo(f);
+            } catch( SmbException se ) {
+                System.out.println( "fail - but failed to rename file back to original!" );
+                throw se;
+            }
+        } catch( SmbException se ) {
+            System.out.println( "fail - renameTo " + f + " should have been successful even though the file is marked read-only: " + se.getMessage() );
+        }
+
+    // setAttributes
+
+        try {
+            f.setAttributes( 0xFFFF );
+            System.out.println( "okay - setAttributes " + f + " successful" );
+        } catch( SmbException se ) {
+            System.out.println( "fail - setAttributes " + f + " failed: " + se.getMessage() );
+        }
+
+    // getAttributes
+
+        int attr;
+
+        if((( attr = f.getAttributes() ) & ATTR_ALL ) == ATTR_ALL ) {
+            System.out.println( "okay - getAttributes " + f + " successful" );
+        } else {
+            System.out.println( "fail - getAttributes " + f + " failed: 0x" + jcifs.util.Hexdump.toHexString( attr, 4 ));
+            System.exit( 1 );
+        }
+
+    // isHidden - Test to see if the file is hidden
+
+        if( f.isHidden() ) {
+            System.out.println( "okay - isHidden " + f + " is hidden" );
+        } else {
+            System.out.println( "fail - isHidden " + f + " is not hidden but it should be ... continuing on" );
+        }
+
+    // canRead - Test canRead again with both hidden and read-only on
+
+        if( f.canRead() ) {
+            System.out.println( "okay - canRead " + f + " was successful with read-only and hidden both on" );
+        } else {
+            System.out.println( "fail - canRead " + f + " failed with read-only and hidden both on" );
+        }
+
+    // canWrite - Test the file for writing again with read-only and hidden
+
+        if( f.canWrite() ) {
+            System.out.println( "fail - canWrite " + f + " was successful even though read-only is set ... continuing on" );
+        } else {
+            System.out.println( "okay - canWrite " + f + " failed as it should being that read-only is set" );
+        }
+
+    // isDirectory - Test file as a directory
+
+        if( f.isDirectory() ) {
+            System.out.println( "fail - isDirectory " + f + " returned true but it is NOT a directory" );
+        } else {
+            System.out.println( "okay - isDirectory " + f + " is not a directory" );
+        }
+
+    // isDirectory - Test directory as a directory
 
-               d.mkdir();
-               System.out.println( "okay - mkdir " + d + " successfull" );
-
-       // exist - Test the directory which should exist now
-
-               if( d.exists() ) {
-                       System.out.println( "okay - " + d + " exists" );
-               } else {
-                       System.out.println( "fail - " + d + " was not successfully created" );
-                       System.exit( 1 );
-               }
-
-       // mkdir - Try to create a directory even though it already exists
-
-               try {
-                       d.mkdir();
-                       System.out.println( "fail - mkdir " + d + " successfull" );
-                       System.exit( 1 );
-               } catch( SmbException se ) {
-                       System.out.println( "okay - mkdir " + d + " failed: " + se.getMessage() );
-               }
-
-       // Create a file to test against
+        if( d.isDirectory() ) {
+            System.out.println( "okay - isDirectory " + d + " is a directory" );
+        } else {
+            System.out.println( "fail - isDirectory " + d + " returned false but it really is a directory" );
+        }
+
+    // isDirectory - Test directory that does not exist
+
+        b = new SmbFile( d, "bogus" );
 
-       SmbFile f = null;
-       try {
-               f = new SmbFile( d, "foo.txt" );
-               SmbFileOutputStream o = new SmbFileOutputStream( f );
-               o.write( "The Common Internet File System (CIFS) is the de-facto file sharing protocol on the Microsoft Windows platform. It is the underlying networking protocol used when accessing shares with Windows Explorer, the Network Neighborhood, via a Map Network Drive...  dialog, the C:\\> net use * \\\\server\\share commands, or smbclient on UNIX, smbfs on Linux, and elsewhere.\r\n".getBytes() );
-               o.close();
-       } catch( IOException ioe ) {
-               System.out.println( "fail - could not create file " + d + "foo.txt: " + ioe.getMessage() );
-       }
-       System.out.println( "okay - created file " + d + "foo.txt" );
-
-       // canRead - Test to see if the new file can be read
-
-               if( f.canRead() ) {
-                       System.out.println( "okay - canRead " + f + " successfull" );
-               } else {
-                       System.out.println( "fail - canRead " + f + " failed" );
-                       System.exit( 1 );
-               }
+        if( b.isDirectory() ) {
+            System.out.println( "fail - isDirectory " + b + " returned true but it does not exist" );
+        } else {
+            System.out.println( "okay - isDirectory " + b + " does not exist" );
+        }
+
+    // isFile - Test file as a file
 
-       // canWrite - Test the file for writing
-
-               if( f.canWrite() ) {
-                       System.out.println( "okay - canWrite " + f + " successfull" );
-               } else {
-                       System.out.println( "fail - canWrite " + f + " failed" );
-                       System.exit( 1 );
-               }
-
-       // ASK USER TO FLIP ON READ-ONLY
-
-               System.out.println( "Please change the file " + f + " to read-only (hit return to continue)" );
-               System.in.read();
+        if( f.isFile() ) {
+            System.out.println( "okay - isFile " + f + " is a file" );
+        } else {
+            System.out.println( "fail - isFile " + f + " return false but it is NOT a file" );
+        }
+
+    // isFile - Test directory as a file
+
+        if( d.isFile() ) {
+            System.out.println( "fail - isFile " + d + " returned true but it is NOT a file" );
+        } else {
+            System.out.println( "okay - isFile " + d + " is not a file" );
+        }
+
+    // length - Check to ensure that the length of the file is correct
+
+        if( f.length() == 363 ) {
+            System.out.println( "okay - length " + f + " is correct" );
+        } else {
+            System.out.println( "fail - length " + f + " is wrong: " + f.length() );
+        }
+
+    // setReadWrite
+
+        try {
+            f.setReadWrite();
+            System.out.println( "okay - setReadWrite " + f + " successful" );
+        } catch( SmbException se ) {
+            System.out.println( "fail - setReadWrite " + f + " failed: " + se.getMessage() );
+        }
+
+    // setLastModified
 
-       // canWrite - Test the file for writing
+        long t = (new Date()).getTime() - 1000 * 60;
 
-               if( f.canWrite() ) {
-                       System.out.println( "fail - canWrite " + f + " returned true but it should have been marked read-only ... continuing on" );
-               } else {
-                       System.out.println( "okay - canWrite " + f + " failed" );
-               }
+        try {
+            f.setLastModified( t );
+            System.out.println( "okay - setLastModified " + f + " successful" );
+        } catch( SmbException se ) {
+            System.out.println( "fail - setLastModified " + f + " failed: " + se.getMessage() );
+        }
+
+    // lastModified
+
+        if( f.lastModified() == t ) {
+            System.out.println( "okay - lastModified " + f + " is correct" );
+        } else {
+            System.out.println( "fail - lastModified " + f + " is wrong: " + f.lastModified() + " vs " + t );
+        }
 
-       // Try to open the file for writing
+    // setCreateTime
+
+        try {
+            f.setCreateTime( t );
+            System.out.println( "okay - setCreateTime " + f + " successful" );
+        } catch( SmbException se ) {
+            System.out.println( "fail - setCreateTime " + f + " failed: " + se.getMessage() );
+        }
+
+    // createTime
 
-               try {
-                       SmbFileOutputStream w = new SmbFileOutputStream( f );
-                       w.close();
-                       System.out.println( "fail - successfully opened " + f + " for writing even though it should be marked read-only ... continuing on" );
-               } catch( IOException ioe ) {
-                       System.out.println( "okay - correctly failed to open " + f + " for writing: " + ioe.getMessage() );
-               }
-
-       // renameTo - rename the file to bar.txt
-
-               SmbFile b = new SmbFile( d, "bar.txt" );
+        if( f.createTime() == t ) {
+            System.out.println( "okay - createTime " + f + " is correct" );
+        } else {
+            System.out.println( "fail - createTime " + f + " is wrong: " + f.createTime() + " vs " + t );
+        }
+
+    // createNewFile
 
-               try {
-                       f.renameTo( b );
-                       System.out.println( "okay - renameTo " + f + " to " + b + " successfull even with read-only" );
-                       try {
-                               b.renameTo(f);
-                       } catch( SmbException se ) {
-                               System.out.println( "fail - but failed to rename file back to original!" );
-                               throw se;
-                       }
-               } catch( SmbException se ) {
-                       System.out.println( "fail - renameTo " + f + " should have been successfull even though the file is marked read-only: " + se.getMessage() );
-               }
-
-       // ASK USER TO FLIP ON HIDDEN FLAG
-
-               System.out.println( "Please turn on the hidden attribute for " + f + " (hit return to continue)" );
-               System.in.read();
+    // delete - See if we can delete the file even though it's read-only
 
-       // isHidden - Test to see if the file is hidden
+        try {
+            f.delete();
+            System.out.println( "okay - delete " + f + " successful even though the file was read-only" );
+        } catch( SmbException se ) {
+            System.out.println( "fail - delete " + f + " should have turned off the read-only attribute to deleted the file: " + se.getMessage() );
+        }
 
-               if( f.isHidden() ) {
-                       System.out.println( "okay - isHidden " + f + " is hidden" );
-               } else {
-                       System.out.println( "fail - isHidden " + f + " is not hidden but it should be ... continuing on" );
-               }
-
-       // canRead - Test canRead again with both hidden and read-only on
-
-               if( f.canRead() ) {
-                       System.out.println( "okay - canRead " + f + " was successfull with read-only and hidden both on" );
-               } else {
-                       System.out.println( "fail - canRead " + f + " failed with read-only and hidden both on" );
-               }
-
-       // canWrite - Test the file for writing again with read-only and hidden
-
-               if( f.canWrite() ) {
-                       System.out.println( "fail - canWrite " + f + " was successfull even though read-only is set ... continuing on" );
-               } else {
-                       System.out.println( "okay - canWrite " + f + " failed as it should being that read-only is set" );
-               }
-
-       // isDirectory - Test file as a directory
-
-               if( f.isDirectory() ) {
-                       System.out.println( "fail - isDirectory " + f + " returned true but it is NOT a directory" );
-               } else {
-                       System.out.println( "okay - isDirectory " + f + " is not a directory" );
-               }
-
-       // isDirectory - Test directory as a directory
-
-               if( d.isDirectory() ) {
-                       System.out.println( "okay - isDirectory " + d + " is a directory" );
-               } else {
-                       System.out.println( "fail - isDirectory " + d + " returned false but it really is a directory" );
-               }
-
-       // isDirectory - Test directory that does not exist
-
-               b = new SmbFile( d, "bogus" );
+        SmbFile r = new SmbFile( d.getParent(), "JcifsDeleteMe/" );
 
-               if( b.isDirectory() ) {
-                       System.out.println( "fail - isDirectory " + b + " returned true but it does not exist" );
-               } else {
-                       System.out.println( "okay - isDirectory " + b + " does not exist" );
-               }
-
-       // isFile - Test file as a file
+    // Must delete any left over directory from a previous run
 
-               if( f.isFile() ) {
-                       System.out.println( "okay - isFile " + f + " is a file" );
-               } else {
-                       System.out.println( "fail - isFile " + f + " return false but it is NOT a file" );
-               }
-
-       // isFile - Test directory as a file
+        try {
+            r.delete();
+            System.out.println( "okay - delete " + r + " successful" );
+        } catch( SmbException se ) {
+            System.out.println( "okay - delete " + r + " probably wasn't there: " + se.getMessage() );
+        }
 
-               if( d.isFile() ) {
-                       System.out.println( "fail - isFile " + d + " returned true but it is NOT a file" );
-               } else {
-                       System.out.println( "okay - isFile " + d + " is not a file" );
-               }
-
-       // delete - See if we can delete the file even though it's read-only
+    // renameTo - Rename the whole directory to JcifsDeleteMe
+
+        try {
+            d.renameTo( r );
+            System.out.println( "okay - renameTo " + d + " successful even though it is a directory" );
+        } catch( SmbException se ) {
+            System.out.println( "fail - renameTo " + d + " failed: " + se.getMessage() );
+        }
 
-               try {
-                       f.delete();
-                       System.out.println( "fail - delete " + f + " should not have been successfull because it is read-only" );
-               } catch( SmbException se ) {
-                       System.out.println( "okay - delete " + f + " failed because it is read-only: " + se.getMessage() );
-               }
-
-       // Flip off both read-only and hidden
-
-               System.out.println( "Flipp off both read-only and hidden flags for " + f + " (hit return to continue)" );
-               System.in.read();
-
-       // length - Check to ensure that the length of the file is correct
-
-               if( f.length() == 363 ) {
-                       System.out.println( "okay - length " + f + " is correct" );
-               } else {
-                       System.out.println( "fail - length " + f + " is wrong: " + f.length() );
-               }
-
-               SmbFile r = new SmbFile( d.getParent(), "JcifsDeleteMe/" );
-
-       // Must delete any left over directory from a previous run
-
-               try {
-                       r.delete();
-                       System.out.println( "okay - delete " + r + " successfull" );
-               } catch( SmbException se ) {
-                       System.out.println( "okay - delete " + r + " probably wasn't there: " + se.getMessage() );
-               }
-
-       // renameTo - Rename the whole directory to JcifsDeleteMe
-
-               try {
-                       d.renameTo( r );
-                       System.out.println( "okay - renameTo " + d + " successfull even though it is a directory" );
-               } catch( SmbException se ) {
-                       System.out.println( "fail - renameTo " + d + " failed: " + se.getMessage() );
-               }
-
-       // delete - Now delete the whole workspace
-
-               try {
-                       r.delete();
-                       System.out.println( "okay - delete " + r + " successfull" );
-               } catch( SmbException se ) {
-                       System.out.println( "fail - delete " + r + " failed: " + se.getMessage() );
-               }
-       }
+    // delete - Now delete the whole workspace
+
+        try {
+            r.delete();
+            System.out.println( "okay - delete " + r + " successful" );
+        } catch( SmbException se ) {
+            System.out.println( "fail - delete " + r + " failed: " + se.getMessage() );
+        }
+    }
 }
 
index 018169e..3cddc99 100644 (file)
@@ -1,37 +1,36 @@
 import jcifs.netbios.NbtAddress;
 import jcifs.smb.*;
-import jcifs.util.Log;
 import java.util.Date;
 
 public class FilterFiles {
 
-       static class ShortFilenameFilter implements SmbFilenameFilter {
-               public boolean accept( SmbFile dir, String name ) throws SmbException {
-                       return name.length() < 9;
-               }
-       }
-       static class BigFileFilter implements SmbFileFilter {
-               public boolean accept( SmbFile file ) throws SmbException {
-                       return file.length() > 0x1FFFFL;
-               }
-       }
+    static class ShortFilenameFilter implements SmbFilenameFilter {
+        public boolean accept( SmbFile dir, String name ) throws SmbException {
+            return name.length() < 9;
+        }
+    }
+    static class BigFileFilter implements SmbFileFilter {
+        public boolean accept( SmbFile file ) throws SmbException {
+            return file.length() > 0x1FFFFL;
+        }
+    }
 
-       public static void main( String[] argv ) throws Exception {
+    public static void main( String[] argv ) throws Exception {
 
-               SmbFile file = new SmbFile( argv[0] );
-               BigFileFilter filter = new BigFileFilter();
-               DosFileFilter everything = new DosFileFilter( "*",
-                               SmbFile.ATTR_DIRECTORY | SmbFile.ATTR_HIDDEN | SmbFile.ATTR_SYSTEM );
+        SmbFile file = new SmbFile( argv[0] );
+        BigFileFilter filter = new BigFileFilter();
+        DosFileFilter everything = new DosFileFilter( "*",
+                SmbFile.ATTR_DIRECTORY | SmbFile.ATTR_HIDDEN | SmbFile.ATTR_SYSTEM );
 
-               long t1 = System.currentTimeMillis();
-               SmbFile[] files = file.listFiles( everything );
-               long t2 = System.currentTimeMillis() - t1;
+        long t1 = System.currentTimeMillis();
+        SmbFile[] files = file.listFiles( everything );
+        long t2 = System.currentTimeMillis() - t1;
 
-               for( int i = 0; i < files.length; i++ ) {
-                       System.out.print( " " + files[i].getName() );
-               }
-               System.out.println();
-               System.out.println( files.length + " files in " + t2 + "ms" );
-       }
+        for( int i = 0; i < files.length; i++ ) {
+            System.out.print( " " + files[i].getName() );
+        }
+        System.out.println();
+        System.out.println( files.length + " files in " + t2 + "ms" );
+    }
 }
 
index 941f726..a04e50e 100644 (file)
-/*\r
- * Cay S. Horstmann & Gary Cornell, Core Java\r
- * Published By Sun Microsystems Press/Prentice-Hall\r
- * Copyright (C) 1997 Sun Microsystems Inc.\r
- * All Rights Reserved.\r
- *\r
- * Permission to use, copy, modify, and distribute this \r
- * software and its documentation for NON-COMMERCIAL purposes\r
- * and without fee is hereby granted provided that this \r
- * copyright notice appears in all copies. \r
- * \r
- * THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR \r
- * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER \r
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE \r
- * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A \r
- * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS\r
- * AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED \r
- * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING \r
- * THIS SOFTWARE OR ITS DERIVATIVES.\r
- */\r
\r
-/**\r
- * A class for formatting numbers that follows printf conventions.\r
- * Also implements C-like atoi and atof functions\r
- * @version 1.04 13 Sep 1998\r
- * @author Cay Horstmann\r
- */\r
-\r
-import java.io.*;\r
-\r
-public class Format\r
-\r
-{ /** \r
-  * Formats the number following printf conventions.\r
-  * Main limitation: Can only handle one format parameter at a time\r
-  * Use multiple Format objects to format more than one number\r
-  * @param s the format string following printf conventions\r
-  * The string has a prefix, a format code and a suffix. The prefix and suffix\r
-  * become part of the formatted output. The format code directs the\r
-  * formatting of the (single) parameter to be formatted. The code has the\r
-  * following structure\r
-  * <ul>\r
-  * <li> a % (required)\r
-  * <li> a modifier (optional)\r
-  * <dl>\r
-  * <dt> + <dd> forces display of + for positive numbers\r
-  * <dt> 0 <dd> show leading zeroes\r
-  * <dt> - <dd> align left in the field\r
-  * <dt> space <dd> prepend a space in front of positive numbers\r
-  * <dt> # <dd> use "alternate" format. Add 0 or 0x for octal or hexadecimal numbers. Don't suppress trailing zeroes in general floating point format.\r
-  * </dl>\r
-  * <li> an integer denoting field width (optional)\r
-  * <li> a period followed by an integer denoting precision (optional)\r
-  * <li> a format descriptor (required)\r
-  * <dl>\r
-  * <dt>f <dd> floating point number in fixed format\r
-  * <dt>e, E <dd> floating point number in exponential notation (scientific format). The E format results in an uppercase E for the exponent (1.14130E+003), the e format in a lowercase e.\r
-  * <dt>g, G <dd> floating point number in general format (fixed format for small numbers, exponential format for large numbers). Trailing zeroes are suppressed. The G format results in an uppercase E for the exponent (if any), the g format in a lowercase e.\r
-  * <dt>d, i <dd> integer in decimal\r
-  * <dt>x <dd> integer in hexadecimal\r
-  * <dt>o <dd> integer in octal\r
-  * <dt>s <dd> string\r
-  * <dt>c <dd> character\r
-  * </dl>\r
-  * </ul>\r
-  * @exception IllegalArgumentException if bad format\r
-  */\r
-\r
-   public Format(String s)\r
-   {  width = 0;\r
-      precision = -1;\r
-      pre = "";\r
-      post = "";\r
-      leading_zeroes = false;\r
-      show_plus = false;\r
-      alternate = false;\r
-      show_space = false;\r
-      left_align = false;\r
-      fmt = ' '; \r
-      \r
-      int state = 0; \r
-      int length = s.length();\r
-      int parse_state = 0; \r
-      // 0 = prefix, 1 = flags, 2 = width, 3 = precision,\r
-      // 4 = format, 5 = end\r
-      int i = 0;\r
-      \r
-      while (parse_state == 0)\r
-      {  if (i >= length) parse_state = 5;\r
-         else if (s.charAt(i) == '%')\r
-         {  if (i < length - 1)\r
-            {  if (s.charAt(i + 1) == '%')\r
-               {  pre = pre + '%';\r
-                  i++;\r
-               }\r
-               else\r
-                  parse_state = 1;\r
-            }\r
-            else throw new java.lang.IllegalArgumentException();\r
-         }\r
-         else\r
-            pre = pre + s.charAt(i);\r
-         i++;\r
-      }\r
-      while (parse_state == 1)\r
-      {  if (i >= length) parse_state = 5;\r
-         else if (s.charAt(i) == ' ') show_space = true;\r
-         else if (s.charAt(i) == '-') left_align = true; \r
-         else if (s.charAt(i) == '+') show_plus = true;\r
-         else if (s.charAt(i) == '0') leading_zeroes = true;\r
-         else if (s.charAt(i) == '#') alternate = true;\r
-         else { parse_state = 2; i--; }\r
-         i++;\r
-      }      \r
-      while (parse_state == 2)\r
-      {  if (i >= length) parse_state = 5;\r
-         else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')\r
-         {  width = width * 10 + s.charAt(i) - '0';\r
-            i++;\r
-         }\r
-         else if (s.charAt(i) == '.')\r
-         {  parse_state = 3;\r
-            precision = 0;\r
-            i++;\r
-         }\r
-         else \r
-            parse_state = 4;            \r
-      }\r
-      while (parse_state == 3)\r
-      {  if (i >= length) parse_state = 5;\r
-         else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')\r
-         {  precision = precision * 10 + s.charAt(i) - '0';\r
-            i++;\r
-         }\r
-         else \r
-            parse_state = 4;                  \r
-      }\r
-      if (parse_state == 4) \r
-      {  if (i >= length) parse_state = 5;\r
-         else fmt = s.charAt(i);\r
-         i++;\r
-      }\r
-      if (i < length)\r
-         post = s.substring(i, length);\r
-   }      \r
-\r
-  /** \r
-  * prints a formatted number following printf conventions\r
-  * @param s a PrintStream\r
-  * @param fmt the format string\r
-  * @param x the double to print\r
-  */\r
-  \r
-   public static void print(java.io.PrintStream s, String fmt, double x)\r
-   {  s.print(new Format(fmt).form(x));\r
-   }\r
-\r
-  /** \r
-  * prints a formatted number following printf conventions\r
-  * @param s a PrintStream\r
-  * @param fmt the format string\r
-  * @param x the long to print\r
-  */\r
-  public static void print(java.io.PrintStream s, String fmt, long x)\r
-   {  s.print(new Format(fmt).form(x));\r
-   }\r
-\r
-  /** \r
-  * prints a formatted number following printf conventions\r
-  * @param s a PrintStream\r
-  * @param fmt the format string\r
-  * @param x the character to \r
-  */\r
-  \r
-   public static void print(java.io.PrintStream s, String fmt, char x)\r
-   {  s.print(new Format(fmt).form(x));\r
-   }\r
-\r
-  /** \r
-  * prints a formatted number following printf conventions\r
-  * @param s a PrintStream, fmt the format string\r
-  * @param x a string that represents the digits to print\r
-  */\r
-  \r
-   public static void print(java.io.PrintStream s, String fmt, String x)\r
-   {  s.print(new Format(fmt).form(x));\r
-   }\r
-   \r
-  /** \r
-  * Converts a string of digits (decimal, octal or hex) to an integer\r
-  * @param s a string\r
-  * @return the numeric value of the prefix of s representing a base 10 integer\r
-  */\r
-  \r
-   public static int atoi(String s)\r
-   {  return (int)atol(s);\r
-   } \r
-   \r
-  /** \r
-  * Converts a string of digits (decimal, octal or hex) to a long integer\r
-  * @param s a string\r
-  * @return the numeric value of the prefix of s representing a base 10 integer\r
-  */\r
-  \r
-   public static long atol(String s)\r
-   {  int i = 0;\r
-\r
-      while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;\r
-      if (i < s.length() && s.charAt(i) == '0')\r
-      {  if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X'))\r
-            return parseLong(s.substring(i + 2), 16);\r
-         else return parseLong(s, 8);\r
-      }\r
-      else return parseLong(s, 10);\r
-   }\r
-\r
-   private static long parseLong(String s, int base)\r
-   {  int i = 0;\r
-      int sign = 1;\r
-      long r = 0;\r
-      \r
-      while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;\r
-      if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }\r
-      else if (i < s.length() && s.charAt(i) == '+') { i++; }\r
-      while (i < s.length())\r
-      {  char ch = s.charAt(i);\r
-         if ('0' <= ch && ch < '0' + base)\r
-            r = r * base + ch - '0';\r
-         else if ('A' <= ch && ch < 'A' + base - 10)\r
-            r = r * base + ch - 'A' + 10 ;\r
-         else if ('a' <= ch && ch < 'a' + base - 10)\r
-            r = r * base + ch - 'a' + 10 ;\r
-         else \r
-            return r * sign;\r
-         i++;\r
-      }\r
-      return r * sign;      \r
-   }\r
-      \r
-   /** \r
-   * Converts a string of digits to an double\r
-   * @param s a string\r
-   */\r
-   \r
-   public static double atof(String s)\r
-   {  int i = 0;\r
-      int sign = 1;\r
-      double r = 0; // integer part\r
-      double f = 0; // fractional part\r
-      double p = 1; // exponent of fractional part\r
-      int state = 0; // 0 = int part, 1 = frac part\r
-      \r
-      while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;\r
-      if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }\r
-      else if (i < s.length() && s.charAt(i) == '+') { i++; }\r
-      while (i < s.length())\r
-      {  char ch = s.charAt(i);\r
-         if ('0' <= ch && ch <= '9')\r
-         {  if (state == 0)\r
-               r = r * 10 + ch - '0';\r
-            else if (state == 1)\r
-            {  p = p / 10;\r
-               r = r + p * (ch - '0');\r
-            }\r
-         }\r
-         else if (ch == '.') \r
-         {  if (state == 0) state = 1; \r
-            else return sign * r;\r
-         }\r
-         else if (ch == 'e' || ch == 'E')\r
-         {  long e = (int)parseLong(s.substring(i + 1), 10);\r
-            return sign * r * Math.pow(10, e);\r
-         }\r
-         else return sign * r;\r
-         i++;\r
-      }\r
-      return sign * r;\r
-   }\r
-            \r
-   /** \r
-   * Formats a double into a string (like sprintf in C)\r
-   * @param x the number to format\r
-   * @return the formatted string \r
-   * @exception IllegalArgumentException if bad argument\r
-   */\r
-   \r
-   public String form(double x)\r
-   {  String r;\r
-      if (precision < 0) precision = 6;\r
-      int s = 1;\r
-      if (x < 0) { x = -x; s = -1; }\r
-      if (fmt == 'f')\r
-         r = fixed_format(x);\r
-      else if (fmt == 'e' || fmt == 'E' || fmt == 'g' || fmt == 'G')\r
-         r = exp_format(x);\r
-      else throw new java.lang.IllegalArgumentException();\r
-      \r
-      return pad(sign(s, r));\r
-   }\r
-   \r
-   /** \r
-   * Formats a long integer into a string (like sprintf in C)\r
-   * @param x the number to format\r
-   * @return the formatted string \r
-   */\r
-   \r
-   public String form(long x)\r
-   {  String r; \r
-      int s = 0;\r
-      if (fmt == 'd' || fmt == 'i')\r
-      {  if (x < 0) \r
-         {  r = ("" + x).substring(1);\r
-            s = -1; \r
-         }\r
-         else \r
-         {  r = "" + x; \r
-            s = 1;\r
-         }\r
-      }\r
-      else if (fmt == 'o')\r
-         r = convert(x, 3, 7, "01234567");\r
-      else if (fmt == 'x')\r
-         r = convert(x, 4, 15, "0123456789abcdef");\r
-      else if (fmt == 'X')\r
-         r = convert(x, 4, 15, "0123456789ABCDEF");\r
-      else throw new java.lang.IllegalArgumentException();\r
-         \r
-      return pad(sign(s, r));\r
-   }\r
-   \r
-   /** \r
-   * Formats a character into a string (like sprintf in C)\r
-   * @param x the value to format\r
-   * @return the formatted string \r
-   */\r
-   \r
-   public String form(char c)\r
-   {  if (fmt != 'c')\r
-         throw new java.lang.IllegalArgumentException();\r
-\r
-      String r = "" + c;\r
-      return pad(r);\r
-   }\r
-   \r
-   /** \r
-   * Formats a string into a larger string (like sprintf in C)\r
-   * @param x the value to format\r
-   * @return the formatted string \r
-   */\r
-   \r
-   public String form(String s)\r
-   {  if (fmt != 's')\r
-         throw new java.lang.IllegalArgumentException();\r
-      if (precision >= 0 && precision < s.length()) \r
-          s = s.substring(0, precision);\r
-      return pad(s);\r
-   }\r
-   \r
-    \r
-   /**\r
-   * a test stub for the format class\r
-   */\r
-   \r
-   public static void main(String[] a)\r
-   {  double x = 1.23456789012;\r
-      double y = 123;\r
-      double z = 1.2345e30;\r
-      double w = 1.02;\r
-      double u = 1.234e-5;\r
-      int d = 0xCAFE;\r
-      Format.print(System.out, "x = |%f|\n", x);\r
-      Format.print(System.out, "u = |%20f|\n", u);\r
-      Format.print(System.out, "x = |% .5f|\n", x);\r
-      Format.print(System.out, "w = |%20.5f|\n", w);\r
-      Format.print(System.out, "x = |%020.5f|\n", x);\r
-      Format.print(System.out, "x = |%+20.5f|\n", x);\r
-      Format.print(System.out, "x = |%+020.5f|\n", x);\r
-      Format.print(System.out, "x = |% 020.5f|\n", x);\r
-      Format.print(System.out, "y = |%#+20.5f|\n", y);\r
-      Format.print(System.out, "y = |%-+20.5f|\n", y);\r
-      Format.print(System.out, "z = |%20.5f|\n", z);\r
-      \r
-      Format.print(System.out, "x = |%e|\n", x);\r
-      Format.print(System.out, "u = |%20e|\n", u);\r
-      Format.print(System.out, "x = |% .5e|\n", x);\r
-      Format.print(System.out, "w = |%20.5e|\n", w);\r
-      Format.print(System.out, "x = |%020.5e|\n", x);\r
-      Format.print(System.out, "x = |%+20.5e|\n", x);\r
-      Format.print(System.out, "x = |%+020.5e|\n", x);\r
-      Format.print(System.out, "x = |% 020.5e|\n", x);\r
-      Format.print(System.out, "y = |%#+20.5e|\n", y);\r
-      Format.print(System.out, "y = |%-+20.5e|\n", y);\r
-      \r
-      Format.print(System.out, "x = |%g|\n", x);\r
-      Format.print(System.out, "z = |%g|\n", z);\r
-      Format.print(System.out, "w = |%g|\n", w);\r
-      Format.print(System.out, "u = |%g|\n", u);\r
-      Format.print(System.out, "y = |%.2g|\n", y);\r
-      Format.print(System.out, "y = |%#.2g|\n", y);\r
-\r
-      Format.print(System.out, "d = |%d|\n", d);\r
-      Format.print(System.out, "d = |%20d|\n", d);            \r
-      Format.print(System.out, "d = |%020d|\n", d);    \r
-      Format.print(System.out, "d = |%+20d|\n", d);\r
-      Format.print(System.out, "d = |% 020d|\n", d);\r
-      Format.print(System.out, "d = |%-20d|\n", d);\r
-      Format.print(System.out, "d = |%20.8d|\n", d);\r
-      Format.print(System.out, "d = |%x|\n", d);            \r
-      Format.print(System.out, "d = |%20X|\n", d);    \r
-      Format.print(System.out, "d = |%#20x|\n", d);\r
-      Format.print(System.out, "d = |%020X|\n", d);\r
-      Format.print(System.out, "d = |%20.8x|\n", d);\r
-      Format.print(System.out, "d = |%o|\n", d);            \r
-      Format.print(System.out, "d = |%020o|\n", d);    \r
-      Format.print(System.out, "d = |%#20o|\n", d);\r
-      Format.print(System.out, "d = |%#020o|\n", d);\r
-      Format.print(System.out, "d = |%20.12o|\n", d);\r
-      \r
-      Format.print(System.out, "s = |%-20s|\n", "Hello");      \r
-      Format.print(System.out, "s = |%-20c|\n", '!');      \r
-\r
-      // regression test to confirm fix of reported bugs\r
-\r
-      Format.print(System.out, "|%i|\n", Long.MIN_VALUE);\r
-\r
-      Format.print(System.out, "|%6.2e|\n", 0.0);\r
-      Format.print(System.out, "|%6.2g|\n", 0.0);\r
-\r
-      Format.print(System.out, "|%6.2f|\n", 9.99);\r
-      Format.print(System.out, "|%6.2f|\n", 9.999);\r
-\r
-      Format.print(System.out, "|%6.0f|\n", 9.999);\r
-   }\r
-   \r
-   private static String repeat(char c, int n)\r
-   {  if (n <= 0) return "";\r
-      StringBuffer s = new StringBuffer(n);\r
-      for (int i = 0; i < n; i++) s.append(c);\r
-      return s.toString();\r
-   }\r
-\r
-   private static String convert(long x, int n, int m, String d)\r
-   {  if (x == 0) return "0";\r
-      String r = "";\r
-      while (x != 0)\r
-      {  r = d.charAt((int)(x & m)) + r;\r
-         x = x >>> n;\r
-      }\r
-      return r;\r
-   }\r
-\r
-   private String pad(String r)\r
-   {  String p = repeat(' ', width - r.length());\r
-      if (left_align) return pre + r + p + post;\r
-      else return pre + p + r + post;\r
-   }\r
-   \r
-   private String sign(int s, String r)\r
-   {  String p = "";\r
-      if (s < 0) p = "-"; \r
-      else if (s > 0)\r
-      {  if (show_plus) p = "+";\r
-         else if (show_space) p = " ";\r
-      }\r
-      else\r
-      {  if (fmt == 'o' && alternate && r.length() > 0 && r.charAt(0) != '0') p = "0";\r
-         else if (fmt == 'x' && alternate) p = "0x";\r
-         else if (fmt == 'X' && alternate) p = "0X";\r
-      }\r
-      int w = 0;\r
-      if (leading_zeroes) \r
-         w = width;\r
-      else if ((fmt == 'd' || fmt == 'i' || fmt == 'x' || fmt == 'X' || fmt == 'o') \r
-         && precision > 0) w = precision;\r
-      \r
-      return p + repeat('0', w - p.length() - r.length()) + r;\r
-   }\r
-   \r
-   private String fixed_format(double d)\r
-   {  boolean removeTrailing\r
-         = (fmt == 'G' || fmt == 'g') && !alternate;\r
-         // remove trailing zeroes and decimal point\r
-\r
-      if (d > 0x7FFFFFFFFFFFFFFFL) return exp_format(d);\r
-      if (precision == 0) \r
-         return (long)(d + 0.5) + (removeTrailing ? "" : ".");\r
-\r
-      long whole = (long)d;\r
-      double fr = d - whole; // fractional part\r
-      if (fr >= 1 || fr < 0) return exp_format(d);\r
-\r
-      double factor = 1;\r
-      String leading_zeroes = "";\r
-      for (int i = 1; i <= precision && factor <= 0x7FFFFFFFFFFFFFFFL; i++) \r
-      {  factor *= 10; \r
-         leading_zeroes = leading_zeroes + "0"; \r
-      }\r
-      long l = (long) (factor * fr + 0.5);\r
-      if (l >= factor) { l = 0; whole++; } // CSH 10-25-97\r
-      \r
-      String z = leading_zeroes + l;\r
-      z = "." + z.substring(z.length() - precision, z.length());\r
-\r
-      if (removeTrailing)\r
-      {  int t = z.length() - 1;\r
-         while (t >= 0 && z.charAt(t) == '0') t--;\r
-         if (t >= 0 && z.charAt(t) == '.') t--;\r
-         z = z.substring(0, t + 1);\r
-      }\r
-\r
-      return whole + z;\r
-   }\r
-\r
-   private String exp_format(double d)\r
-   {  String f = "";\r
-      int e = 0;\r
-      double dd = d;\r
-      double factor = 1;\r
-      if (d != 0)\r
-      {  while (dd > 10) { e++; factor /= 10; dd = dd / 10; }\r
-         while (dd < 1) { e--; factor *= 10; dd = dd * 10; }\r
-      }\r
-      if ((fmt == 'g' || fmt == 'G') && e >= -4 && e < precision) \r
-         return fixed_format(d);\r
-      \r
-      d = d * factor;\r
-      f = f + fixed_format(d);\r
-      \r
-      if (fmt == 'e' || fmt == 'g')\r
-         f = f + "e";\r
-      else\r
-         f = f + "E";\r
-\r
-      String p = "000";      \r
-      if (e >= 0) \r
-      {  f = f + "+";\r
-         p = p + e;\r
-      }\r
-      else\r
-      {  f = f + "-";\r
-         p = p + (-e);\r
-      }\r
-         \r
-      return f + p.substring(p.length() - 3, p.length());\r
-   }\r
-   \r
-   private int width;\r
-   private int precision;\r
-   private String pre;\r
-   private String post;\r
-   private boolean leading_zeroes;\r
-   private boolean show_plus;\r
-   private boolean alternate;\r
-   private boolean show_space;\r
-   private boolean left_align;\r
-   private char fmt; // one of cdeEfgGiosxXos\r
-}\r
-\r
-\r
-\r
-\r
-\r
+/*
+ * Cay S. Horstmann & Gary Cornell, Core Java
+ * Published By Sun Microsystems Press/Prentice-Hall
+ * Copyright (C) 1997 Sun Microsystems Inc.
+ * All Rights Reserved.
+ *
+ * Permission to use, copy, modify, and distribute this 
+ * software and its documentation for NON-COMMERCIAL purposes
+ * and without fee is hereby granted provided that this 
+ * copyright notice appears in all copies. 
+ * 
+ * THE AUTHORS AND PUBLISHER MAKE NO REPRESENTATIONS OR 
+ * WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER 
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
+ * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHORS
+ * AND PUBLISHER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED 
+ * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING 
+ * THIS SOFTWARE OR ITS DERIVATIVES.
+ */
+/**
+ * A class for formatting numbers that follows printf conventions.
+ * Also implements C-like atoi and atof functions
+ * @version 1.04 13 Sep 1998
+ * @author Cay Horstmann
+ */
+
+import java.io.*;
+
+public class Format
+
+{ /** 
+  * Formats the number following printf conventions.
+  * Main limitation: Can only handle one format parameter at a time
+  * Use multiple Format objects to format more than one number
+  * @param s the format string following printf conventions
+  * The string has a prefix, a format code and a suffix. The prefix and suffix
+  * become part of the formatted output. The format code directs the
+  * formatting of the (single) parameter to be formatted. The code has the
+  * following structure
+  * <ul>
+  * <li> a % (required)
+  * <li> a modifier (optional)
+  * <dl>
+  * <dt> + <dd> forces display of + for positive numbers
+  * <dt> 0 <dd> show leading zeroes
+  * <dt> - <dd> align left in the field
+  * <dt> space <dd> prepend a space in front of positive numbers
+  * <dt> # <dd> use "alternate" format. Add 0 or 0x for octal or hexadecimal numbers. Don't suppress trailing zeroes in general floating point format.
+  * </dl>
+  * <li> an integer denoting field width (optional)
+  * <li> a period followed by an integer denoting precision (optional)
+  * <li> a format descriptor (required)
+  * <dl>
+  * <dt>f <dd> floating point number in fixed format
+  * <dt>e, E <dd> floating point number in exponential notation (scientific format). The E format results in an uppercase E for the exponent (1.14130E+003), the e format in a lowercase e.
+  * <dt>g, G <dd> floating point number in general format (fixed format for small numbers, exponential format for large numbers). Trailing zeroes are suppressed. The G format results in an uppercase E for the exponent (if any), the g format in a lowercase e.
+  * <dt>d, i <dd> integer in decimal
+  * <dt>x <dd> integer in hexadecimal
+  * <dt>o <dd> integer in octal
+  * <dt>s <dd> string
+  * <dt>c <dd> character
+  * </dl>
+  * </ul>
+  * @exception IllegalArgumentException if bad format
+  */
+
+   public Format(String s)
+   {  width = 0;
+      precision = -1;
+      pre = "";
+      post = "";
+      leading_zeroes = false;
+      show_plus = false;
+      alternate = false;
+      show_space = false;
+      left_align = false;
+      fmt = ' '; 
+      
+      int state = 0; 
+      int length = s.length();
+      int parse_state = 0; 
+      // 0 = prefix, 1 = flags, 2 = width, 3 = precision,
+      // 4 = format, 5 = end
+      int i = 0;
+      
+      while (parse_state == 0)
+      {  if (i >= length) parse_state = 5;
+         else if (s.charAt(i) == '%')
+         {  if (i < length - 1)
+            {  if (s.charAt(i + 1) == '%')
+               {  pre = pre + '%';
+                  i++;
+               }
+               else
+                  parse_state = 1;
+            }
+            else throw new java.lang.IllegalArgumentException();
+         }
+         else
+            pre = pre + s.charAt(i);
+         i++;
+      }
+      while (parse_state == 1)
+      {  if (i >= length) parse_state = 5;
+         else if (s.charAt(i) == ' ') show_space = true;
+         else if (s.charAt(i) == '-') left_align = true; 
+         else if (s.charAt(i) == '+') show_plus = true;
+         else if (s.charAt(i) == '0') leading_zeroes = true;
+         else if (s.charAt(i) == '#') alternate = true;
+         else { parse_state = 2; i--; }
+         i++;
+      }      
+      while (parse_state == 2)
+      {  if (i >= length) parse_state = 5;
+         else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
+         {  width = width * 10 + s.charAt(i) - '0';
+            i++;
+         }
+         else if (s.charAt(i) == '.')
+         {  parse_state = 3;
+            precision = 0;
+            i++;
+         }
+         else 
+            parse_state = 4;            
+      }
+      while (parse_state == 3)
+      {  if (i >= length) parse_state = 5;
+         else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
+         {  precision = precision * 10 + s.charAt(i) - '0';
+            i++;
+         }
+         else 
+            parse_state = 4;                  
+      }
+      if (parse_state == 4) 
+      {  if (i >= length) parse_state = 5;
+         else fmt = s.charAt(i);
+         i++;
+      }
+      if (i < length)
+         post = s.substring(i, length);
+   }      
+
+  /** 
+  * prints a formatted number following printf conventions
+  * @param s a PrintStream
+  * @param fmt the format string
+  * @param x the double to print
+  */
+  
+   public static void print(java.io.PrintStream s, String fmt, double x)
+   {  s.print(new Format(fmt).form(x));
+   }
+
+  /** 
+  * prints a formatted number following printf conventions
+  * @param s a PrintStream
+  * @param fmt the format string
+  * @param x the long to print
+  */
+  public static void print(java.io.PrintStream s, String fmt, long x)
+   {  s.print(new Format(fmt).form(x));
+   }
+
+  /** 
+  * prints a formatted number following printf conventions
+  * @param s a PrintStream
+  * @param fmt the format string
+  * @param x the character to 
+  */
+  
+   public static void print(java.io.PrintStream s, String fmt, char x)
+   {  s.print(new Format(fmt).form(x));
+   }
+
+  /** 
+  * prints a formatted number following printf conventions
+  * @param s a PrintStream, fmt the format string
+  * @param x a string that represents the digits to print
+  */
+  
+   public static void print(java.io.PrintStream s, String fmt, String x)
+   {  s.print(new Format(fmt).form(x));
+   }
+   
+  /** 
+  * Converts a string of digits (decimal, octal or hex) to an integer
+  * @param s a string
+  * @return the numeric value of the prefix of s representing a base 10 integer
+  */
+  
+   public static int atoi(String s)
+   {  return (int)atol(s);
+   } 
+   
+  /** 
+  * Converts a string of digits (decimal, octal or hex) to a long integer
+  * @param s a string
+  * @return the numeric value of the prefix of s representing a base 10 integer
+  */
+  
+   public static long atol(String s)
+   {  int i = 0;
+
+      while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
+      if (i < s.length() && s.charAt(i) == '0')
+      {  if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X'))
+            return parseLong(s.substring(i + 2), 16);
+         else return parseLong(s, 8);
+      }
+      else return parseLong(s, 10);
+   }
+
+   private static long parseLong(String s, int base)
+   {  int i = 0;
+      int sign = 1;
+      long r = 0;
+      
+      while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
+      if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
+      else if (i < s.length() && s.charAt(i) == '+') { i++; }
+      while (i < s.length())
+      {  char ch = s.charAt(i);
+         if ('0' <= ch && ch < '0' + base)
+            r = r * base + ch - '0';
+         else if ('A' <= ch && ch < 'A' + base - 10)
+            r = r * base + ch - 'A' + 10 ;
+         else if ('a' <= ch && ch < 'a' + base - 10)
+            r = r * base + ch - 'a' + 10 ;
+         else 
+            return r * sign;
+         i++;
+      }
+      return r * sign;      
+   }
+      
+   /** 
+   * Converts a string of digits to an double
+   * @param s a string
+   */
+   
+   public static double atof(String s)
+   {  int i = 0;
+      int sign = 1;
+      double r = 0; // integer part
+      double f = 0; // fractional part
+      double p = 1; // exponent of fractional part
+      int state = 0; // 0 = int part, 1 = frac part
+      
+      while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
+      if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
+      else if (i < s.length() && s.charAt(i) == '+') { i++; }
+      while (i < s.length())
+      {  char ch = s.charAt(i);
+         if ('0' <= ch && ch <= '9')
+         {  if (state == 0)
+               r = r * 10 + ch - '0';
+            else if (state == 1)
+            {  p = p / 10;
+               r = r + p * (ch - '0');
+            }
+         }
+         else if (ch == '.') 
+         {  if (state == 0) state = 1; 
+            else return sign * r;
+         }
+         else if (ch == 'e' || ch == 'E')
+         {  long e = (int)parseLong(s.substring(i + 1), 10);
+            return sign * r * Math.pow(10, e);
+         }
+         else return sign * r;
+         i++;
+      }
+      return sign * r;
+   }
+            
+   /** 
+   * Formats a double into a string (like sprintf in C)
+   * @param x the number to format
+   * @return the formatted string 
+   * @exception IllegalArgumentException if bad argument
+   */
+   
+   public String form(double x)
+   {  String r;
+      if (precision < 0) precision = 6;
+      int s = 1;
+      if (x < 0) { x = -x; s = -1; }
+      if (fmt == 'f')
+         r = fixed_format(x);
+      else if (fmt == 'e' || fmt == 'E' || fmt == 'g' || fmt == 'G')
+         r = exp_format(x);
+      else throw new java.lang.IllegalArgumentException();
+      
+      return pad(sign(s, r));
+   }
+   
+   /** 
+   * Formats a long integer into a string (like sprintf in C)
+   * @param x the number to format
+   * @return the formatted string 
+   */
+   
+   public String form(long x)
+   {  String r; 
+      int s = 0;
+      if (fmt == 'd' || fmt == 'i')
+      {  if (x < 0) 
+         {  r = ("" + x).substring(1);
+            s = -1; 
+         }
+         else 
+         {  r = "" + x; 
+            s = 1;
+         }
+      }
+      else if (fmt == 'o')
+         r = convert(x, 3, 7, "01234567");
+      else if (fmt == 'x')
+         r = convert(x, 4, 15, "0123456789abcdef");
+      else if (fmt == 'X')
+         r = convert(x, 4, 15, "0123456789ABCDEF");
+      else throw new java.lang.IllegalArgumentException();
+         
+      return pad(sign(s, r));
+   }
+   
+   /** 
+   * Formats a character into a string (like sprintf in C)
+   * @param x the value to format
+   * @return the formatted string 
+   */
+   
+   public String form(char c)
+   {  if (fmt != 'c')
+         throw new java.lang.IllegalArgumentException();
+
+      String r = "" + c;
+      return pad(r);
+   }
+   
+   /** 
+   * Formats a string into a larger string (like sprintf in C)
+   * @param x the value to format
+   * @return the formatted string 
+   */
+   
+   public String form(String s)
+   {  if (fmt != 's')
+         throw new java.lang.IllegalArgumentException();
+      if (precision >= 0 && precision < s.length()) 
+          s = s.substring(0, precision);
+      return pad(s);
+   }
+   
+    
+   /**
+   * a test stub for the format class
+   */
+   
+   public static void main(String[] a)
+   {  double x = 1.23456789012;
+      double y = 123;
+      double z = 1.2345e30;
+      double w = 1.02;
+      double u = 1.234e-5;
+      int d = 0xCAFE;
+      Format.print(System.out, "x = |%f|\n", x);
+      Format.print(System.out, "u = |%20f|\n", u);
+      Format.print(System.out, "x = |% .5f|\n", x);
+      Format.print(System.out, "w = |%20.5f|\n", w);
+      Format.print(System.out, "x = |%020.5f|\n", x);
+      Format.print(System.out, "x = |%+20.5f|\n", x);
+      Format.print(System.out, "x = |%+020.5f|\n", x);
+      Format.print(System.out, "x = |% 020.5f|\n", x);
+      Format.print(System.out, "y = |%#+20.5f|\n", y);
+      Format.print(System.out, "y = |%-+20.5f|\n", y);
+      Format.print(System.out, "z = |%20.5f|\n", z);
+      
+      Format.print(System.out, "x = |%e|\n", x);
+      Format.print(System.out, "u = |%20e|\n", u);
+      Format.print(System.out, "x = |% .5e|\n", x);
+      Format.print(System.out, "w = |%20.5e|\n", w);
+      Format.print(System.out, "x = |%020.5e|\n", x);
+      Format.print(System.out, "x = |%+20.5e|\n", x);
+      Format.print(System.out, "x = |%+020.5e|\n", x);
+      Format.print(System.out, "x = |% 020.5e|\n", x);
+      Format.print(System.out, "y = |%#+20.5e|\n", y);
+      Format.print(System.out, "y = |%-+20.5e|\n", y);
+      
+      Format.print(System.out, "x = |%g|\n", x);
+      Format.print(System.out, "z = |%g|\n", z);
+      Format.print(System.out, "w = |%g|\n", w);
+      Format.print(System.out, "u = |%g|\n", u);
+      Format.print(System.out, "y = |%.2g|\n", y);
+      Format.print(System.out, "y = |%#.2g|\n", y);
+
+      Format.print(System.out, "d = |%d|\n", d);
+      Format.print(System.out, "d = |%20d|\n", d);            
+      Format.print(System.out, "d = |%020d|\n", d);    
+      Format.print(System.out, "d = |%+20d|\n", d);
+      Format.print(System.out, "d = |% 020d|\n", d);
+      Format.print(System.out, "d = |%-20d|\n", d);
+      Format.print(System.out, "d = |%20.8d|\n", d);
+      Format.print(System.out, "d = |%x|\n", d);            
+      Format.print(System.out, "d = |%20X|\n", d);    
+      Format.print(System.out, "d = |%#20x|\n", d);
+      Format.print(System.out, "d = |%020X|\n", d);
+      Format.print(System.out, "d = |%20.8x|\n", d);
+      Format.print(System.out, "d = |%o|\n", d);            
+      Format.print(System.out, "d = |%020o|\n", d);    
+      Format.print(System.out, "d = |%#20o|\n", d);
+      Format.print(System.out, "d = |%#020o|\n", d);
+      Format.print(System.out, "d = |%20.12o|\n", d);
+      
+      Format.print(System.out, "s = |%-20s|\n", "Hello");      
+      Format.print(System.out, "s = |%-20c|\n", '!');      
+
+      // regression test to confirm fix of reported bugs
+
+      Format.print(System.out, "|%i|\n", Long.MIN_VALUE);
+
+      Format.print(System.out, "|%6.2e|\n", 0.0);
+      Format.print(System.out, "|%6.2g|\n", 0.0);
+
+      Format.print(System.out, "|%6.2f|\n", 9.99);
+      Format.print(System.out, "|%6.2f|\n", 9.999);
+
+      Format.print(System.out, "|%6.0f|\n", 9.999);
+   }
+   
+   private static String repeat(char c, int n)
+   {  if (n <= 0) return "";
+      StringBuffer s = new StringBuffer(n);
+      for (int i = 0; i < n; i++) s.append(c);
+      return s.toString();
+   }
+
+   private static String convert(long x, int n, int m, String d)
+   {  if (x == 0) return "0";
+      String r = "";
+      while (x != 0)
+      {  r = d.charAt((int)(x & m)) + r;
+         x = x >>> n;
+      }
+      return r;
+   }
+
+   private String pad(String r)
+   {  String p = repeat(' ', width - r.length());
+      if (left_align) return pre + r + p + post;
+      else return pre + p + r + post;
+   }
+   
+   private String sign(int s, String r)
+   {  String p = "";
+      if (s < 0) p = "-"; 
+      else if (s > 0)
+      {  if (show_plus) p = "+";
+         else if (show_space) p = " ";
+      }
+      else
+      {  if (fmt == 'o' && alternate && r.length() > 0 && r.charAt(0) != '0') p = "0";
+         else if (fmt == 'x' && alternate) p = "0x";
+         else if (fmt == 'X' && alternate) p = "0X";
+      }
+      int w = 0;
+      if (leading_zeroes) 
+         w = width;
+      else if ((fmt == 'd' || fmt == 'i' || fmt == 'x' || fmt == 'X' || fmt == 'o') 
+         && precision > 0) w = precision;
+      
+      return p + repeat('0', w - p.length() - r.length()) + r;
+   }
+   
+   private String fixed_format(double d)
+   {  boolean removeTrailing
+         = (fmt == 'G' || fmt == 'g') && !alternate;
+         // remove trailing zeroes and decimal point
+
+      if (d > 0x7FFFFFFFFFFFFFFFL) return exp_format(d);
+      if (precision == 0) 
+         return (long)(d + 0.5) + (removeTrailing ? "" : ".");
+
+      long whole = (long)d;
+      double fr = d - whole; // fractional part
+      if (fr >= 1 || fr < 0) return exp_format(d);
+
+      double factor = 1;
+      String leading_zeroes = "";
+      for (int i = 1; i <= precision && factor <= 0x7FFFFFFFFFFFFFFFL; i++) 
+      {  factor *= 10; 
+         leading_zeroes = leading_zeroes + "0"; 
+      }
+      long l = (long) (factor * fr + 0.5);
+      if (l >= factor) { l = 0; whole++; } // CSH 10-25-97
+      
+      String z = leading_zeroes + l;
+      z = "." + z.substring(z.length() - precision, z.length());
+
+      if (removeTrailing)
+      {  int t = z.length() - 1;
+         while (t >= 0 && z.charAt(t) == '0') t--;
+         if (t >= 0 && z.charAt(t) == '.') t--;
+         z = z.substring(0, t + 1);
+      }
+
+      return whole + z;
+   }
+
+   private String exp_format(double d)
+   {  String f = "";
+      int e = 0;
+      double dd = d;
+      double factor = 1;
+      if (d != 0)
+      {  while (dd > 10) { e++; factor /= 10; dd = dd / 10; }
+         while (dd < 1) { e--; factor *= 10; dd = dd * 10; }
+      }
+      if ((fmt == 'g' || fmt == 'G') && e >= -4 && e < precision) 
+         return fixed_format(d);
+      
+      d = d * factor;
+      f = f + fixed_format(d);
+      
+      if (fmt == 'e' || fmt == 'g')
+         f = f + "e";
+      else
+         f = f + "E";
+
+      String p = "000";      
+      if (e >= 0) 
+      {  f = f + "+";
+         p = p + e;
+      }
+      else
+      {  f = f + "-";
+         p = p + (-e);
+      }
+         
+      return f + p.substring(p.length() - 3, p.length());
+   }
+   
+   private int width;
+   private int precision;
+   private String pre;
+   private String post;
+   private boolean leading_zeroes;
+   private boolean show_plus;
+   private boolean alternate;
+   private boolean show_space;
+   private boolean left_align;
+   private char fmt; // one of cdeEfgGiosxXos
+}
+
+
+
+
+
index 0ed1621..8ae8f7a 100644 (file)
@@ -4,30 +4,30 @@ import java.io.FileOutputStream;
 
 public class Get {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFile f = new SmbFile( argv[0] );
-               SmbFileInputStream in = new SmbFileInputStream( f );
-               FileOutputStream out = new FileOutputStream( f.getName() );
+        SmbFile f = new SmbFile( argv[0] );
+        SmbFileInputStream in = new SmbFileInputStream( f );
+        FileOutputStream out = new FileOutputStream( f.getName() );
 
-               long t0 = System.currentTimeMillis();
+        long t0 = System.currentTimeMillis();
 
-               byte[] b = new byte[8192];
-               int n, tot = 0;
-               long t1 = t0;
-               while(( n = in.read( b )) > 0 ) {
-                       out.write( b, 0, n );
-                       tot += n;
-                       System.out.print( '#' );
-               }
+        byte[] b = new byte[8192];
+        int n, tot = 0;
+        long t1 = t0;
+        while(( n = in.read( b )) > 0 ) {
+            out.write( b, 0, n );
+            tot += n;
+            System.out.print( '#' );
+        }
 
-               long t = System.currentTimeMillis() - t0;
+        long t = System.currentTimeMillis() - t0;
 
-               System.out.println();
-               System.out.println( tot + " bytes transfered in " + ( t / 1000 ) + " seconds at " + (( tot / 1000 ) / Math.max( 1, ( t / 1000 ))) + "Kbytes/sec" );
+        System.out.println();
+        System.out.println( tot + " bytes transfered in " + ( t / 1000 ) + " seconds at " + (( tot / 1000 ) / Math.max( 1, ( t / 1000 ))) + "Kbytes/sec" );
 
-               in.close();
-               out.close();
-       }
+        in.close();
+        out.close();
+    }
 }
 
index edcb26a..4fd4c80 100644 (file)
@@ -5,12 +5,12 @@ import java.util.GregorianCalendar;
 
 public class GetDate {
 
-       public static void main( String argv[] ) throws Exception {
-               SmbFile f = new SmbFile( argv[0] );
-               Date d = new Date( f.lastModified() );
-               SimpleDateFormat sdf = new SimpleDateFormat( "EEEE, MMMM d, yyyy h:mm:ss a" );
-               sdf.setCalendar( new GregorianCalendar() );
-               System.out.println( sdf.format( d ));
-       }
+    public static void main( String argv[] ) throws Exception {
+        SmbFile f = new SmbFile( argv[0] );
+        Date d = new Date( f.lastModified() );
+        SimpleDateFormat sdf = new SimpleDateFormat( "EEEE, MMMM d, yyyy h:mm:ss a" );
+        sdf.setCalendar( new GregorianCalendar() );
+        System.out.println( sdf.format( d ));
+    }
 }
 
index fa4e12c..88d4dab 100644 (file)
@@ -2,10 +2,10 @@ import jcifs.smb.SmbFile;
 
 public class GetDfsPath {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFile f = new SmbFile( argv[0] );
-               System.out.println( f.getDfsPath() );
-       }
+        SmbFile f = new SmbFile( argv[0] );
+        System.out.println( f.getDfsPath() );
+    }
 }
 
index b3619c1..83d8358 100644 (file)
@@ -1,54 +1,53 @@
 import jcifs.netbios.NbtAddress;
 import jcifs.smb.SmbFile;
-import jcifs.util.Log;
 import java.util.Date;
 
 public class GetType {
 
-       static final String[] types = { "TYPE_FILESYSTEM", "TYPE_WORKGROUP",
-               "TYPE_SERVER", "TYPE_SHARE", "TYPE_NAMED_PIPE", "TYPE_PRINTER", "TYPE_COMM" };
+    static final String[] types = { "TYPE_FILESYSTEM", "TYPE_WORKGROUP",
+        "TYPE_SERVER", "TYPE_SHARE", "TYPE_NAMED_PIPE", "TYPE_PRINTER", "TYPE_COMM" };
 
-       public static void main( String[] argv ) throws Exception {
+    public static void main( String[] argv ) throws Exception {
 
-               SmbFile file = new SmbFile( argv[0] );
-               int type;
+        SmbFile file = new SmbFile( argv[0] );
+        int type;
 
-               switch( file.getType() ) {
-                       case SmbFile.TYPE_FILESYSTEM:
-                               type = 0;
-                               break;
-                       case SmbFile.TYPE_WORKGROUP:
-                               type = 1;
-                               break;
-                       case SmbFile.TYPE_SERVER:
-                               type = 2;
-                               break;
-                       case SmbFile.TYPE_SHARE:
-                               type = 3;
-                               break;
-                       case SmbFile.TYPE_NAMED_PIPE:
-                               type = 4;
-                               break;
-                       case SmbFile.TYPE_PRINTER:
-                               type = 5;
-                               break;
-                       case SmbFile.TYPE_COMM:
-                               type = 6;
-                               break;
-                       default:
-                               throw new RuntimeException( "Unknown service type: " + file.getType() );
-               }
-               System.out.println( types[type] );
-               System.out.println();
+        switch( file.getType() ) {
+            case SmbFile.TYPE_FILESYSTEM:
+                type = 0;
+                break;
+            case SmbFile.TYPE_WORKGROUP:
+                type = 1;
+                break;
+            case SmbFile.TYPE_SERVER:
+                type = 2;
+                break;
+            case SmbFile.TYPE_SHARE:
+                type = 3;
+                break;
+            case SmbFile.TYPE_NAMED_PIPE:
+                type = 4;
+                break;
+            case SmbFile.TYPE_PRINTER:
+                type = 5;
+                break;
+            case SmbFile.TYPE_COMM:
+                type = 6;
+                break;
+            default:
+                throw new RuntimeException( "Unknown service type: " + file.getType() );
+        }
+        System.out.println( types[type] );
+        System.out.println();
 
-               long t1 = System.currentTimeMillis();
-               String[] files = file.list();
-               long t2 = System.currentTimeMillis() - t1;
+        long t1 = System.currentTimeMillis();
+        String[] files = file.list();
+        long t2 = System.currentTimeMillis() - t1;
 
-               for( int i = 0; i < files.length; i++ ) {
-                       System.out.print( " " + files[i] );
-               }
-               System.out.println();
-               System.out.println( files.length + " files in " + t2 + "ms" );
-       }
+        for( int i = 0; i < files.length; i++ ) {
+            System.out.print( " " + files[i] );
+        }
+        System.out.println();
+        System.out.println( files.length + " files in " + t2 + "ms" );
+    }
 }
index 0b8201c..e910142 100644 (file)
@@ -3,23 +3,23 @@ import java.io.InputStream;
 
 public class GetURL {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               jcifs.Config.registerSmbURLHandler();
+        jcifs.Config.registerSmbURLHandler();
 
-               URL url = new URL( argv[0] );
-               InputStream in = url.openStream();
+        URL url = new URL( argv[0] );
+        InputStream in = url.openStream();
 
-               if( in != null ) {
-                       byte[] buf = new byte[4096];
-                       int n;
-                       while(( n = in.read( buf )) != -1 ) {
-                               System.out.print( " " + n );
-                       }
-               } else {
-                       System.out.println( "stream waz null" );
-               }
-               in.close();
-       }
+        if( in != null ) {
+            byte[] buf = new byte[4096];
+            int n;
+            while(( n = in.read( buf )) != -1 ) {
+                System.out.write( buf, 0, n );
+            }
+        } else {
+            System.out.println( "stream waz null" );
+        }
+        in.close();
+    }
 }
 
index 70ba4d4..1517316 100644 (file)
@@ -4,27 +4,27 @@ import java.io.FileInputStream;
 
 public class GrowWrite {
 
-       static final int SIZE = 0x4FFF;
+    static final int SIZE = 0x4FFF;
 
-       public static void main( String argv[] ) throws Exception {
-               int n, tot;
-               byte[] buf = new byte[SIZE];
-               SmbFile f = new SmbFile( argv[0] );
-               SmbFileOutputStream out = new SmbFileOutputStream( f );
+    public static void main( String argv[] ) throws Exception {
+        int n, tot;
+        byte[] buf = new byte[SIZE];
+        SmbFile f = new SmbFile( argv[0] );
+        SmbFileOutputStream out = new SmbFileOutputStream( f );
 
-               n = tot = 0;
-               do {
-                       if(( n % 0x1F ) == 0) {
-                               f = new SmbFile( argv[0] );
-                               out = new SmbFileOutputStream( f );
-                               System.out.print( '#' );
-                       }
-                       out.write( buf, 0, n );
-                       out.flush();
-                       tot += n;
-               } while( n++ < SIZE );
+        n = tot = 0;
+        do {
+            if(( n % 0x1F ) == 0) {
+                f = new SmbFile( argv[0] );
+                out = new SmbFileOutputStream( f );
+                System.out.print( '#' );
+            }
+            out.write( buf, 0, n );
+            out.flush();
+            tot += n;
+        } while( n++ < SIZE );
 
-               System.out.println();
-               System.out.println( tot + " bytes transfered." );
-       }
+        System.out.println();
+        System.out.println( tot + " bytes transfered." );
+    }
 }
index f74f5d2..a810ffd 100644 (file)
@@ -2,10 +2,10 @@ import java.net.*;
 
 public class HttpURL {
 
-       public static void main( String[] args ) throws Exception {
-               jcifs.Config.registerSmbURLHandler();
+    public static void main( String[] args ) throws Exception {
+        jcifs.Config.registerSmbURLHandler();
 
-               URL u = new URL( new URL( args[0] ), args[1] );
-               System.out.println( u );
-       }
+        URL u = new URL( new URL( args[0] ), args[1] );
+        System.out.println( u );
+    }
 }
index 7378ce2..c099307 100644 (file)
@@ -2,39 +2,39 @@ import jcifs.smb.*;
 
 public class Interleave {
 
-       static class IThread extends Thread {
-               String url;
+    static class IThread extends Thread {
+        String url;
 
-               IThread( String url ) {
-                       this.url = url;
-               }
+        IThread( String url ) {
+            this.url = url;
+        }
 
-               public void run() {
-                       try {
-                               yield();
-                               System.out.println( getName() + ": started" );
-                               SmbFileOutputStream o = new SmbFileOutputStream( url );
-                               o.close();
-                               System.out.println( getName() + ": done" );
-                       } catch( Exception x ) {
-                               x.printStackTrace();
-                       }
-               }
-       }
+        public void run() {
+            try {
+                yield();
+                System.out.println( getName() + ": started" );
+                SmbFileOutputStream o = new SmbFileOutputStream( url );
+                o.close();
+                System.out.println( getName() + ": done" );
+            } catch( Exception x ) {
+                x.printStackTrace();
+            }
+        }
+    }
 
-       public static void main(String[] argv) throws Exception {
-               if( argv.length < 2 ) {
-                       System.out.println( "java Interleave dir numThreads" );
-                       return;
-               }
-       
-               int numThreads = Integer.parseInt( argv[1] );
-               IThread[] t = new IThread[numThreads];
-               for( int i = 0; i < numThreads; i++ ) {
-                       t[i] = new IThread( argv[0] + "/it" + i + ".tmp" );
-               }
-               for( int j = 0; j < numThreads; j++ ) {
-                       t[j].start();
-               }
-       }
+    public static void main(String[] argv) throws Exception {
+        if( argv.length < 2 ) {
+            System.out.println( "java Interleave dir numThreads" );
+            return;
+        }
+    
+        int numThreads = Integer.parseInt( argv[1] );
+        IThread[] t = new IThread[numThreads];
+        for( int i = 0; i < numThreads; i++ ) {
+            t[i] = new IThread( argv[0] + "/it" + i + ".tmp" );
+        }
+        for( int j = 0; j < numThreads; j++ ) {
+            t[j].start();
+        }
+    }
 }
index 030703b..c7fe924 100644 (file)
@@ -1,11 +1,10 @@
-import jcifs.util.Log;
 import jcifs.smb.SmbFile;
 
 public class IsDir {
 
-       public static void main( String argv[] ) throws Exception {
-               SmbFile f = new SmbFile( argv[0] );
-               System.out.println( f.isDirectory() );
-       }
+    public static void main( String argv[] ) throws Exception {
+        SmbFile f = new SmbFile( argv[0] );
+        System.out.println( f.isDirectory() );
+    }
 }
 
index 910faaa..8b654c1 100644 (file)
@@ -2,10 +2,10 @@ import jcifs.smb.SmbFile;
 
 public class Length {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFile f = new SmbFile( argv[0] );
-               System.out.println( argv[0] + "'s length is " + f.length() );
-       }
+        SmbFile f = new SmbFile( argv[0] );
+        System.out.println( argv[0] + "'s length is " + f.length() );
+    }
 }
 
index 98dcf43..6b7209f 100644 (file)
@@ -1,22 +1,21 @@
 import jcifs.netbios.NbtAddress;
 import jcifs.smb.SmbFile;
-import jcifs.util.Log;
 import java.util.Date;
 
 public class List {
 
-       public static void main( String[] argv ) throws Exception {
+    public static void main( String[] argv ) throws Exception {
 
-               SmbFile file = new SmbFile( argv[0] );
+        SmbFile file = new SmbFile( argv[0] );
 
-               long t1 = System.currentTimeMillis();
-               String[] files = file.list();
-               long t2 = System.currentTimeMillis() - t1;
+        long t1 = System.currentTimeMillis();
+        String[] files = file.list();
+        long t2 = System.currentTimeMillis() - t1;
 
-               for( int i = 0; i < files.length; i++ ) {
-                       System.out.print( " " + files[i] );
-               }
-               System.out.println();
-               System.out.println( files.length + " files in " + t2 + "ms" );
-       }
+        for( int i = 0; i < files.length; i++ ) {
+            System.out.print( " " + files[i] );
+        }
+        System.out.println();
+        System.out.println( files.length + " files in " + t2 + "ms" );
+    }
 }
index 1af0c27..6f0ee57 100644 (file)
@@ -1,22 +1,21 @@
 import jcifs.netbios.NbtAddress;
 import jcifs.smb.SmbFile;
-import jcifs.util.Log;
 import java.util.Date;
 
 public class ListFiles {
 
-       public static void main( String[] argv ) throws Exception {
+    public static void main( String[] argv ) throws Exception {
 
-               SmbFile file = new SmbFile( argv[0] );
+        SmbFile file = new SmbFile( argv[0] );
 
-               long t1 = System.currentTimeMillis();
-               SmbFile[] files = file.listFiles();
-               long t2 = System.currentTimeMillis() - t1;
+        long t1 = System.currentTimeMillis();
+        SmbFile[] files = file.listFiles();
+        long t2 = System.currentTimeMillis() - t1;
 
-               for( int i = 0; i < files.length; i++ ) {
-                       System.out.print( " " + files[i].getName() );
-               }
-               System.out.println();
-               System.out.println( files.length + " files in " + t2 + "ms" );
-       }
+        for( int i = 0; i < files.length; i++ ) {
+            System.out.print( " " + files[i].getName() );
+        }
+        System.out.println();
+        System.out.println( files.length + " files in " + t2 + "ms" );
+    }
 }
index f060728..ceeda40 100644 (file)
@@ -1,44 +1,43 @@
 import jcifs.netbios.NbtAddress;
 import jcifs.smb.SmbFile;
-import jcifs.util.Log;
 import java.util.Date;
 
 public class ListTypes {
 
-       public static void main( String[] argv ) throws Exception {
+    public static void main( String[] argv ) throws Exception {
 
-               SmbFile file = new SmbFile( argv[0] );
+        SmbFile file = new SmbFile( argv[0] );
 
-               long t1 = System.currentTimeMillis();
-               SmbFile[] files = file.listFiles();
-               long t2 = System.currentTimeMillis() - t1;
+        long t1 = System.currentTimeMillis();
+        SmbFile[] files = file.listFiles();
+        long t2 = System.currentTimeMillis() - t1;
 
-               for( int i = 0; i < files.length; i++ ) {
-                       System.out.print( " " + files[i].getName() );
-                       switch(files[i].getType()) {
-                               case SmbFile.TYPE_FILESYSTEM:
-                                       System.out.println( "[TYPE_FILESYSTEM]" );
-                                       break;
-                               case SmbFile.TYPE_WORKGROUP:
-                                       System.out.println( "[TYPE_WORKGROUP]" );
-                                       break;
-                               case SmbFile.TYPE_SERVER:
-                                       System.out.println( "[TYPE_SERVER]" );
-                                       break;
-                               case SmbFile.TYPE_SHARE:
-                                       System.out.println( "[TYPE_SHARE]" );
-                                       break;
-                               case SmbFile.TYPE_NAMED_PIPE:
-                                       System.out.println( "[TYPE_NAMEDPIPE]" );
-                                       break;
-                               case SmbFile.TYPE_PRINTER:
-                                       System.out.println( "[TYPE_PRINTER]" );
-                                       break;
-                               case SmbFile.TYPE_COMM:
-                                       System.out.println( "[TYPE_COMM]" );
-                                       break;
-                       };
-               }
-               System.out.println( files.length + " files in " + t2 + "ms" );
-       }
+        for( int i = 0; i < files.length; i++ ) {
+            System.out.print( " " + files[i].getName() );
+            switch(files[i].getType()) {
+                case SmbFile.TYPE_FILESYSTEM:
+                    System.out.println( "[TYPE_FILESYSTEM]" );
+                    break;
+                case SmbFile.TYPE_WORKGROUP:
+                    System.out.println( "[TYPE_WORKGROUP]" );
+                    break;
+                case SmbFile.TYPE_SERVER:
+                    System.out.println( "[TYPE_SERVER]" );
+                    break;
+                case SmbFile.TYPE_SHARE:
+                    System.out.println( "[TYPE_SHARE]" );
+                    break;
+                case SmbFile.TYPE_NAMED_PIPE:
+                    System.out.println( "[TYPE_NAMEDPIPE]" );
+                    break;
+                case SmbFile.TYPE_PRINTER:
+                    System.out.println( "[TYPE_PRINTER]" );
+                    break;
+                case SmbFile.TYPE_COMM:
+                    System.out.println( "[TYPE_COMM]" );
+                    break;
+            };
+        }
+        System.out.println( files.length + " files in " + t2 + "ms" );
+    }
 }
diff --git a/examples/LogTest.java b/examples/LogTest.java
deleted file mode 100644 (file)
index 5af77cc..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-import jcifs.util.Log;
-
-public class LogTest {
-
-       public static void main( String[] argv ) {
-               Log.setMask(( Log.ALL | Log.EXCEPTIONS ) & ~Log.HEX_DUMPS );
-
-               Log.println( Log.WARNINGS, "LogTest warning", "you've been warned" );
-               Log.println( Log.DEBUGGING, "This is a debugging message", "MADE IT!" );
-               Log.printHexDump( "This will not be printed", "hello, world".getBytes() );
-               try {
-                       int i = 10/0;
-               } catch( Exception x ) {
-                       Log.printStackTrace( "LogTest exception", x );
-               }
-       }
-}
index 1228d42..e5f1df5 100644 (file)
@@ -3,7 +3,7 @@ CLASSPATH=../build:.
 
 .SUFFIXES: .java .class
 
-CLASSFILES=AllocInfo.class Append.class AuthListFiles.class CallNamedPipe.class CifsTime.class CopyTo.class CreateFile.class Delete.class Equals.class Exists.class FileInfo.class FileOps.class FilterFiles.class Format.class GetDate.class GetDfsPath.class Get.class GetType.class GetURL.class GrowWrite.class HttpURL.class Interleave.class IsDir.class Length.class ListFiles.class List.class ListTypes.class LogTest.class Mkdir.class NodeStatus.class OpenExclusive.class PeekNamedPipe.class PipeTalk.class Put.class Query.class RenameTo.class SetAttrs.class SetTime.class SlowRead.class SlowWrite.class SmbCrawler.class SmbShell.class SmbTableFile.class SmbTableFileRecord.class T2Crawler.class TestRandomAccess.class TestSmbURL.class TestUnicode.class ThreadedNbtQuery.class ThreadedSmbCrawler.class ThreadedUniQuery.class Torture1.class Torture2.class TortureTest5.class TransactNamedPipe.class URLTest.class VerifyGuest.class VerifyIO.class VerifyReads.class
+CLASSFILES=AllocInfo.class Append.class AuthListFiles.class CallNamedPipe.class CifsTime.class CopyTo.class CreateFile.class Delete.class Equals.class Exists.class FileInfo.class FileOps.class FilterFiles.class Format.class GetDate.class GetDfsPath.class Get.class GetType.class GetURL.class GrowWrite.class HttpURL.class Interleave.class IsDir.class Length.class ListFiles.class List.class ListTypes.class Mkdir.class NodeStatus.class OpenExclusive.class PeekNamedPipe.class PipeTalk.class Put.class Query.class RenameTo.class SetAttrs.class SetTime.class SlowRead.class SlowWrite.class SmbCrawler.class SmbShell.class SmbTableFile.class SmbTableFileRecord.class T2Crawler.class TestRandomAccess.class TestSmbURL.class TestUnicode.class ThreadedNbtQuery.class ThreadedSmbCrawler.class ThreadedUniQuery.class Torture1.class Torture2.class TortureTest5.class TransactNamedPipe.class URLTest.class VerifyGuest.class VerifyIO.class VerifyReads.class
 
 all: ${CLASSFILES}
 
index 56732e3..3a34136 100644 (file)
@@ -1,10 +1,9 @@
-import jcifs.util.Log;
 import jcifs.smb.SmbFile;
 
 public class Mkdir {
 
-       public static void main( String argv[] ) throws Exception {
-               (new SmbFile( argv[0] )).mkdir();
-       }
+    public static void main( String argv[] ) throws Exception {
+        (new SmbFile( argv[0] )).mkdir();
+    }
 }
 
index 47b26b8..4873b6b 100644 (file)
@@ -2,10 +2,10 @@ import jcifs.netbios.NbtAddress;
 
 public class NodeStatus {
 
-       public static void main( String argv[] ) throws Exception {
-               NbtAddress[] addrs = NbtAddress.getAllByAddress( argv[0] );
-               for( int i = 0; i < addrs.length; i++ ) {
-                       System.out.println( addrs[i] );
-               }
-       }
+    public static void main( String argv[] ) throws Exception {
+        NbtAddress[] addrs = NbtAddress.getAllByAddress( argv[0] );
+        for( int i = 0; i < addrs.length; i++ ) {
+            System.out.println( addrs[i] );
+        }
+    }
 }
index 1107439..79fbf21 100644 (file)
@@ -1,32 +1,32 @@
-import java.io.*;\r
-import javax.servlet.*;\r
-import javax.servlet.http.*;\r
-\r
-public class NtlmHttpAuthExample extends HttpServlet {\r
-\r
-       public void doGet( HttpServletRequest req,\r
-                               HttpServletResponse resp ) throws IOException, ServletException {\r
-               PrintWriter out = resp.getWriter();\r
-\r
-               resp.setContentType( "text/html" );\r
-               out.println( "<HTML><HEAD><TITLE>NTLM HTTP Authentication Example</TITLE></HEAD><BODY>" );\r
-               out.println( "<h2>NTLM HTTP Authentication Example</h2>" );\r
-\r
-               out.println( req.getRemoteUser() + " successfully logged in" );\r
-\r
-               out.println( "<h3>Please submit some form data using POST</h3>" );\r
-               out.println( "<form action=\"NtlmHttpAuthExample\" method=\"post\">" );\r
-               out.println( "<input type=\"text\" name=\"field1\" size=\"20\"/>" );\r
-               out.println( "<input type=\"submit\"/>" );\r
-               out.println( "</form>" );\r
-\r
-               out.println( "field1 = " + req.getParameter( "field1" ));\r
-\r
-               out.println( "</BODY></HTML>" );\r
-       }\r
-       public void doPost( HttpServletRequest req,\r
-                               HttpServletResponse resp ) throws IOException, ServletException {\r
-               doGet( req, resp );\r
-       }\r
-}\r
-\r
+import java.io.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+public class NtlmHttpAuthExample extends HttpServlet {
+
+    public void doGet( HttpServletRequest req,
+                HttpServletResponse resp ) throws IOException, ServletException {
+        PrintWriter out = resp.getWriter();
+
+        resp.setContentType( "text/html" );
+        out.println( "<HTML><HEAD><TITLE>NTLM HTTP Authentication Example</TITLE></HEAD><BODY>" );
+        out.println( "<h2>NTLM HTTP Authentication Example</h2>" );
+
+        out.println( req.getRemoteUser() + " successfully logged in" );
+
+        out.println( "<h3>Please submit some form data using POST</h3>" );
+        out.println( "<form action=\"NtlmHttpAuthExample\" method=\"post\">" );
+        out.println( "<input type=\"text\" name=\"field1\" size=\"20\"/>" );
+        out.println( "<input type=\"submit\"/>" );
+        out.println( "</form>" );
+
+        out.println( "field1 = " + req.getParameter( "field1" ));
+
+        out.println( "</BODY></HTML>" );
+    }
+    public void doPost( HttpServletRequest req,
+                HttpServletResponse resp ) throws IOException, ServletException {
+        doGet( req, resp );
+    }
+}
+
index 98d8914..1e51df0 100644 (file)
@@ -1,49 +1,49 @@
-import java.io.*;\r
-\r
-import java.net.*;\r
-\r
-import jcifs.*;\r
-\r
-public class NtlmHttpClient {\r
-\r
-    public static void main(String[] args) throws Exception {\r
-        // Normally set this outside application.\r
-        // Note that as a side effect due to the way handlers are located,\r
-        // you can also achieve this by simply doing:\r
-             Config.registerSmbURLHandler();\r
-        // which we already do to register the smb handler.\r
-        //String pkgs = System.getProperty("java.protocol.handler.pkgs");\r
-        //pkgs = (pkgs != null) ? "jcifs|" + pkgs : "jcifs";\r
-        //System.setProperty("java.protocol.handler.pkgs", pkgs);\r
-        //\r
-\r
-        if (args == null || args.length < 4) {\r
-            System.out.println("NtlmHttpClient <url> <domain> <user> <password>");\r
-            System.exit(1);\r
-        }\r
-        String location = args[0];\r
-        String domain = args[1];\r
-        String user = args[2];\r
-        String password = args[3];\r
-        // can also specify these in the URL, i.e.\r
-        //     http://DOMAIN%5cuser:password@host/dir/file.html\r
-        // which will override these properties\r
-        Config.setProperty("jcifs.smb.client.domain", domain);\r
-        Config.setProperty("jcifs.smb.client.username", user);\r
-        Config.setProperty("jcifs.smb.client.password", password);\r
-\r
-        try {\r
-            Config.setProperty("jcifs.netbios.hostname",\r
-                    Config.getProperty("jcifs.netbios.hostname",\r
-                            InetAddress.getLocalHost().getHostName()));\r
-        } catch (Exception ex) { }\r
-        URL url = new URL(location);\r
-        BufferedReader reader = new BufferedReader(\r
-                new InputStreamReader(url.openStream()));\r
-        String line;\r
-        while ((line = reader.readLine()) != null) {\r
-            System.out.println(line);\r
-        }\r
-    }\r
-\r
-}\r
+import java.io.*;
+
+import java.net.*;
+
+import jcifs.*;
+
+public class NtlmHttpClient {
+
+    public static void main(String[] args) throws Exception {
+        // Normally set this outside application.
+        // Note that as a side effect due to the way handlers are located,
+        // you can also achieve this by simply doing:
+             Config.registerSmbURLHandler();
+        // which we already do to register the smb handler.
+        //String pkgs = System.getProperty("java.protocol.handler.pkgs");
+        //pkgs = (pkgs != null) ? "jcifs|" + pkgs : "jcifs";
+        //System.setProperty("java.protocol.handler.pkgs", pkgs);
+        //
+
+        if (args == null || args.length < 4) {
+            System.out.println("NtlmHttpClient <url> <domain> <user> <password>");
+            System.exit(1);
+        }
+        String location = args[0];
+        String domain = args[1];
+        String user = args[2];
+        String password = args[3];
+        // can also specify these in the URL, i.e.
+        //     http://DOMAIN%5cuser:password@host/dir/file.html
+        // which will override these properties
+        Config.setProperty("jcifs.smb.client.domain", domain);
+        Config.setProperty("jcifs.smb.client.username", user);
+        Config.setProperty("jcifs.smb.client.password", password);
+
+        try {
+            Config.setProperty("jcifs.netbios.hostname",
+                    Config.getProperty("jcifs.netbios.hostname",
+                            InetAddress.getLocalHost().getHostName()));
+        } catch (Exception ex) { }
+        URL url = new URL(location);
+        BufferedReader reader = new BufferedReader(
+                new InputStreamReader(url.openStream()));
+        String line;
+        while ((line = reader.readLine()) != null) {
+            System.out.println(line);
+        }
+    }
+
+}
index 33e82a6..b68d460 100644 (file)
@@ -3,18 +3,18 @@ import jcifs.smb.SmbFileOutputStream;
 
 public class OpenExclusive {
 
-       public static void main( String argv[] ) throws Exception {
-               SmbFileOutputStream out;
-               SmbFile f = new SmbFile( argv[0], "", null, SmbFile.FILE_NO_SHARE );
-               out = new SmbFileOutputStream( f );
+    public static void main( String argv[] ) throws Exception {
+        SmbFileOutputStream out;
+        SmbFile f = new SmbFile( argv[0], "", null, SmbFile.FILE_NO_SHARE );
+        out = new SmbFileOutputStream( f );
 System.in.read();
-               out.close();
+        out.close();
 System.in.read();
 // OR
-               out = new SmbFileOutputStream( argv[1], SmbFile.FILE_NO_SHARE );
+        out = new SmbFileOutputStream( argv[1], SmbFile.FILE_NO_SHARE );
 System.in.read();
-               out.close();
+        out.close();
 System.in.read();
-       }
+    }
 }
 
index 463e533..33e8475 100644 (file)
@@ -5,60 +5,60 @@ import java.io.IOException;
 
 public class PeekNamedPipe {
 
-       static class ReceiverThread extends Thread {
-               InputStream in;
-               byte[] buf = new byte[20];
-               int n;
+    static class ReceiverThread extends Thread {
+        InputStream in;
+        byte[] buf = new byte[20];
+        int n;
 
-               ReceiverThread( InputStream in ) {
-                       this.in = in;
-               }
-               public void run() {
-                       try {
-                               while( true ) {
-                                       while(( n = in.available() ) == 0 ) {
-                                               System.out.println( "0 available" );
-                                               sleep( 3000 );
-                                       }
-                                       System.out.println( n + " available" );
+        ReceiverThread( InputStream in ) {
+            this.in = in;
+        }
+        public void run() {
+            try {
+                while( true ) {
+                    while(( n = in.available() ) == 0 ) {
+                        System.out.println( "0 available" );
+                        sleep( 3000 );
+                    }
+                    System.out.println( n + " available" );
 
-                                       if(( n = in.read( buf )) == -1 ) {
-                                               break;
-                                       }
-                                       System.out.println( new String( buf, 0, n ));
-                               }
-                       } catch( Exception e ) {
-                               e.printStackTrace();
-                       }
-                       System.out.println( "run finished" );
-               }
-       }
+                    if(( n = in.read( buf )) == -1 ) {
+                        break;
+                    }
+                    System.out.println( new String( buf, 0, n ));
+                }
+            } catch( Exception e ) {
+                e.printStackTrace();
+            }
+            System.out.println( "run finished" );
+        }
+    }
 
-       public static void main( String[] argv ) throws Exception {
-               SmbNamedPipe pipe = new SmbNamedPipe( argv[0], SmbNamedPipe.PIPE_TYPE_RDWR );
-               InputStream in = pipe.getNamedPipeInputStream();
-               OutputStream out = pipe.getNamedPipeOutputStream();
+    public static void main( String[] argv ) throws Exception {
+        SmbNamedPipe pipe = new SmbNamedPipe( argv[0], SmbNamedPipe.PIPE_TYPE_RDWR );
+        InputStream in = pipe.getNamedPipeInputStream();
+        OutputStream out = pipe.getNamedPipeOutputStream();
 
-               ReceiverThread rt = new ReceiverThread( in );
-               rt.start();
+        ReceiverThread rt = new ReceiverThread( in );
+        rt.start();
 
-               StringBuffer sb = new StringBuffer();
-               String msg;
-               int c;
-               while(( c = System.in.read() ) != -1 ) {
-                       if( c == '\n' ) {
-                               msg = sb.toString();
-                               if( msg.startsWith( "exi" )) {
-                                       break;
-                               }
-                               out.write( msg.getBytes() );
-                               sb.setLength( 0 );
-                       } else {
-                               sb.append( (char)c );
-                       }
-               }
-               in.close();
-               out.close();
-       }
+        StringBuffer sb = new StringBuffer();
+        String msg;
+        int c;
+        while(( c = System.in.read() ) != -1 ) {
+            if( c == '\n' ) {
+                msg = sb.toString();
+                if( msg.startsWith( "exi" )) {
+                    break;
+                }
+                out.write( msg.getBytes() );
+                sb.setLength( 0 );
+            } else {
+                sb.append( (char)c );
+            }
+        }
+        in.close();
+        out.close();
+    }
 }
 
index a5fe346..2853bb0 100644 (file)
@@ -5,52 +5,52 @@ import java.io.IOException;
 
 public class PipeTalk {
 
-       static class ReceiverThread extends Thread {
-               InputStream in;
-               byte[] buf = new byte[20];
-               int n;
-
-               ReceiverThread( InputStream in ) {
-                       this.in = in;
-               }
-               public void run() {
-                       try {
-                               while(( n = in.read( buf )) != -1 ) {
-                                       System.out.println( new String( buf, 0, n ));
-                               }
-                       } catch( IOException ioe ) {
-                               ioe.printStackTrace();
-                       }
-               }
-       }
-
-       public static void main( String argv[] ) throws Exception {
-
-               SmbNamedPipe pipe = new SmbNamedPipe( argv[0], SmbNamedPipe.PIPE_TYPE_RDWR );
-               InputStream in = pipe.getNamedPipeInputStream();
-               OutputStream out = pipe.getNamedPipeOutputStream();
-
-               ReceiverThread rt = new ReceiverThread( in );
-               rt.start();
-
-               StringBuffer sb = new StringBuffer();
-               String msg;
-               int c;
-               while(( c = System.in.read() ) != -1 ) {
-                       if( c == '\n' ) {
-                               msg = sb.toString();
-                               if( msg.startsWith( "exi" )) {
-                                       break;
-                               }
-                               System.out.println( sb.toString() );
-                               out.write( msg.getBytes() );
-                               sb.setLength( 0 );
-                       } else {
-                               sb.append( (char)c );
-                       }
-               }
-               in.close();
-               out.close();
-       }
+    static class ReceiverThread extends Thread {
+        InputStream in;
+        byte[] buf = new byte[20];
+        int n;
+
+        ReceiverThread( InputStream in ) {
+            this.in = in;
+        }
+        public void run() {
+            try {
+                while(( n = in.read( buf )) != -1 ) {
+                    System.out.println( new String( buf, 0, n ));
+                }
+            } catch( IOException ioe ) {
+                ioe.printStackTrace();
+            }
+        }
+    }
+
+    public static void main( String argv[] ) throws Exception {
+
+        SmbNamedPipe pipe = new SmbNamedPipe( argv[0], SmbNamedPipe.PIPE_TYPE_RDWR );
+        InputStream in = pipe.getNamedPipeInputStream();
+        OutputStream out = pipe.getNamedPipeOutputStream();
+
+        ReceiverThread rt = new ReceiverThread( in );
+        rt.start();
+
+        StringBuffer sb = new StringBuffer();
+        String msg;
+        int c;
+        while(( c = System.in.read() ) != -1 ) {
+            if( c == '\n' ) {
+                msg = sb.toString();
+                if( msg.startsWith( "exi" )) {
+                    break;
+                }
+                System.out.println( sb.toString() );
+                out.write( msg.getBytes() );
+                sb.setLength( 0 );
+            } else {
+                sb.append( (char)c );
+            }
+        }
+        in.close();
+        out.close();
+    }
 }
 
index 7876329..7ea5603 100644 (file)
@@ -4,28 +4,28 @@ import java.io.FileInputStream;
 
 public class Put {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFile f = new SmbFile( argv[0] );
-               FileInputStream in = new FileInputStream( f.getName() );
-               SmbFileOutputStream out = new SmbFileOutputStream( f );
+        SmbFile f = new SmbFile( argv[0] );
+        FileInputStream in = new FileInputStream( f.getName() );
+        SmbFileOutputStream out = new SmbFileOutputStream( f );
 
-               long t0 = System.currentTimeMillis();
+        long t0 = System.currentTimeMillis();
 
-               byte[] b = new byte[8192];
-               int n, tot = 0;
-               while(( n = in.read( b )) > 0 ) {
-                       out.write( b, 0, n );
-                       tot += n;
-                       System.out.print( '#' );
-               }
+        byte[] b = new byte[8192];
+        int n, tot = 0;
+        while(( n = in.read( b )) > 0 ) {
+            out.write( b, 0, n );
+            tot += n;
+            System.out.print( '#' );
+        }
 
-               long t = System.currentTimeMillis() - t0;
+        long t = System.currentTimeMillis() - t0;
 
-               System.out.println();
-               System.out.println( tot + " bytes transfered in " + ( t / 1000 ) + " seconds at " + (( tot / 1000 ) / Math.max( 1, ( t / 1000 ))) + "Kbytes/sec" );
+        System.out.println();
+        System.out.println( tot + " bytes transfered in " + ( t / 1000 ) + " seconds at " + (( tot / 1000 ) / Math.max( 1, ( t / 1000 ))) + "Kbytes/sec" );
 
-               in.close();
-               out.close();
-       }
+        in.close();
+        out.close();
+    }
 }
index 9889c77..12ab0ff 100644 (file)
@@ -4,15 +4,15 @@ import java.net.InetAddress;
 
 public class Query {
 
-       public static void main( String argv[] ) throws Exception {
-               UniAddress ua;
-               String cn;
+    public static void main( String argv[] ) throws Exception {
+        UniAddress ua;
+        String cn;
 
-               ua = UniAddress.getByName( argv[0] );
+        ua = UniAddress.getByName( argv[0] );
 
-               cn = ua.firstCalledName();
-               do {
-                       System.out.println( "calledName=" + cn );
-               } while(( cn = ua.nextCalledName() ) != null );
-       }
+        cn = ua.firstCalledName();
+        do {
+            System.out.println( "calledName=" + cn );
+        } while(( cn = ua.nextCalledName() ) != null );
+    }
 }
index 13e26c8..fd36760 100644 (file)
@@ -2,11 +2,11 @@ import jcifs.smb.SmbFile;
 
 public class RenameTo {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFile from = new SmbFile( argv[0] );
-               SmbFile to = new SmbFile( argv[1] );
-               from.renameTo( to );
-       }
+        SmbFile from = new SmbFile( argv[0] );
+        SmbFile to = new SmbFile( argv[1] );
+        from.renameTo( to );
+    }
 }
 
index c2d3af9..aa3aa6e 100644 (file)
@@ -2,17 +2,17 @@ import jcifs.smb.*;
 
 public class SetAttrs {
 
-       public static void main( String argv[] ) throws Exception {
-               if( argv.length < 2 ) {
-                       System.err.println( "usage: SetAttrs <smburl> <hexval>" );
-                       return;
-               }
+    public static void main( String argv[] ) throws Exception {
+        if( argv.length < 2 ) {
+            System.err.println( "usage: SetAttrs <smburl> <hexval>" );
+            return;
+        }
 
-               SmbFile f = new SmbFile( argv[0] );
-               SmbFileInputStream in = new SmbFileInputStream( f );
-               int attrs = Integer.parseInt( argv[1], 16 );
+        SmbFile f = new SmbFile( argv[0] );
+        SmbFileInputStream in = new SmbFileInputStream( f );
+        int attrs = Integer.parseInt( argv[1], 16 );
 
-               f.setAttributes( attrs );
-       }
+        f.setAttributes( attrs );
+    }
 }
 
index 6ec41a9..def80c6 100644 (file)
@@ -3,10 +3,10 @@ import jcifs.smb.SmbException;
 
 public class SetTime {
 
-       public static void main( String argv[] ) throws Exception {
-               SmbFile f = new SmbFile( argv[0] );
-               long time = f.getLastModified();
-               f.setLastModified( time + 65000 ); /* add 1 minute and 5 seconds */
-       }
+    public static void main( String argv[] ) throws Exception {
+        SmbFile f = new SmbFile( argv[0] );
+        long time = f.getLastModified();
+        f.setLastModified( time + 65000 ); /* add 1 minute and 5 seconds */
+    }
 }
 
index 4d97386..4268c27 100644 (file)
@@ -4,19 +4,19 @@ import java.io.FileOutputStream;
 
 public class SlowRead {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFileInputStream in = new SmbFileInputStream( argv[0] );
+        SmbFileInputStream in = new SmbFileInputStream( argv[0] );
 
-               byte[] b = new byte[10];
-               int n, tot = 0;
-               while(( n = in.read( b )) > 0 ) {
-                       System.out.write( b, 0, n );
-                       tot += n;
-                       Thread.sleep( 17000 );
-               }
+        byte[] b = new byte[10];
+        int n, tot = 0;
+        while(( n = in.read( b )) > 0 ) {
+            System.out.write( b, 0, n );
+            tot += n;
+            Thread.sleep( 17000 );
+        }
 
-               in.close();
-       }
+        in.close();
+    }
 }
 
index cdd8e80..e1a388d 100644 (file)
@@ -2,16 +2,16 @@ import jcifs.smb.SmbFileOutputStream;
 
 public class SlowWrite {
 
-       public static void main( String argv[] ) throws Exception {
+    public static void main( String argv[] ) throws Exception {
 
-               SmbFileOutputStream out = new SmbFileOutputStream( argv[0] );
+        SmbFileOutputStream out = new SmbFileOutputStream( argv[0] );
 
-               for( int i = 0; i < 2; i++ ) {
-                       out.write( (new String( "hello" + i )).getBytes() );
-                       Thread.sleep( 17000 );
-               }
+        for( int i = 0; i < 2; i++ ) {
+            out.write( (new String( "hello" + i )).getBytes() );
+            Thread.sleep( 17000 );
+        }
 
-               out.close();
-       }
+        out.close();
+    }
 }
 
index 989b853..2beccbe 100644 (file)
@@ -6,38 +6,38 @@ import java.io.IOException;
 
 public class SmbCrawler {
 
-       int maxDepth;
-
-       SmbCrawler( int maxDepth ) {
-               this.maxDepth = maxDepth;
-       }
-
-       void traverse( SmbFile f, int depth ) throws MalformedURLException, IOException {
-
-               if( depth == 0 ) {
-                       return;
-               }
-
-               SmbFile[] l = f.listFiles();
-
-               for(int i = 0; l != null && i < l.length; i++ ) {
-                       try {
-                               for( int j = maxDepth - depth; j > 0; j-- ) {
-                                       System.out.print( "    " );
-                               }
-                               System.out.println( l[i] + " " + l[i].exists() );
-                               if( l[i].isDirectory() ) {
-                                       traverse( l[i], depth - 1 );
-                               }
-                       } catch( IOException ioe ) {
-                               System.out.println( l[i] + ": " + ioe.getMessage() );
-                       }
-               }
-       }
-
-       public static void main(String[] argv) throws Exception {
-               int depth = Integer.parseInt( argv[1] );
-               SmbCrawler sc = new SmbCrawler( depth );
-               sc.traverse( new SmbFile( argv[0] ), depth );
-       }
+    int maxDepth;
+
+    SmbCrawler( int maxDepth ) {
+        this.maxDepth = maxDepth;
+    }
+
+    void traverse( SmbFile f, int depth ) throws MalformedURLException, IOException {
+
+        if( depth == 0 ) {
+            return;
+        }
+
+        SmbFile[] l = f.listFiles();
+
+        for(int i = 0; l != null && i < l.length; i++ ) {
+            try {
+                for( int j = maxDepth - depth; j > 0; j-- ) {
+                    System.out.print( "    " );
+                }
+                System.out.println( l[i] + " " + l[i].exists() );
+                if( l[i].isDirectory() ) {
+                    traverse( l[i], depth - 1 );
+                }
+            } catch( IOException ioe ) {
+                System.out.println( l[i] + ": " + ioe.getMessage() );
+            }
+        }
+    }
+
+    public static void main(String[] argv) throws Exception {
+        int depth = Integer.parseInt( argv[1] );
+        SmbCrawler sc = new SmbCrawler( depth );
+        sc.traverse( new SmbFile( argv[0] ), depth );
+    }
 }
index 7d6d3c2..f1083d0 100644 (file)
@@ -25,166 +25,166 @@ import java.util.Date;
 
 public class SmbShell extends NtlmAuthenticator {
 
-       protected NtlmPasswordAuthentication getNtlmPasswordAuthentication() {
-               System.out.println( getRequestingException().getMessage() +
-                                       " for " + getRequestingURL() );
-               System.out.print( "username: " );
-               try {
-                       int i;
-                       String username = readLine();
-                       String domain = null, password;
+    protected NtlmPasswordAuthentication getNtlmPasswordAuthentication() {
+        System.out.println( getRequestingException().getMessage() +
+                    " for " + getRequestingURL() );
+        System.out.print( "username: " );
+        try {
+            int i;
+            String username = readLine();
+            String domain = null, password;
 
-                       if(( i = username.indexOf( '\\' )) != -1 ) {
-                               domain = username.substring( 0, i );
-                               username = username.substring( i + 1 );
-                       }
-                       System.out.print( "password: " );
-                       password = readLine();
-                       if( password.length() == 0 ) {
-                               return null;
-                       }
-                       return new NtlmPasswordAuthentication( domain, username, password );
-               } catch( Exception e ) {
-               }
-               return null;
-       }
+            if(( i = username.indexOf( '\\' )) != -1 ) {
+                domain = username.substring( 0, i );
+                username = username.substring( i + 1 );
+            }
+            System.out.print( "password: " );
+            password = readLine();
+            if( password.length() == 0 ) {
+                return null;
+            }
+            return new NtlmPasswordAuthentication( domain, username, password );
+        } catch( Exception e ) {
+        }
+        return null;
+    }
 
     public static String readLine() throws Exception {
         int c;
         StringBuffer sb = new StringBuffer();
         while(( c = System.in.read() ) != '\n' ) {
-                       if( c == -1 ) return "";
+            if( c == -1 ) return "";
             sb.append( (char)c );
         }
         return sb.toString().trim();
     }
 
-       String start;
+    String start;
 
-       public SmbShell( String start ) {
-               this.start = start;
-               NtlmAuthenticator.setDefault( this );
-       }
+    public SmbShell( String start ) {
+        this.start = start;
+        NtlmAuthenticator.setDefault( this );
+    }
 
-       void run() throws Exception {
+    void run() throws Exception {
         int c;
         String cmd, prompt;
-               SmbFile conn, tmp;
-               SimpleDateFormat sdf1 = new SimpleDateFormat( "EEE MMM" );
-               SimpleDateFormat sdf2 = new SimpleDateFormat( "d" );
-               SimpleDateFormat sdf3 = new SimpleDateFormat( "yyyy h:mm a" );
-               sdf1.setCalendar( new GregorianCalendar() );
-               sdf2.setCalendar( new GregorianCalendar() );
-               sdf3.setCalendar( new GregorianCalendar() );
+        SmbFile conn, tmp;
+        SimpleDateFormat sdf1 = new SimpleDateFormat( "EEE MMM" );
+        SimpleDateFormat sdf2 = new SimpleDateFormat( "d" );
+        SimpleDateFormat sdf3 = new SimpleDateFormat( "yyyy h:mm a" );
+        sdf1.setCalendar( new GregorianCalendar() );
+        sdf2.setCalendar( new GregorianCalendar() );
+        sdf3.setCalendar( new GregorianCalendar() );
 
-               conn = new SmbFile( start );
+        conn = new SmbFile( start );
         while( true ) {
-                       try {
-                               if( conn.exists() ) {
-                                       prompt = conn.getName() + "> ";
-                               } else {
-                                       System.out.println( "error reading " + conn );
-                                       conn = new SmbFile( "smb://" );
-                                       continue;
-                               }
-                   System.out.print( prompt );
-       
-                   cmd = readLine();
-                   if( cmd.equals( "" ) ) {
-                   } else if( cmd.startsWith( "cd" )) {
-                       int i = cmd.indexOf( ' ' );
-                       String dir;
-                       if( i == -1 || (dir = cmd.substring( i ).trim()).length() == 0 ) {
-                                               conn = new SmbFile( "smb://" );
-                           continue;
-                       }
-                                       tmp = new SmbFile( conn, dir );
-                                       if( tmp.exists() ) {
-                                               if( tmp.isDirectory() ) {
-                                                       conn = tmp;
-                                               } else {
-                                                       System.out.println( dir + " is not a directory" );
-                                               }
-                                       } else {
-                                               System.out.println( "no such directory" );
-                                       }
-                   } else if( cmd.startsWith( "ls" )) {
-                       int i = cmd.indexOf( ' ' );
-                                       SmbFile d = conn;
-                       String dir, wildcard = "*";
-                       if( i != -1 && (dir = cmd.substring( i ).trim()).length() != 0 ) {
-                                               // there's an argument which could be a directory,
-                                               // a wildcard, or a directory with a wildcard appended
-                                               int s = dir.lastIndexOf( '/' );
-                                               int a = dir.lastIndexOf( '*' );
-                                               int q = dir.lastIndexOf( '?' );
+            try {
+                if( conn.exists() ) {
+                    prompt = conn.getName() + "> ";
+                } else {
+                    System.out.println( "error reading " + conn );
+                    conn = new SmbFile( "smb://" );
+                    continue;
+                }
+                System.out.print( prompt );
+    
+                cmd = readLine();
+                if( cmd.equals( "" ) ) {
+                } else if( cmd.startsWith( "cd" )) {
+                    int i = cmd.indexOf( ' ' );
+                    String dir;
+                    if( i == -1 || (dir = cmd.substring( i ).trim()).length() == 0 ) {
+                        conn = new SmbFile( "smb://" );
+                        continue;
+                    }
+                    tmp = new SmbFile( conn, dir );
+                    if( tmp.exists() ) {
+                        if( tmp.isDirectory() ) {
+                            conn = tmp;
+                        } else {
+                            System.out.println( dir + " is not a directory" );
+                        }
+                    } else {
+                        System.out.println( "no such directory" );
+                    }
+                } else if( cmd.startsWith( "ls" )) {
+                    int i = cmd.indexOf( ' ' );
+                    SmbFile d = conn;
+                    String dir, wildcard = "*";
+                    if( i != -1 && (dir = cmd.substring( i ).trim()).length() != 0 ) {
+                        // there's an argument which could be a directory,
+                        // a wildcard, or a directory with a wildcard appended
+                        int s = dir.lastIndexOf( '/' );
+                        int a = dir.lastIndexOf( '*' );
+                        int q = dir.lastIndexOf( '?' );
 
-                                               if(( a != -1 && a > s ) || ( q != -1 && q > s )) {
-                                                       // it's a wildcard
-                                                       if( s == -1 ) {
-                                                               wildcard = dir;
-                                                               d = conn;
-                                                       } else {
-                                                               wildcard = dir.substring( s + 1 );
-                                                               d = new SmbFile( conn, dir.substring( 0, s ));
-                                                       }
-                                               } else {
-                                                       d = new SmbFile( conn, dir );
-                                               }
-                       }
-                                       long t0 = System.currentTimeMillis();
-                                       SmbFile[] list = d.listFiles( wildcard );
-                                       t0 = System.currentTimeMillis() - t0;
-                                       if( list != null ) {
-                                               for( int j = 0; j < list.length; j++ ) {
-                                                       StringBuffer sb = new StringBuffer();
-                                                       Date date = new Date( list[j].lastModified() );
-                                                       Format.print( System.out, "%-40s", list[j].getName() );
-                                                       sb.append( list[j].isDirectory() ? 'd' : '-' );
-                                                       sb.append( list[j].canRead() ? 'r' : '-' );
-                                                       sb.append( list[j].canWrite() ? 'w' : '-' );
-                                                       sb.append( list[j].isHidden() ? 'h' : '-' );
-                                                       sb.append( list[j].getType() == SmbFile.TYPE_WORKGROUP ? 'g' : '-' );
-                                                       Format.print( System.out, "%-6s", sb.toString() );
-                                                       Format.print( System.out, "%10d ", list[j].length() );
+                        if(( a != -1 && a > s ) || ( q != -1 && q > s )) {
+                            // it's a wildcard
+                            if( s == -1 ) {
+                                wildcard = dir;
+                                d = conn;
+                            } else {
+                                wildcard = dir.substring( s + 1 );
+                                d = new SmbFile( conn, dir.substring( 0, s ));
+                            }
+                        } else {
+                            d = new SmbFile( conn, dir );
+                        }
+                    }
+                    long t0 = System.currentTimeMillis();
+                    SmbFile[] list = d.listFiles( wildcard );
+                    t0 = System.currentTimeMillis() - t0;
+                    if( list != null ) {
+                        for( int j = 0; j < list.length; j++ ) {
+                            StringBuffer sb = new StringBuffer();
+                            Date date = new Date( list[j].lastModified() );
+                            Format.print( System.out, "%-40s", list[j].getName() );
+                            sb.append( list[j].isDirectory() ? 'd' : '-' );
+                            sb.append( list[j].canRead() ? 'r' : '-' );
+                            sb.append( list[j].canWrite() ? 'w' : '-' );
+                            sb.append( list[j].isHidden() ? 'h' : '-' );
+                            sb.append( list[j].getType() == SmbFile.TYPE_WORKGROUP ? 'g' : '-' );
+                            Format.print( System.out, "%-6s", sb.toString() );
+                            Format.print( System.out, "%10d ", list[j].length() );
 
-                                                       System.out.print( sdf1.format( date ));
-                                                       Format.print( System.out, "%3s ", sdf2.format( date ));
-                                                       System.out.print( sdf3.format( date ));
-                                                       System.out.println();
-                                               }
-                                               System.out.println( list.length + " items in " + t0 + "ms" );
-                                       } else {
-                                               System.out.println( "no such file or directory" );
-                                       }
-                   } else if( cmd.startsWith( "pwd" )) {
-                                       System.out.println( conn.getCanonicalPath() );
-                   } else if( cmd.startsWith( "q" ) ||
-                               cmd.startsWith( "x" ) ||
-                               cmd.startsWith( "ex" ) ||
-                               cmd.startsWith( "by" )) {
-                       break;
-                   } else {
-                       System.out.println( "commands:" );
-                       System.out.println( "  ls [dir|file]" );
-                       System.out.println( "  cd dir" );
-                       System.out.println( "  pwd" );
-                       System.out.println( "  quit" );
-                   }
-                       } catch( MalformedURLException mue ) {
-                               mue.printStackTrace();
-                               conn = null;
-                       } catch( SmbException se ) {
-                               se.printStackTrace();
-                       } catch( Exception e ) {
-                               e.printStackTrace();
-                               System.exit( 1 );
-                       }
+                            System.out.print( sdf1.format( date ));
+                            Format.print( System.out, "%3s ", sdf2.format( date ));
+                            System.out.print( sdf3.format( date ));
+                            System.out.println();
+                        }
+                        System.out.println( list.length + " items in " + t0 + "ms" );
+                    } else {
+                        System.out.println( "no such file or directory" );
+                    }
+                } else if( cmd.startsWith( "pwd" )) {
+                    System.out.println( conn.getCanonicalPath() );
+                } else if( cmd.startsWith( "q" ) ||
+                            cmd.startsWith( "x" ) ||
+                            cmd.startsWith( "ex" ) ||
+                            cmd.startsWith( "by" )) {
+                    break;
+                } else {
+                    System.out.println( "commands:" );
+                    System.out.println( "  ls [dir|file]" );
+                    System.out.println( "  cd dir" );
+                    System.out.println( "  pwd" );
+                    System.out.println( "  quit" );
+                }
+            } catch( MalformedURLException mue ) {
+                mue.printStackTrace();
+                conn = null;
+            } catch( SmbException se ) {
+                se.printStackTrace();
+            } catch( Exception e ) {
+                e.printStackTrace();
+                System.exit( 1 );
+            }
         }
-               System.exit( 0 );
+        System.exit( 0 );
     }
     public static void main( String[] argv ) throws Exception {
-               SmbShell smbsh = new SmbShell( argv.length > 0 ? argv[0] : "smb://" );
-               smbsh.run();
-       }
+        SmbShell smbsh = new SmbShell( argv.length > 0 ? argv[0] : "smb://" );
+        smbsh.run();
+    }
 }
index 43bc425..9a781b4 100644 (file)
@@ -21,108 +21,108 @@ import java.io.*;
 
 public class SmbTableFile extends SmbRandomAccessFile {
 
-       static final byte BYTE_FULL = (byte)0xFF;
+    static final byte BYTE_FULL = (byte)0xFF;
 
-       byte[] hdr = new byte[512];
-       byte[] buf = new byte[1024];
-       char[] cbuf = new char[512];
-       int recordSize, row;
+    byte[] hdr = new byte[512];
+    byte[] buf = new byte[1024];
+    char[] cbuf = new char[512];
+    int recordSize, row;
 
-       public SmbTableFile( SmbFile file, String mode, int recordSize ) throws IOException {
-               super( file, mode );
-               this.recordSize = recordSize;
-               read( hdr, 0, 512 );
-       }
-       public SmbTableFile( String url, String mode, int shareAccess, int recordSize ) throws IOException {
-               super( url, mode, shareAccess );
-               this.recordSize = recordSize;
-               read( hdr, 0, 512 );
-       }
+    public SmbTableFile( SmbFile file, String mode, int recordSize ) throws IOException {
+        super( file, mode );
+        this.recordSize = recordSize;
+        read( hdr, 0, 512 );
+    }
+    public SmbTableFile( String url, String mode, int shareAccess, int recordSize ) throws IOException {
+        super( url, mode, shareAccess );
+        this.recordSize = recordSize;
+        read( hdr, 0, 512 );
+    }
 
-       public void insert( SmbTableFileRecord tfr ) throws IOException {
-               int i, b = 0;
+    public void insert( SmbTableFileRecord tfr ) throws IOException {
+        int i, b = 0;
 
-               /* Find an unset bit it in the bitmap
-                */
-               for( i = 128; i < 512; i++ ) {
-                       if( hdr[i] != BYTE_FULL ) {
-                               /* bitwise complement inverts each bit
-                                * mask with 0xFF ensures we only use 8 bits of int b
-                                */
-                               b = ~hdr[i] & 0xFF;
-                               /* clever trick to isolate first bit on
-                                */
-                               b = b & -b;
-                               break;
-                       }
-               }
-               if( i == 512 ) {
-                       throw new IOException( "No more space in " + this );
-               }
-               /* convert power of two to position
-                */
-               switch( b ) {
-                       case 1: b = 0; break;
-                       case 2: b = 1; break;
-                       case 4: b = 2; break;
-                       case 8: b = 3; break;
-                       case 16: b = 4; break;
-                       case 32: b = 5; break;
-                       case 64: b = 6; break;
-                       case 128: b = 7; break;
-               }
-               tfr.rowid = (i - 128) * 8 + b;
-               update( tfr );
-       }
-       public void update( SmbTableFileRecord tfr ) throws IOException {
-               int i;
+        /* Find an unset bit it in the bitmap
+         */
+        for( i = 128; i < 512; i++ ) {
+            if( hdr[i] != BYTE_FULL ) {
+                /* bitwise complement inverts each bit
+                 * mask with 0xFF ensures we only use 8 bits of int b
+                 */
+                b = ~hdr[i] & 0xFF;
+                /* clever trick to isolate first bit on
+                 */
+                b = b & -b;
+                break;
+            }
+        }
+        if( i == 512 ) {
+            throw new IOException( "No more space in " + this );
+        }
+        /* convert power of two to position
+         */
+        switch( b ) {
+            case 1: b = 0; break;
+            case 2: b = 1; break;
+            case 4: b = 2; break;
+            case 8: b = 3; break;
+            case 16: b = 4; break;
+            case 32: b = 5; break;
+            case 64: b = 6; break;
+            case 128: b = 7; break;
+        }
+        tfr.rowid = (i - 128) * 8 + b;
+        update( tfr );
+    }
+    public void update( SmbTableFileRecord tfr ) throws IOException {
+        int i;
 
-               seek( 512L + tfr.rowid * recordSize );
-               tfr.encode( this );
+        seek( 512L + tfr.rowid * recordSize );
+        tfr.encode( this );
 
-               i = 128 + tfr.rowid / 8;
-               seek( i );
-               hdr[i] |= 1 << (tfr.rowid % 8);
-               write( hdr[i] );
-       }
-       public void get( SmbTableFileRecord tfr ) throws IOException {
-               seek( 512L + tfr.rowid * recordSize );
-               tfr.decode( this );
-       }
-       public void iterate() {
-               row = 0;
-       }
-       public boolean next( SmbTableFileRecord tfr ) throws IOException {
-               int i, b;
+        i = 128 + tfr.rowid / 8;
+        seek( i );
+        hdr[i] |= 1 << (tfr.rowid % 8);
+        write( hdr[i] );
+    }
+    public void get( SmbTableFileRecord tfr ) throws IOException {
+        seek( 512L + tfr.rowid * recordSize );
+        tfr.decode( this );
+    }
+    public void iterate() {
+        row = 0;
+    }
+    public boolean next( SmbTableFileRecord tfr ) throws IOException {
+        int i, b;
 
-               i = 128 + row / 8;       /* Search bitmap for next bit that is on */
-               b = 1 << (row % 8);
-               for( ; i < 512; i++ ) {
-                       if(( hdr[i] & -b ) != 0 ) {
-                               b = hdr[i] & -b;
-                               b = b & -b;
-                               break;
-                       }
-                       b = 1;
-               }
-               if( i == 512 ) {                   /* Are no more on bits, return */
-                       return false;
-               }
-               switch( b ) {
-                       case 1: b = 0; break;
-                       case 2: b = 1; break;
-                       case 4: b = 2; break;
-                       case 8: b = 3; break;
-                       case 16: b = 4; break;
-                       case 32: b = 5; break;
-                       case 64: b = 6; break;
-                       case 128: b = 7; break;
-               }
-               tfr.rowid = (i - 128) * 8 + b;               /* Set rowid and get */
-               get( tfr );
+        i = 128 + row / 8;       /* Search bitmap for next bit that is on */
+        b = 1 << (row % 8);
+        for( ; i < 512; i++ ) {
+            if(( hdr[i] & -b ) != 0 ) {
+                b = hdr[i] & -b;
+                b = b & -b;
+                break;
+            }
+            b = 1;
+        }
+        if( i == 512 ) {                   /* Are no more on bits, return */
+            return false;
+        }
+        switch( b ) {
+            case 1: b = 0; break;
+            case 2: b = 1; break;
+            case 4: b = 2; break;
+            case 8: b = 3; break;
+            case 16: b = 4; break;
+            case 32: b = 5; break;
+            case 64: b = 6; break;
+            case 128: b = 7; break;
+        }
+        tfr.rowid = (i - 128) * 8 + b;               /* Set rowid and get */
+        get( tfr );
 
-               row = tfr.rowid + 1;               /* Iterate row for next caller */
+        row = tfr.rowid + 1;               /* Iterate row for next caller */
 
-               return true;
-       }
+        return true;
+    }
 }
index a92f9cb..a227ec9 100644 (file)
@@ -19,7 +19,7 @@
 import jcifs.smb.SmbException;
 
 public abstract class SmbTableFileRecord {
-       public int rowid;
-       public abstract void encode( SmbTableFile tf ) throws SmbException;
-       public abstract void decode( SmbTableFile tf ) throws SmbException;
+    public int rowid;
+    public abstract void encode( SmbTableFile tf ) throws SmbException;
+    public abstract void decode( SmbTableFile tf ) throws SmbException;
 }
diff --git a/examples/SsnLimit.java b/examples/SsnLimit.java
new file mode 100644 (file)
index 0000000..15386e7
--- /dev/null
@@ -0,0 +1,17 @@
+import jcifs.*;
+import jcifs.smb.*;
+
+public class SsnLimit {
+
+    public static void main( String argv[] ) throws Exception {
+        jcifs.Config.setProperty( "jcifs.smb.client.ssnLimit", "1" );
+        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication( null, null, null );
+        UniAddress addr = UniAddress.getByName( argv[0] );
+        for( int i = 0; i < 25; i++ ) {
+            SmbSession.logon( addr, auth );
+            Thread.sleep( 1000 );
+        }
+        Thread.sleep( 10000 );
+    }
+}
+
index 2a0359a..14a6ad5 100644 (file)
@@ -25,104 +25,103 @@ import java.io.IOException;
 
 public class T2Crawler {
 
-       class Semaphore {
-               private int value = 0;
+    class Semaphore {
+        private int value = 0;
 
-               Semaphore() {value = 0;}
-               Semaphore(int initial) {value = initial;}
+        Semaphore() {value = 0;}
+        Semaphore(int initial) {value = initial;}
 
-               public synchronized void P() {
-                       value--;
-                       if (value < 0) {
-                               try {
-                                       wait();
-                               } catch (InterruptedException e) {
-                                       e.printStackTrace();
-                               }
-                       }
-               }
+        public synchronized void P() {
+            value--;
+            if (value < 0) {
+                try {
+                    wait();
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+            }
+        }
 
-               public synchronized void V() {
-                       value++;
-                       notify();
-               }
-       }
+        public synchronized void V() {
+            value++;
+            notify();
+        }
+    }
 
-       class CrawlerThread extends Thread {
-               LinkedList list;
-               Semaphore sem;
-               SmbFile dir;
-               int depth;
+    class CrawlerThread extends Thread {
+        LinkedList list;
+        Semaphore sem;
+        SmbFile dir;
+        int depth;
 
 
-               CrawlerThread( SmbFile dir, Semaphore sem, int depth ) {
-                       this.dir = dir;
-                       list = new LinkedList();
-                       list.add( dir );
-                       this.sem = sem;
-                       this.depth = depth;
-               }
+        CrawlerThread( SmbFile dir, Semaphore sem, int depth ) {
+            this.dir = dir;
+            list = new LinkedList();
+            list.add( dir );
+            this.sem = sem;
+            this.depth = depth;
+        }
 
-               public void run() {
-                       SmbFile d;
-                       SmbFile l[];
+        public void run() {
+            SmbFile d;
+            SmbFile l[];
 
-                       while( list.isEmpty() == false ) {
-                               int i;
-                               d = (SmbFile)list.remove( 0 );
-                               try {
-                                       l = d.listFiles();
+            while( list.isEmpty() == false ) {
+                int i;
+                d = (SmbFile)list.remove( 0 );
+                try {
+                    l = d.listFiles();
 
 /* This is flawed. It decrements depth too agressively and causes the
  * thread to finish prematurely. I do not know of a way to fix this
  * because there is no concept of a stack here.
  */
-                                       depth--;
-                                       for( i = 0; i < l.length; i++ ) {
-                                               System.out.println( l[i] );
-                                       //      if( depth++ > 0 && l[i].isDirectory() && !l[i].isHidden() ) {
-                                               if( depth > 0 && l[i].isDirectory() ) {
-                                                       list.add( l[i] );
-                                               }
-                                       }
-                               } catch( Exception e ) {
-                                       System.out.println( d );
-                                       e.printStackTrace();
-                               }
-                       }
-                       sem.V();
-               }
-       }
+                    depth--;
+                    for( i = 0; i < l.length; i++ ) {
+                        System.out.println( l[i] );
+                    //  if( depth++ > 0 && l[i].isDirectory() && !l[i].isHidden() ) {
+                        if( depth > 0 && l[i].isDirectory() ) {
+                            list.add( l[i] );
+                        }
+                    }
+                } catch( Exception e ) {
+                    System.out.println( d );
+                    e.printStackTrace();
+                }
+            }
+            sem.V();
+        }
+    }
 
-       T2Crawler( String dir, int numThreads, int depth ) throws Exception {
-               SmbFile top = new SmbFile( dir );
-               Semaphore sem = new Semaphore( numThreads );
-               SmbFile[] l = top.listFiles();
-               depth--;
-               for( int i = 0; i < l.length; i++ ) {
-                       try {
-                               System.out.println( l[i] );
-                               if( !l[i].isDirectory() || l[i].isHidden() ) {
-                                       continue;
-                               }
-                               if( depth > 0 ) {
-                                       sem.P();
-                                       (new CrawlerThread( l[i], sem, depth )).start();
-                               }
-                       } catch( Exception e ) {
-                               e.printStackTrace();
-                       }
-               }
-               for( int i = 0; i < l.length; i++ ) {
-                       l[i].canRead();
-               }
-       }
-       public static void main(String[] argv) throws Exception {
-               jcifs.util.Log.setMask( Log.EXCEPTIONS | 0x00010000 );
-               if( argv.length < 3) {
-                       System.out.println( "$ java -Djcifs.properties=miallen.prp T2Crawler <dir> <num threads> <depth>");
-                       System.exit(1);
-               }
-               new T2Crawler( argv[0], Integer.parseInt( argv[1] ), Integer.parseInt( argv[2] ));
-       }
+    T2Crawler( String dir, int numThreads, int depth ) throws Exception {
+        SmbFile top = new SmbFile( dir );
+        Semaphore sem = new Semaphore( numThreads );
+        SmbFile[] l = top.listFiles();
+        depth--;
+        for( int i = 0; i < l.length; i++ ) {
+            try {
+                System.out.println( l[i] );
+                if( !l[i].isDirectory() || l[i].isHidden() ) {
+                    continue;
+                }
+                if( depth > 0 ) {
+                    sem.P();
+                    (new CrawlerThread( l[i], sem, depth )).start();
+                }
+            } catch( Exception e ) {
+                e.printStackTrace();
+            }
+        }
+        for( int i = 0; i < l.length; i++ ) {
+            l[i].canRead();
+        }
+    }
+    public static void main(String[] argv) throws Exception {
+        if( argv.length < 3) {
+            System.out.println( "$ java -Djcifs.properties=miallen.prp T2Crawler <dir> <num threads> <depth>");
+            System.exit(1);
+        }
+        new T2Crawler( argv[0], Integer.parseInt( argv[1] ), Integer.parseInt( argv[2] ));
+    }
 }
index ec9305d..e25f7c8 100644 (file)
@@ -2,120 +2,120 @@ import jcifs.smb.*;
 
 public class TestRandomAccess {
 
-       public static class TestRecord extends SmbTableFileRecord {
+    public static class TestRecord extends SmbTableFileRecord {
 
-               boolean f1; /* 1 byte */
-               byte f2;    /* 1 byte */
-               int f3;     /* 1 byte */
-               short f4;   /* 2 bytes */
-               int f5;     /* 2 bytes */
-               char f6;    /* 2 bytes */
-               int f7;     /* 4 bytes */
-               long f8;    /* 8 bytes */
-               float f9;   /* 4 bytes */
-               double f10; /* 8 bytes */
-               String f11; /* 95 bytes max */
+        boolean f1; /* 1 byte */
+        byte f2;    /* 1 byte */
+        int f3;     /* 1 byte */
+        short f4;   /* 2 bytes */
+        int f5;     /* 2 bytes */
+        char f6;    /* 2 bytes */
+        int f7;     /* 4 bytes */
+        long f8;    /* 8 bytes */
+        float f9;   /* 4 bytes */
+        double f10; /* 8 bytes */
+        String f11; /* 95 bytes max */
                     /* 128 bytes total */
 
-               public TestRecord() {
-               }
-               public TestRecord( boolean f1, byte f2, int f3, short f4,
-                               int f5, char f6, int f7, long f8,
-                               float f9, double f10, String f11 ) {
-                       this.f1 = f1;
-                       this.f2 = f2;
-                       this.f3 = f3;
-                       this.f4 = f4;
-                       this.f5 = f5;
-                       this.f6 = f6;
-                       this.f7 = f7;
-                       this.f8 = f8;
-                       this.f9 = f9;
-                       this.f10 = f10;
-                       this.f11 = f11;
-               }
+        public TestRecord() {
+        }
+        public TestRecord( boolean f1, byte f2, int f3, short f4,
+                int f5, char f6, int f7, long f8,
+                float f9, double f10, String f11 ) {
+            this.f1 = f1;
+            this.f2 = f2;
+            this.f3 = f3;
+            this.f4 = f4;
+            this.f5 = f5;
+            this.f6 = f6;
+            this.f7 = f7;
+            this.f8 = f8;
+            this.f9 = f9;
+            this.f10 = f10;
+            this.f11 = f11;
+        }
 
-               public void encode( SmbTableFile tf ) throws SmbException {
-                       tf.writeBoolean( f1 );
-                       tf.writeByte( f2 );
-                       tf.writeByte( f3 );
-                       tf.writeShort( f4 );
-                       tf.writeShort( f5 );
-                       tf.writeChar( f6 );
-                       tf.writeInt( f7 );
-                       tf.writeLong( f8 );
-                       tf.writeFloat( f9 );
-                       tf.writeDouble( f10 );
-                       tf.writeUTF( f11 );
-               }
-               public void decode( SmbTableFile tf ) throws SmbException {
-                       f1 = tf.readBoolean();
-                       f2 = tf.readByte();
-                       f3 = tf.readUnsignedByte();
-                       f4 = tf.readShort();
-                       f5 = tf.readUnsignedShort();
-                       f6 = tf.readChar();
-                       f7 = tf.readInt();
-                       f8 = tf.readLong();
-                       f9 = tf.readFloat();
-                       f10 = tf.readDouble();
-                       f11 = tf.readUTF();
-               }
-               public boolean equals( Object obj ) {
-                       if( obj instanceof TestRecord ) {
-                               TestRecord r = (TestRecord)obj;
+        public void encode( SmbTableFile tf ) throws SmbException {
+            tf.writeBoolean( f1 );
+            tf.writeByte( f2 );
+            tf.writeByte( f3 );
+            tf.writeShort( f4 );
+            tf.writeShort( f5 );
+            tf.writeChar( f6 );
+            tf.writeInt( f7 );
+            tf.writeLong( f8 );
+            tf.writeFloat( f9 );
+            tf.writeDouble( f10 );
+            tf.writeUTF( f11 );
+        }
+        public void decode( SmbTableFile tf ) throws SmbException {
+            f1 = tf.readBoolean();
+            f2 = tf.readByte();
+            f3 = tf.readUnsignedByte();
+            f4 = tf.readShort();
+            f5 = tf.readUnsignedShort();
+            f6 = tf.readChar();
+            f7 = tf.readInt();
+            f8 = tf.readLong();
+            f9 = tf.readFloat();
+            f10 = tf.readDouble();
+            f11 = tf.readUTF();
+        }
+        public boolean equals( Object obj ) {
+            if( obj instanceof TestRecord ) {
+                TestRecord r = (TestRecord)obj;
 
-                               return r.f1 == f1 &&
-                                       r.f2 == f2 &&
-                                       r.f3 == f3 &&
-                                       r.f4 == f4 &&
-                                       r.f5 == f5 &&
-                                       r.f6 == f6 &&
-                                       r.f7 == f7 &&
-                                       r.f8 == f8 &&
-                                       r.f9 == f9 &&
-                                       r.f10 == f10 &&
-                                       f11.equals( r.f11 );
-                       }
-                       return false;
-               }
-       }
+                return r.f1 == f1 &&
+                    r.f2 == f2 &&
+                    r.f3 == f3 &&
+                    r.f4 == f4 &&
+                    r.f5 == f5 &&
+                    r.f6 == f6 &&
+                    r.f7 == f7 &&
+                    r.f8 == f8 &&
+                    r.f9 == f9 &&
+                    r.f10 == f10 &&
+                    f11.equals( r.f11 );
+            }
+            return false;
+        }
+    }
 
-       public static void main( String[] argv ) throws Exception {
-               if( argv.length < 2 ) {
-                       System.err.println( "usage: TestRandomAccess <url> <N> (1 for read or 2 for write with <index>)" );
-                       return;
-               }
-               SmbTableFile stf;
-               int op = Integer.parseInt( argv[1] );
+    public static void main( String[] argv ) throws Exception {
+        if( argv.length < 2 ) {
+            System.err.println( "usage: TestRandomAccess <url> <N> (1 for read or 2 for write with <index>)" );
+            return;
+        }
+        SmbTableFile stf;
+        int op = Integer.parseInt( argv[1] );
 
-               TestRecord r1 = new TestRecord( true, (byte)0x12, 0x34, (short)0x1122,
-                                       0x3344, '\u04c1', 0x11112222, 0x1111111122222222L,
-                                       0.1122f, 3344.1, "The surface is smooth like glass" );
+        TestRecord r1 = new TestRecord( true, (byte)0x12, 0x34, (short)0x1122,
+                    0x3344, '\u04c1', 0x11112222, 0x1111111122222222L,
+                    0.1122f, 3344.1, "The surface is smooth like glass" );
 
-               if( op == 3 ) {
-                       stf = new SmbTableFile( argv[0], "rw", 0, 128 );
-                       int newLength = Integer.parseInt( argv[2] );
-                       stf.setLength( newLength );
-                       System.out.println( "truncated to " + newLength );
-               } else if( op == 1 ) {
-                       SmbFile file = new SmbFile( argv[0], null, SmbFile.FILE_SHARE_READ );
-                       stf = new SmbTableFile( file, "rw", 128 );
-                       stf.insert( r1 );
-                       System.out.println( "rowid: " + r1.rowid );
-               } else {
-                       if( argv.length < 3 ) {
-                               System.err.println( "usage: TestRandomAccess <url> <N> (1 for read or 2 for write with <index>)" );
-                               return;
-                       }
-                       stf = new SmbTableFile( argv[0], "r", 0, 128 );
-                       TestRecord r2 = new TestRecord();
-                       r2.rowid = Integer.parseInt( argv[2] );
-                       stf.get( r2 );
-                       System.out.println( "r1.equals( r2 ) = " + r1.equals( r2 ));
-               }
+        if( op == 3 ) {
+            stf = new SmbTableFile( argv[0], "rw", 0, 128 );
+            int newLength = Integer.parseInt( argv[2] );
+            stf.setLength( newLength );
+            System.out.println( "truncated to " + newLength );
+        } else if( op == 1 ) {
+            SmbFile file = new SmbFile( argv[0], null, SmbFile.FILE_SHARE_READ );
+            stf = new SmbTableFile( file, "rw", 128 );
+            stf.insert( r1 );
+            System.out.println( "rowid: " + r1.rowid );
+        } else {
+            if( argv.length < 3 ) {
+                System.err.println( "usage: TestRandomAccess <url> <N> (1 for read or 2 for write with <index>)" );
+                return;
+            }
+            stf = new SmbTableFile( argv[0], "r", 0, 128 );
+            TestRecord r2 = new TestRecord();
+            r2.rowid = Integer.parseInt( argv[2] );
+            stf.get( r2 );
+            System.out.println( "r1.equals( r2 ) = " + r1.equals( r2 ));
+        }
 
-               stf.close();
-       }
+        stf.close();
+    }
 }
 
index 2ef4d96..b937ed4 100644 (file)
@@ -4,161 +4,161 @@ import java.io.*;
 
 public class TestSmbURL {
 
-       static void test( String url, String name ) throws Exception {
-               SmbFile f;
+    static void test( String url, String name ) throws Exception {
+        SmbFile f;
 
-               if( name == null ) name = "";
+        if( name == null ) name = "";
 
-               System.out.println( "INPUT[" + url + ", " + name + "]");
-               try {
-                       f = new SmbFile( url, name );
-               } catch( Exception e ) {
-                       e.printStackTrace();
-                       return;
-               }
+        System.out.println( "INPUT[" + url + ", " + name + "]");
+        try {
+            f = new SmbFile( url, name );
+        } catch( Exception e ) {
+            e.printStackTrace();
+            return;
+        }
 
-               System.out.print( "toString()         : " );
-               try {
-                       System.out.println( f.toString() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "getCanonicalPath() : " );
-               try {
-                       System.out.println( f.getCanonicalPath() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "getUncPath()       : " );
-               try {
-                       System.out.println( f.getUncPath() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "getName()          : " );
-               try {
-                       System.out.println( f.getName() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "getParent()        : " );
-               try {
-                       System.out.println( f.getParent() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "getPath()          : " );
-               try {
-                       System.out.println( f.getPath() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "getServer()        : " );
-               try {
-                       System.out.println( f.getServer() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "getShare()         : " );
-               try {
-                       System.out.println( f.getShare() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "exists()           : " );
-               try {
-                       System.out.println( f.exists() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "isDirectory()      : " );
-               try {
-                       System.out.println( f.isDirectory() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "isFile()           : " );
-               try {
-                       System.out.println( f.isFile() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "length()           : " );
-               try {
-                       System.out.println( f.length() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "lastModified()     : " );
-               try {
-                       System.out.println( (new Date( f.lastModified() )));
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
-               System.out.print( "toURL().toString() : " );
-               try {
-                       System.out.println( f.toURL() );
-               } catch( Exception e ) {
-                       e.printStackTrace(); System.out.println();
-               }
+        System.out.print( "toString()         : " );
+        try {
+            System.out.println( f.toString() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "getCanonicalPath() : " );
+        try {
+            System.out.println( f.getCanonicalPath() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "getUncPath()       : " );
+        try {
+            System.out.println( f.getUncPath() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "getName()          : " );
+        try {
+            System.out.println( f.getName() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "getParent()        : " );
+        try {
+            System.out.println( f.getParent() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "getPath()          : " );
+        try {
+            System.out.println( f.getPath() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "getServer()        : " );
+        try {
+            System.out.println( f.getServer() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "getShare()         : " );
+        try {
+            System.out.println( f.getShare() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "exists()           : " );
+        try {
+            System.out.println( f.exists() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "isDirectory()      : " );
+        try {
+            System.out.println( f.isDirectory() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "isFile()           : " );
+        try {
+            System.out.println( f.isFile() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "length()           : " );
+        try {
+            System.out.println( f.length() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "lastModified()     : " );
+        try {
+            System.out.println( (new Date( f.lastModified() )));
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
+        System.out.print( "toURL().toString() : " );
+        try {
+            System.out.println( f.toURL() );
+        } catch( Exception e ) {
+            e.printStackTrace(); System.out.println();
+        }
 
-               System.in.read();
-       }
+        System.in.read();
+    }
 
-       public static void main( String argv[] ) throws Exception {
-               String workgroup, server, share, path, file;
+    public static void main( String argv[] ) throws Exception {
+        String workgroup, server, share, path, file;
 
-               if( argv.length < 5 ) {
-                       System.err.println( "TestSmbURL workgroup server share path file" );
-                       System.exit( 1 );
-               }
+        if( argv.length < 5 ) {
+            System.err.println( "TestSmbURL workgroup server share path file" );
+            System.exit( 1 );
+        }
 
-               workgroup = argv[0];
-               server = argv[1];
-               share = argv[2];
-               path = argv[3];
-               file = argv[4];
+        workgroup = argv[0];
+        server = argv[1];
+        share = argv[2];
+        path = argv[3];
+        file = argv[4];
 
 /*
-               System.out.println();
-               System.out.println( "-- UNUSUAL --" );
-               System.out.println();
-               test( "smb://" + server, "../" + server + "/" + share );
-               test( "smb://foo", "../" + workgroup );
-               test( "smb://", ".." );
+        System.out.println();
+        System.out.println( "-- UNUSUAL --" );
+        System.out.println();
+        test( "smb://" + server, "../" + server + "/" + share );
+        test( "smb://foo", "../" + workgroup );
+        test( "smb://", ".." );
 */
 
-               System.out.println();
-               System.out.println( "-- BASICS: ONE ARGUMENT --" );
-               System.out.println();
-               test( "smb://" + server + "/" + share + "/" + path + "/" + file, null );
-               test( "smb://" + server + "/" + share + "/" + path + "/", null );
-               test( "smb://" + server + "/" + share + "/", null );
-               test( "smb://" + server + "/", null );
-               test( "smb://" + workgroup + "/", null );
-               test( "smb://", null );
+        System.out.println();
+        System.out.println( "-- BASICS: ONE ARGUMENT --" );
+        System.out.println();
+        test( "smb://" + server + "/" + share + "/" + path + "/" + file, null );
+        test( "smb://" + server + "/" + share + "/" + path + "/", null );
+        test( "smb://" + server + "/" + share + "/", null );
+        test( "smb://" + server + "/", null );
+        test( "smb://" + workgroup + "/", null );
+        test( "smb://", null );
 
-               System.out.println();
-               System.out.println( "-- BASICS: TWO ARGUMENTS --" );
-               System.out.println();
-               test( "smb://" + server + "/" + share + "/" + path + "/", file);
-               test( "smb://" + server + "/" + share + "/", path + "/" + file);
-               test( "smb://" + server + "/", share + "/" + path + "/" + file);
-               test( "smb://", server + "/" + share + "/" + path + "/" + file);
-               test( "smb://", "smb://" + server + "/" + share + "/" + path + "/" + file);
-               test( "smb://", "smb://" + server + "/");
-               test( "smb://", "smb://" + workgroup + "/");
-               test( "smb://", "smb://");
-               test( "smb://" + server + "/share/", "smb://");
+        System.out.println();
+        System.out.println( "-- BASICS: TWO ARGUMENTS --" );
+        System.out.println();
+        test( "smb://" + server + "/" + share + "/" + path + "/", file);
+        test( "smb://" + server + "/" + share + "/", path + "/" + file);
+        test( "smb://" + server + "/", share + "/" + path + "/" + file);
+        test( "smb://", server + "/" + share + "/" + path + "/" + file);
+        test( "smb://", "smb://" + server + "/" + share + "/" + path + "/" + file);
+        test( "smb://", "smb://" + server + "/");
+        test( "smb://", "smb://" + workgroup + "/");
+        test( "smb://", "smb://");
+        test( "smb://" + server + "/share/", "smb://");
 
-               System.out.println();
-               System.out.println( "-- CANONICALIZATION --" );
-               System.out.println();
-               test( "smb://" + server + "/" + share + "/foo/../" + path + "/" + file, null );
-               test( "smb://" + server + "/foo/bar/.././../" + share + "/" + path + "/" + file, null );
-               test( "smb://" + server + "/foo/bar/.././.././" + share + "/fake/../" + path + "/" + file, null );
-               test( "smb://" + server + "/foo/bar/.././.././", share + "/fake/../" + path + "/" + file);
-               test( "smb://", server + "/foo/bar/.././.././" + share + "/fake/../" + path + "/" + file);
-       }
+        System.out.println();
+        System.out.println( "-- CANONICALIZATION --" );
+        System.out.println();
+        test( "smb://" + server + "/" + share + "/foo/../" + path + "/" + file, null );
+        test( "smb://" + server + "/foo/bar/.././../" + share + "/" + path + "/" + file, null );
+        test( "smb://" + server + "/foo/bar/.././.././" + share + "/fake/../" + path + "/" + file, null );
+        test( "smb://" + server + "/foo/bar/.././.././", share + "/fake/../" + path + "/" + file);
+        test( "smb://", server + "/foo/bar/.././.././" + share + "/fake/../" + path + "/" + file);
+    }
 }
 
index fc8e703..4ecfeb3 100644 (file)
@@ -3,58 +3,58 @@ import jcifs.smb.*;
 import jcifs.util.*;
 
 public class TestUnicode {
-       static SmbFile dir;
+    static SmbFile dir;
 
-       public static void mkobj( String name ) throws Exception {
-               int r = (int)(Math.random() * 100.0);
-               if( r < 50 ) {
-                       SmbFile d = new SmbFile( dir.getParent(), dir.getName() + "/" + name );
-                       d.mkdir();
-                       if( r < 15 ) {
-                               dir = d;
-                       }
-               } else {
-                       SmbFileOutputStream out = new SmbFileOutputStream( dir.getParent() + "/" + dir.getName() + "/" + name );
-                       out.close();
-               }
-       }
+    public static void mkobj( String name ) throws Exception {
+        int r = (int)(Math.random() * 100.0);
+        if( r < 50 ) {
+            SmbFile d = new SmbFile( dir.getParent(), dir.getName() + "/" + name );
+            d.mkdir();
+            if( r < 15 ) {
+                dir = d;
+            }
+        } else {
+            SmbFileOutputStream out = new SmbFileOutputStream( dir.getParent() + "/" + dir.getName() + "/" + name );
+            out.close();
+        }
+    }
 
-       public static void main( String argv[] ) throws Exception {
-               if( argv.length < 1 ) {
-                       throw new IllegalArgumentException( "Must provide path to directory in which to run test" );
-               }
-               FileInputStream in = new FileInputStream( "data" );
-               byte[] b = new byte[4096];
-               int n = in.read( b );
-               String data = new String( b, 0, n, "UTF-8" );
-               char[] d = data.toCharArray();
+    public static void main( String argv[] ) throws Exception {
+        if( argv.length < 1 ) {
+            throw new IllegalArgumentException( "Must provide path to directory in which to run test" );
+        }
+        FileInputStream in = new FileInputStream( "data" );
+        byte[] b = new byte[4096];
+        int n = in.read( b );
+        String data = new String( b, 0, n, "UTF-8" );
+        char[] d = data.toCharArray();
 
-               dir = new SmbFile( argv[0] + "/TestUnicode" );
-               try {
-                       dir.delete();
-               } catch( SmbException se ) {
-                       se.printStackTrace();
-               }
-               dir.mkdir();
+        dir = new SmbFile( argv[0] + "/TestUnicode" );
+        try {
+            dir.delete();
+        } catch( SmbException se ) {
+            se.printStackTrace();
+        }
+        dir.mkdir();
 
-               int i, s, max = 8;
-               for( i = s = 0; i < d.length; i++ ) {
-                       switch (d[i]) {
-                               case '"': case '/': case '\\': case '[': case ']':
-                               case ':': case '|': case '<': case '>': case '=':
-                               case ';': case ',': case '*': case '?': case '\n':
-                                       d[i] = '_';
-                       }
-                       if(Character.isWhitespace( d[i] )) {
-                               if( i == s ) {
-                                       s++;
-                               }
-                               if( i > (s + max)) {
-                                       String name = new String( d, s, i - s );
-                                       mkobj( name );
-                                       s = i + 1;
-                               }
-                       }
-               }
-       }
+        int i, s, max = 8;
+        for( i = s = 0; i < d.length; i++ ) {
+            switch (d[i]) {
+                case '"': case '/': case '\\': case '[': case ']':
+                case ':': case '|': case '<': case '>': case '=':
+                case ';': case ',': case '*': case '?': case '\n':
+                    d[i] = '_';
+            }
+            if(Character.isWhitespace( d[i] )) {
+                if( i == s ) {
+                    s++;
+                }
+                if( i > (s + max)) {
+                    String name = new String( d, s, i - s );
+                    mkobj( name );
+                    s = i + 1;
+                }
+            }
+        }
+    }
 }
index 2addf3c..6848ddd 100644 (file)
@@ -2,37 +2,37 @@ import jcifs.netbios.*;
 
 public class ThreadedNbtQuery {
 
-       static class QThread extends Thread {
-               String name; 
+    static class QThread extends Thread {
+        String name; 
 
-               QThread( String name ) {
-                       this.name = name;
-               }
+        QThread( String name ) {
+            this.name = name;
+        }
 
-               public void run() {
-                       try {
-                               yield();
-                               System.out.println( getName() + ": started" );
-                               NbtAddress.getByName( name );
-                               System.out.println( getName() + ": done" );
-                       } catch( Exception x ) {
-                               x.printStackTrace();
-                       }
-               }
-       }
+        public void run() {
+            try {
+                yield();
+                System.out.println( getName() + ": started" );
+                NbtAddress.getByName( name );
+                System.out.println( getName() + ": done" );
+            } catch( Exception x ) {
+                x.printStackTrace();
+            }
+        }
+    }
 
-       public static void main(String[] argv) throws Exception {
-               if( argv.length < 2 ) {
-                       System.out.println( "java ThreadedNbtQuery name [name [name [...]]]" );
-                       return;
-               }
+    public static void main(String[] argv) throws Exception {
+        if( argv.length < 2 ) {
+            System.out.println( "java ThreadedNbtQuery name [name [name [...]]]" );
+            return;
+        }
 
-               QThread[] t = new QThread[argv.length];
-               for( int i = 0; i < argv.length; i++ ) {
-                       t[i] = new QThread( argv[i] );
-               }
-               for( int j = 0; j < argv.length; j++ ) {
-                       t[j].start();
-               }
-       }
+        QThread[] t = new QThread[argv.length];
+        for( int i = 0; i < argv.length; i++ ) {
+            t[i] = new QThread( argv[i] );
+        }
+        for( int j = 0; j < argv.length; j++ ) {
+            t[j].start();
+        }
+    }
 }
index 0b515ad..c6d02cc 100644 (file)
@@ -17,7 +17,6 @@
  */
 
 import jcifs.smb.SmbFile;
-import jcifs.util.Log;
 import java.util.LinkedList;
 import java.util.ListIterator;
 import java.net.MalformedURLException;
@@ -25,113 +24,113 @@ import java.io.IOException;
 
 public class ThreadedSmbCrawler {
 
-       static int workingThreads = 0;
+    static int workingThreads = 0;
 
-       class DirEntry {
-               SmbFile dir;
-               int depth;
+    class DirEntry {
+        SmbFile dir;
+        int depth;
 
-               DirEntry( SmbFile dir, int depth ) {
-                       this.dir = dir;
-                       this.depth = depth;
-               }
-       }
+        DirEntry( SmbFile dir, int depth ) {
+            this.dir = dir;
+            this.depth = depth;
+        }
+    }
 
-       class SmbCrawlerThread extends Thread {
+    class SmbCrawlerThread extends Thread {
 
-               StringBuffer sb = new StringBuffer();
+        StringBuffer sb = new StringBuffer();
 
-               public void run() {
-                       while( true ) {
-                               try {
-                                       DirEntry e;
+        public void run() {
+            while( true ) {
+                try {
+                    DirEntry e;
 
-                                       synchronized( dirList ) {
-                                               while( dirList.isEmpty() ) {
+                    synchronized( dirList ) {
+                        while( dirList.isEmpty() ) {
 //System.err.println( "workingThreads=" + workingThreads );
-                                                       if( workingThreads == 0 ) {
-                                                               return; // done
-                                                       }
-                                                       dirList.wait( 2000 );
-                                               }
-                                               e = (DirEntry)dirList.remove( 0 );
-                                               if( e.depth == 0 ) {
-                                                       continue;
-                                               }
-                                               workingThreads++;
-                                       }
-
-                                       SmbFile[] l = e.dir.listFiles();
-
-                                       int n = maxDepth - e.depth;
-
-                                       for(int i = 0; l != null && i < l.length; i++ ) {
-                                               try {
-                                                       sb.setLength( 0 );
-                                                       for( int k = 0; k < n; k++ ) {
-                                                               sb.append( "    " );
-                                                       }
-                                                       SmbFile d = l[i];
-                                                       System.err.println( sb.append( d ));
-                                                       if( d.isDirectory() ) {
-                                                               synchronized( dirList ) {
-                                                                       dirList.add( new DirEntry( d, e.depth - 1 ));
-                                                                       dirList.notify();
-                                                               }
-                                                       }
-                                               } catch( IOException ioe ) {
-                                                       ioe.printStackTrace();
-                                               }
-                                       }
-                                       synchronized( dirList ) {
-                                               workingThreads--;
-                                       }
-                               } catch( Exception x ) {
-                                       synchronized( dirList ) {
-                                               workingThreads--;
-                                       }
-                                       x.printStackTrace();
-                               }
-                       }
-               }
-       }
-
-       LinkedList dirList;
-       int maxDepth, numThreads;
-       Thread[] threads;
-
-       ThreadedSmbCrawler( String dir, int maxDepth, int numThreads ) throws Exception {
-               this.maxDepth = maxDepth;
-               this.numThreads = numThreads;
-               threads = new Thread[numThreads];
-               dirList = new LinkedList();
-               dirList.add( new DirEntry( new SmbFile( dir ), maxDepth ));
-       }
-
-       long go() throws Exception {
-               int i;
-               long start = System.currentTimeMillis();
-
-               for( i = 0; i < numThreads; i++ ) {
-                       threads[i] = new SmbCrawlerThread();
-                       threads[i].start();
-               }
-               for( i = 0; i < numThreads; i++ ) {
-                       threads[i].join();
-               }
-
-               return System.currentTimeMillis() - start;
-       }
-
-       public static void main(String[] argv) throws Exception {
-               ThreadedSmbCrawler tsc;
-
-               if( argv.length < 3 ) {
-                       System.err.println( "usage: ThreadedSmbCrawler dir depth numThreads" );
-                       System.exit( 1 );
-               }
-
-               tsc = new ThreadedSmbCrawler( argv[0], Integer.parseInt( argv[1] ), Integer.parseInt( argv[2] ));
-               System.err.println( "Crawling Complete: " + (tsc.go() / 1000) + "sec" );
-       }
+                            if( workingThreads == 0 ) {
+                                return; // done
+                            }
+                            dirList.wait( 2000 );
+                        }
+                        e = (DirEntry)dirList.remove( 0 );
+                        if( e.depth == 0 ) {
+                            continue;
+                        }
+                        workingThreads++;
+                    }
+
+                    SmbFile[] l = e.dir.listFiles();
+
+                    int n = maxDepth - e.depth;
+
+                    for(int i = 0; l != null && i < l.length; i++ ) {
+                        try {
+                            sb.setLength( 0 );
+                            for( int k = 0; k < n; k++ ) {
+                                sb.append( "    " );
+                            }
+                            SmbFile d = l[i];
+                            System.err.println( sb.append( d ));
+                            if( d.isDirectory() ) {
+                                synchronized( dirList ) {
+                                    dirList.add( new DirEntry( d, e.depth - 1 ));
+                                    dirList.notify();
+                                }
+                            }
+                        } catch( IOException ioe ) {
+                            ioe.printStackTrace();
+                        }
+                    }
+                    synchronized( dirList ) {
+                        workingThreads--;
+                    }
+                } catch( Exception x ) {
+                    synchronized( dirList ) {
+                        workingThreads--;
+                    }
+                    x.printStackTrace();
+                }
+            }
+        }
+    }
+
+    LinkedList dirList;
+    int maxDepth, numThreads;
+    Thread[] threads;
+
+    ThreadedSmbCrawler( String dir, int maxDepth, int numThreads ) throws Exception {
+        this.maxDepth = maxDepth;
+        this.numThreads = numThreads;
+        threads = new Thread[numThreads];
+        dirList = new LinkedList();
+        dirList.add( new DirEntry( new SmbFile( dir ), maxDepth ));
+    }
+
+    long go() throws Exception {
+        int i;
+        long start = System.currentTimeMillis();
+
+        for( i = 0; i < numThreads; i++ ) {
+            threads[i] = new SmbCrawlerThread();
+            threads[i].start();
+        }
+        for( i = 0; i < numThreads; i++ ) {
+            threads[i].join();
+        }
+
+        return System.currentTimeMillis() - start;
+    }
+
+    public static void main(String[] argv) throws Exception {
+        ThreadedSmbCrawler tsc;
+
+        if( argv.length < 3 ) {
+            System.err.println( "usage: ThreadedSmbCrawler dir depth numThreads" );
+            System.exit( 1 );
+        }
+
+        tsc = new ThreadedSmbCrawler( argv[0], Integer.parseInt( argv[1] ), Integer.parseInt( argv[2] ));
+        System.err.println( "Crawling Complete: " + (tsc.go() / 1000) + "sec" );
+    }
 }
index feb756c..5fcd894 100644 (file)
@@ -3,48 +3,48 @@ import jcifs.*;
 
 public class ThreadedUniQuery {
 
-       static class QThread extends Thread {
-               String name; 
+    static class QThread extends Thread {
+        String name; 
 
-               QThread( String name ) {
-                       super( name + "-thread" );
-                       this.name = name;
-               }
+        QThread( String name ) {
+            super( name + "-thread" );
+            this.name = name;
+        }
 
-               public void run() {
-                       try {
-                               System.out.println( getName() + ": started" );
-                               for( int i = 0; i < 15; i++ ) {
-                                       Thread.sleep( (long)(Math.random() * 1000L ));
-                                       try {
-                                               UniAddress.getByName( name, true );
-                                       } catch( UnknownHostException uhe ) {
-                                               uhe.printStackTrace();
-                                       }
-                               }
-                               System.out.println( getName() + ": done" );
-                       } catch( Exception x ) {
-                               x.printStackTrace();
-                       }
-               }
-       }
+        public void run() {
+            try {
+                System.out.println( getName() + ": started" );
+                for( int i = 0; i < 15; i++ ) {
+                    Thread.sleep( (long)(Math.random() * 1000L ));
+                    try {
+                        UniAddress.getByName( name, true );
+                    } catch( UnknownHostException uhe ) {
+                        uhe.printStackTrace();
+                    }
+                }
+                System.out.println( getName() + ": done" );
+            } catch( Exception x ) {
+                x.printStackTrace();
+            }
+        }
+    }
 
-       public static void main(String[] argv) throws Exception {
-               if( argv.length < 2 ) {
-                       System.out.println( "java ThreadedUniQuery name [name [name [...]]]" );
-                       return;
-               }
+    public static void main(String[] argv) throws Exception {
+        if( argv.length < 2 ) {
+            System.out.println( "java ThreadedUniQuery name [name [name [...]]]" );
+            return;
+        }
 
-               QThread[] t = new QThread[argv.length];
-               for( int i = 0; i < argv.length; i++ ) {
-                       t[i] = new QThread( argv[i] );
-               }
-               for( int j = 0; j < argv.length; j++ ) {
-                       t[j].start();
-               }
-               for( int j = 0; j < argv.length; j++ ) {
-                       t[j].join();
-               }
-               Runtime.getRuntime().exit(0);
-       }
+        QThread[] t = new QThread[argv.length];
+        for( int i = 0; i < argv.length; i++ ) {
+            t[i] = new QThread( argv[i] );
+        }
+        for( int j = 0; j < argv.length; j++ ) {
+            t[j].start();
+        }
+        for( int j = 0; j < argv.length; j++ ) {
+            t[j].join();
+        }
+        Runtime.getRuntime().exit(0);
+    }
 }
index 053f1ec..9f054e1 100644 (file)
@@ -4,99 +4,99 @@ import java.util.*;
 
 class Worker extends Thread {
 
-       Torture1 t;
-       Exception e;
-
-       Worker( Torture1 t ) {
-               this.t = t;
-               e = null;
-       }
-       public void run() {
-               try {
-                       t.torture();
-               } catch( Exception e ) {
-                       this.e = e;
-               }
-       }
+    Torture1 t;
+    Exception e;
+
+    Worker( Torture1 t ) {
+        this.t = t;
+        e = null;
+    }
+    public void run() {
+        try {
+            t.torture();
+        } catch( Exception e ) {
+            this.e = e;
+        }
+    }
 }
 
 public class Torture1 {
 
-       Properties prp;
-
-       Torture1( Properties prp ) {
-               this.prp = prp;
-       }
-
-       void compare( SmbFile f1, SmbFile f2 ) throws Exception {
-               if( f1.isDirectory() && f2.isDirectory() ) {
-                       SmbFile[] dirents = f1.listFiles();
-                       SmbFile f;
-                       for( int i = 0; i < dirents.length; i++ ) {
-                               f = new SmbFile( f2, dirents[i].getName() );
-                               compare( dirents[i], f );
-                       }
-               }
-               if( f1.isDirectory() != f2.isDirectory() ) {
-                       System.err.println( "directory comparison failed" );
-               }
-               if( f1.isFile() != f2.isFile() ) {
-                       System.err.println( "file comparison failed" );
-               }
-               if( f1.getType() != f2.getType() ) {
-                       System.err.println( "type comparison failed" );
-               }
-               if( f1.getName().equals( f2.getName() ) == false ) {
-                       System.err.println( "name comparison failed: " + f1.getName() + " " + f2.getName() );
-               }
-               if( f1.length() != f2.length() ) {
-                       System.err.println( "length comparison failed: " + f1.length() + " " + f2.length() );
-               }
-       }
-
-       void torture() throws Exception {
-               String domain, username, password, server, share, directory;
-               NtlmPasswordAuthentication ntlm;
-
-               domain = prp.getProperty( "torture.dst.domain" );
-               username = prp.getProperty( "torture.dst.username" );
-               password = prp.getProperty( "torture.dst.password" );
-
-               ntlm = new NtlmPasswordAuthentication( domain, username, password );
-
-               server = prp.getProperty( "torture.dst.server" );
-               share = prp.getProperty( "torture.dst.share" );
-               directory = prp.getProperty( "torture.dst.directory" );
-
-               SmbFile dst = new SmbFile( "smb://", ntlm );
-               dst = new SmbFile( dst, server );
-               dst = new SmbFile( dst, share );
-               dst = new SmbFile( dst, directory );
-
-               SmbFile src = new SmbFile( prp.getProperty( "torture.src.url" ));
+    Properties prp;
+
+    Torture1( Properties prp ) {
+        this.prp = prp;
+    }
+
+    void compare( SmbFile f1, SmbFile f2 ) throws Exception {
+        if( f1.isDirectory() && f2.isDirectory() ) {
+            SmbFile[] dirents = f1.listFiles();
+            SmbFile f;
+            for( int i = 0; i < dirents.length; i++ ) {
+                f = new SmbFile( f2, dirents[i].getName() );
+                compare( dirents[i], f );
+            }
+        }
+        if( f1.isDirectory() != f2.isDirectory() ) {
+            System.err.println( "directory comparison failed" );
+        }
+        if( f1.isFile() != f2.isFile() ) {
+            System.err.println( "file comparison failed" );
+        }
+        if( f1.getType() != f2.getType() ) {
+            System.err.println( "type comparison failed" );
+        }
+        if( f1.getName().equals( f2.getName() ) == false ) {
+            System.err.println( "name comparison failed: " + f1.getName() + " " + f2.getName() );
+        }
+        if( f1.length() != f2.length() ) {
+            System.err.println( "length comparison failed: " + f1.length() + " " + f2.length() );
+        }
+    }
+
+    void torture() throws Exception {
+        String domain, username, password, server, share, directory;
+        NtlmPasswordAuthentication ntlm;
+
+        domain = prp.getProperty( "torture.dst.domain" );
+        username = prp.getProperty( "torture.dst.username" );
+        password = prp.getProperty( "torture.dst.password" );
+
+        ntlm = new NtlmPasswordAuthentication( domain, username, password );
+
+        server = prp.getProperty( "torture.dst.server" );
+        share = prp.getProperty( "torture.dst.share" );
+        directory = prp.getProperty( "torture.dst.directory" );
+
+        SmbFile dst = new SmbFile( "smb://", ntlm );
+        dst = new SmbFile( dst, server );
+        dst = new SmbFile( dst, share );
+        dst = new SmbFile( dst, directory );
+
+        SmbFile src = new SmbFile( prp.getProperty( "torture.src.url" ));
 
 System.err.println( src + " --> " + dst );
 System.in.read();
 
-               if( dst.exists() ) {
-                       dst.delete();
-               }
-               src.copyTo( dst );
+        if( dst.exists() ) {
+            dst.delete();
+        }
+        src.copyTo( dst );
 System.err.println( "CopyTo done" );
 System.in.read();
-               compare( src, dst );
+        compare( src, dst );
 System.err.println( "Test Complete" );
-       }
-
-       public static void main( String[] argv ) throws Exception {
-               Properties prp = new Properties();
-               prp.load( new FileInputStream( "torture.prp" ));
-               Torture1 t = new Torture1( prp );
-               Worker w = new Worker( t );
-               w.start();
-               w.join();
-               if( w.e != null ) {
-                       throw w.e;
-               }
-       }
+    }
+
+    public static void main( String[] argv ) throws Exception {
+        Properties prp = new Properties();
+        prp.load( new FileInputStream( "torture.prp" ));
+        Torture1 t = new Torture1( prp );
+        Worker w = new Worker( t );
+        w.start();
+        w.join();
+        if( w.e != null ) {
+            throw w.e;
+        }
+    }
 }
index f8737d0..bd9c7c7 100644 (file)
 import java.io.*;
 import jcifs.smb.*;
+import jcifs.util.Hexdump;
 import java.util.*;
 
 public class Torture2 extends Thread {
 
-       SmbFile from, to;
+    SmbFile from, to;
 
-       Torture2( String from, String to ) throws Exception {
-               this.from = new SmbFile( from );
-               this.to = new SmbFile( to );
-       }
+    Torture2( String from, String to ) throws Exception {
+        this.from = new SmbFile( from );
+        this.to = new SmbFile( to );
+    }
 
-       public void run() {
-               try {
-                       copyAndVerify();
-               } catch( Exception e ) {
-                       e.printStackTrace();
-               }
-       }
+    public void run() {
+        try {
+            copyAndVerify();
+        } catch( Exception e ) {
+            e.printStackTrace();
+        }
+    }
 
-       void compare( SmbFile f1, SmbFile f2 ) throws Exception {
+    void compare( SmbFile f1, SmbFile f2 ) throws Exception {
 //System.err.println( f1.getName() + " | " + f2.getName() );
 try {
-               if( f1.isDirectory() && f2.isDirectory() ) {
-                       SmbFile[] dirents = f1.listFiles();
-                       SmbFile f;
-                       for( int i = 0; i < dirents.length; i++ ) {
-                               f = new SmbFile( f2, dirents[i].getName() );
+        if( f1.isDirectory() && f2.isDirectory() ) {
+            SmbFile[] dirents = f1.listFiles();
+            SmbFile f;
+            for( int i = 0; i < dirents.length; i++ ) {
+                f = new SmbFile( f2, dirents[i].getName() );
 //System.err.println( f2 + " + " + dirents[i].getName() + " = " + f + ": isDirectory=" + f.isDirectory() );
-                               compare( dirents[i], f );
-                       }
-               }
-               if( f1.isDirectory() != f2.isDirectory() ) {
-                       System.err.println( "directory comparison failed: " + f1.getName() + ": " + f1.isDirectory() + " " + f2.isDirectory() );
-               }
-               if( f1.isFile() != f2.isFile() ) {
-                       System.err.println( "file comparison failed: " + f1.getName() + ": " + f1.isFile() + " " + f2.isFile() );
-               }
-               if( f1.getType() != f2.getType() ) {
-                       System.err.println( "type comparison failed: " + f1.getName() + " " + f2.getName() );
-               }
-               if( f1.getName().equals( f2.getName() ) == false ) {
-                       System.err.println( "name comparison failed: " + f1.getName() + " " + f2.getName() );
-               }
-               if( f1.length() != f2.length() ) {
-                       System.err.println( "length comparison failed: " + f1.getName() + ": " + f1.length() + " " + f2.length() );
-               }
-               if( f1.getAttributes() != f2.getAttributes() ) {
-                       System.err.println( "attribute comparison failed: " + f1.getName() + ": " + Log.getHexString( f1.getAttributes(), 4 ) + " " + Log.getHexString( f2.getAttributes(), 4 ));
-               }
-               if( Math.abs( f1.createTime() - f2.createTime() ) > 1000 ) {
-                       System.err.println( "create time comparison failed: " + f1.getName() + ": " + f1.createTime() + " " + f2.createTime() );
-               }
-               if( Math.abs( f1.lastModified() - f2.lastModified() ) > 1000 ) {
-                       System.err.println( "last modified comparison failed: " + f1.getName() + ": " + f1.lastModified() + " " + f2.lastModified() );
-               }
+                compare( dirents[i], f );
+            }
+        }
+        if( f1.isDirectory() != f2.isDirectory() ) {
+            System.err.println( "directory comparison failed: " + f1.getName() + ": " + f1.isDirectory() + " " + f2.isDirectory() );
+        }
+        if( f1.isFile() != f2.isFile() ) {
+            System.err.println( "file comparison failed: " + f1.getName() + ": " + f1.isFile() + " " + f2.isFile() );
+        }
+        if( f1.getType() != f2.getType() ) {
+            System.err.println( "type comparison failed: " + f1.getName() + " " + f2.getName() );
+        }
+        if( f1.getName().equals( f2.getName() ) == false ) {
+            System.err.println( "name comparison failed: " + f1.getName() + " " + f2.getName() );
+        }
+        if( f1.length() != f2.length() ) {
+            System.err.println( "length comparison failed: " + f1.getName() + ": " + f1.length() + " " + f2.length() );
+        }
+        if( f1.getAttributes() != f2.getAttributes() ) {
+            System.err.println( "attribute comparison failed: " + f1.getName() + ": " + Hexdump.toHexString( f1.getAttributes(), 4 ) + " " + Hexdump.toHexString( f2.getAttributes(), 4 ));
+        }
+        if( Math.abs( f1.createTime() - f2.createTime() ) > 1000 ) {
+            System.err.println( "create time comparison failed: " + f1.getName() + ": " + f1.createTime() + " " + f2.createTime() );
+        }
+        if( Math.abs( f1.lastModified() - f2.lastModified() ) > 1000 ) {
+            System.err.println( "last modified comparison failed: " + f1.getName() + ": " + f1.lastModified() + " " + f2.lastModified() );
+        }
 } catch( Exception x ) {
-       System.err.println( "Exception comparing: " + f1 + " | " + f2 );
-       x.printStackTrace();
+    System.err.println( "Exception comparing: " + f1 + " | " + f2 );
+    x.printStackTrace();
 }
-       }
+    }
 
-       void copyAndVerify() throws Exception {
-               from.copyTo( to );
-               compare( from, to );
-       }
+    void copyAndVerify() throws Exception {
+        from.copyTo( to );
+        compare( from, to );
+    }
 
-       public static void main( String[] argv ) throws Exception {
-               Properties prp;
-               Torture2[] threads;
-               String from, to;
-               int i;
+    public static void main( String[] argv ) throws Exception {
+        Properties prp;
+        Torture2[] threads;
+        String from, to;
+        int i;
 
-               if( argv.length < 1 ) {
-                       System.err.println( "Torture2 <properties file>" );
-                       System.exit( 1 );
-               }
+        if( argv.length < 1 ) {
+            System.err.println( "Torture2 <properties file>" );
+            System.exit( 1 );
+        }
 
-               prp = new Properties();
-               prp.load( new FileInputStream( argv[0] ));
+        prp = new Properties();
+        prp.load( new FileInputStream( argv[0] ));
 
-               threads = new Torture2[10];
+        threads = new Torture2[10];
 
-               for( i = 0; i < 10; i++ ) {
-                       from = prp.getProperty( "thread." + i + ".from.url" );
-                       to = prp.getProperty( "thread." + i + ".to.url" );
-                       if( from == null || to == null ) {
-                               break;
-                       }
-                       threads[i] = new Torture2( from, to );
-                       threads[i].start();
-                       Thread.sleep( 12345 );
-               }
-               while( i-- > 0 ) {
-                       threads[i].join();
-               }
-               System.err.println( "Test complete" );
-       }
+        for( i = 0; i < 10; i++ ) {
+            from = prp.getProperty( "thread." + i + ".from.url" );
+            to = prp.getProperty( "thread." + i + ".to.url" );
+            if( from == null || to == null ) {
+                break;
+            }
+            threads[i] = new Torture2( from, to );
+            threads[i].start();
+            Thread.sleep( 12345 );
+        }
+        while( i-- > 0 ) {
+            threads[i].join();
+        }
+        System.err.println( "Test complete" );
+    }
 }
 
index aa24f73..717e3d3 100644 (file)
@@ -3,35 +3,34 @@ import java.util.Enumeration;
 
 public class TortureTest5 extends Thread {
 
-       String name;
+    String name;
 
-       TortureTest5( String name ) {
-               this.name = name;
-       }
+    TortureTest5( String name ) {
+        this.name = name;
+    }
 
-       public void run() {
-               try {
-                       System.out.println( UniAddress.getByName( name ));
-               } catch( Exception e ) {
-                       e.printStackTrace();
-               }
-       }
+    public void run() {
+        try {
+            System.out.println( UniAddress.getByName( name ));
+        } catch( Exception e ) {
+            e.printStackTrace();
+        }
+    }
 
-       public static void main( String[] argv ) throws Exception {
-       //      jcifs.util.Log.setMask( jcifs.util.Log.EXCEPTIONS | jcifs.util.Log.HEX_DUMPS );
-       //      jcifs.util.Config.setProperty( "retryCount", "1" );
-       //      jcifs.util.Config.setProperty( "soTimeout", "1000" );
+    public static void main( String[] argv ) throws Exception {
+    //  jcifs.util.Config.setProperty( "retryCount", "1" );
+    //  jcifs.util.Config.setProperty( "soTimeout", "1000" );
 
-               Thread[] threads = new Thread[30];
-               for( int i = 0; i < argv.length; i++ ) {
-                       threads[i] = new TortureTest5( argv[i] );
-               }
-               for( int t = 0; t < argv.length; t++ ) {
-                       threads[t].start();
-               }
-               for( int j = 0; j < argv.length; j++ ) {
-                       threads[j].join();
-               }
-               System.exit( 0 );
-       }
+        Thread[] threads = new Thread[30];
+        for( int i = 0; i < argv.length; i++ ) {
+            threads[i] = new TortureTest5( argv[i] );
+        }
+        for( int t = 0; t < argv.length; t++ ) {
+            threads[t].start();
+        }
+        for( int j = 0; j < argv.length; j++ ) {
+            threads[j].join();
+        }
+        System.exit( 0 );
+    }
 }
index 1f451e3..e97fb81 100644 (file)
@@ -6,31 +6,31 @@ import java.io.FileOutputStream;
 
 public class TransactNamedPipe {
 
-       public static void main( String[] argv ) throws Exception {
+    public static void main( String[] argv ) throws Exception {
 
-               if( argv.length < 2 ) {
-                       throw new IllegalArgumentException(
-                                               "args: <smburl> <filedatatosend> <filetowriterecvdata>" );
-               }
+        if( argv.length < 2 ) {
+            throw new IllegalArgumentException(
+                        "args: <smburl> <filedatatosend> <filetowriterecvdata>" );
+        }
 
-               byte[] b = new byte[65535];
-               FileInputStream fin = new FileInputStream( argv[1] );
-               FileOutputStream fos = new FileOutputStream( argv[2] );
+        byte[] b = new byte[65535];
+        FileInputStream fin = new FileInputStream( argv[1] );
+        FileOutputStream fos = new FileOutputStream( argv[2] );
 
-               SmbNamedPipe pipe = new SmbNamedPipe( argv[0],
-                               SmbNamedPipe.PIPE_TYPE_RDWR | SmbNamedPipe.PIPE_TYPE_TRANSACT );
-               OutputStream out = pipe.getNamedPipeOutputStream();
-               InputStream in = pipe.getNamedPipeInputStream();
+        SmbNamedPipe pipe = new SmbNamedPipe( argv[0],
+                SmbNamedPipe.PIPE_TYPE_RDWR | SmbNamedPipe.PIPE_TYPE_TRANSACT );
+        OutputStream out = pipe.getNamedPipeOutputStream();
+        InputStream in = pipe.getNamedPipeInputStream();
 
-               int n = fin.read( b );
-               System.out.println( "writing " + n + " bytes" );
-               out.write( b, 0, n );
-               n = in.read(b);
-               System.out.println( "read " + n + " bytes" );
-               fos.write(b, 0, n );
+        int n = fin.read( b );
+        System.out.println( "writing " + n + " bytes" );
+        out.write( b, 0, n );
+        n = in.read(b);
+        System.out.println( "read " + n + " bytes" );
+        fos.write(b, 0, n );
 
-               fin.close();
-               fos.close();
-               out.close();
-       }
+        fin.close();
+        fos.close();
+        out.close();
+    }
 }
index 60f1aa3..8c1d919 100644 (file)
@@ -3,29 +3,29 @@ import java.util.*;
 
 public class URLTest {
 
-       public static void main( String[] argv ) throws Exception {
-               URL url;
+    public static void main( String[] argv ) throws Exception {
+        URL url;
 
-               jcifs.Config.registerSmbURLHandler();
+        jcifs.Config.registerSmbURLHandler();
 
-               if( argv.length > 2 ) {
-                       url = new URL( new URL( new URL( argv[0] ), argv[1] ), argv[2] );
-               } else if( argv.length > 1 ) {
-                       url = new URL( new URL( argv[0] ), argv[1] );
-               } else {
-                       url = new URL( argv[0] );
-               }
-               System.out.println( "   authority: " + url.getAuthority() );
-               System.out.println( "        file: " + url.getFile() );
-               System.out.println( "        host: " + url.getHost() );
-               System.out.println( "        port: " + url.getPort() );
-               System.out.println( "        path: " + url.getPath() );
-               System.out.println( "       query: " + url.getQuery() );
-               System.out.println( "         ref: " + url.getRef() );
-               System.out.println( "    userinfo: " + url.getUserInfo() );
-               System.out.println( "externalform: " + url.toExternalForm() );
-               System.out.println( "      string: " + url.toString() );
+        if( argv.length > 2 ) {
+            url = new URL( new URL( new URL( argv[0] ), argv[1] ), argv[2] );
+        } else if( argv.length > 1 ) {
+            url = new URL( new URL( argv[0] ), argv[1] );
+        } else {
+            url = new URL( argv[0] );
+        }
+        System.out.println( "   authority: " + url.getAuthority() );
+        System.out.println( "        file: " + url.getFile() );
+        System.out.println( "        host: " + url.getHost() );
+        System.out.println( "        port: " + url.getPort() );
+        System.out.println( "        path: " + url.getPath() );
+        System.out.println( "       query: " + url.getQuery() );
+        System.out.println( "         ref: " + url.getRef() );
+        System.out.println( "    userinfo: " + url.getUserInfo() );
+        System.out.println( "externalform: " + url.toExternalForm() );
+        System.out.println( "      string: " + url.toString() );
 
-               System.exit( 0 );
-       }
+        System.exit( 0 );
+    }
 }
index 9e78d3f..8b0d6be 100644 (file)
@@ -1,28 +1,27 @@
 import jcifs.netbios.NbtAddress;
 import jcifs.smb.*;
-import jcifs.util.Log;
 import java.util.Date;
 
 public class VerifyGuest {
 
-       public static void list( SmbFile dir ) {
-               try {
-                       long t1 = System.currentTimeMillis();
-                       SmbFile[] files = dir.listFiles();
-                       long t2 = System.currentTimeMillis() - t1;
+    public static void list( SmbFile dir ) {
+        try {
+            long t1 = System.currentTimeMillis();
+            SmbFile[] files = dir.listFiles();
+            long t2 = System.currentTimeMillis() - t1;
 
-                       for( int i = 0; i < files.length; i++ ) {
-                               System.out.print( " " + files[i].getName() );
-                       }
-                       System.out.println();
-                       System.out.println( files.length + " files in " + t2 + "ms" );
-               } catch( Exception e ) {
-                       e.printStackTrace();
-               }
-       }
+            for( int i = 0; i < files.length; i++ ) {
+                System.out.print( " " + files[i].getName() );
+            }
+            System.out.println();
+            System.out.println( files.length + " files in " + t2 + "ms" );
+        } catch( Exception e ) {
+            e.printStackTrace();
+        }
+    }
 
-       public static void main( String[] argv ) throws Exception {
-               list( new SmbFile( "smb://miallen2/" ));
-               list( new SmbFile( "smb://miallen2/pub/", new NtlmPasswordAuthentication( "dom", "user", "pass" )));
-       }
+    public static void main( String[] argv ) throws Exception {
+        list( new SmbFile( "smb://miallen2/" ));
+        list( new SmbFile( "smb://miallen2/pub/", new NtlmPasswordAuthentication( "dom", "user", "pass" )));
+    }
 }
index e99fc64..93cbab7 100644 (file)
@@ -4,73 +4,73 @@ import java.io.*;
 
 public class VerifyIO {
 
-       static File get( SmbFile f0 ) throws Exception {
-               int i;
-               File f1;
-               byte[] buf = new byte[8192];
-
-               f1 = new File( f0.getName() );
-               FileOutputStream out = new FileOutputStream( f1 );
-               SmbFileInputStream in = new SmbFileInputStream( f0 );
-
-               while(( i = in.read( buf )) > 0 ) {
-                       out.write( buf, 0, i );
-                       System.err.print( '.' );
-               }
-
-               in.close();
-               out.close();
-
-               return f1;
-       }
-       static void put( SmbFile f2 ) throws Exception {
-               int i;
-               byte[] buf = new byte[8192];
-
-               FileInputStream in = new FileInputStream( f2.getName() );
-               SmbFileOutputStream out = new SmbFileOutputStream( f2 );
-
-               while(( i = in.read( buf )) > 0 ) {
-                       out.write( buf, 0, i );
-                       System.err.print( '-' );
-               }
-
-               in.close();
-               out.close();
-       }
-
-       public static void main(String[] argv) throws Exception {
-               BufferedReader in;
-               String name;
-
-               if( argv.length < 2 ) {
-                       System.err.println( "Must provide file of SMB URLs and destination directory" );
-                       System.exit( 1 );
-               }
-
-               in = new BufferedReader( new FileReader( argv[0] ));
-               while(( name = in.readLine() ) != null ) {
-                       SmbFile f0, f2;
-                       File f1;
-
-                       System.err.print( name + ": " );
-                       f0 = new SmbFile( name );
-                       f1 = get( f0 );
-
-                       if( f0.length() != f1.length() ) {
-                               throw new RuntimeException( "File lengths do not match: f0=" + f0.length() + ",f1=" + f1.length() );
-                       }
-
-                       f2 = new SmbFile( argv[1] + "/" + f0.getName() );
-                       put( f2 );
-
-                       if( f1.length() != f2.length() ) {
-                               throw new RuntimeException( "File lengths do not match: f1=" + f1.length() + ",f2=" + f2.length() );
-                       }
-
-                       f1.delete();
-                       System.err.println( " ok" );
-               }
-       }
+    static File get( SmbFile f0 ) throws Exception {
+        int i;
+        File f1;
+        byte[] buf = new byte[8192];
+
+        f1 = new File( f0.getName() );
+        FileOutputStream out = new FileOutputStream( f1 );
+        SmbFileInputStream in = new SmbFileInputStream( f0 );
+
+        while(( i = in.read( buf )) > 0 ) {
+            out.write( buf, 0, i );
+            System.err.print( '.' );
+        }
+
+        in.close();
+        out.close();
+
+        return f1;
+    }
+    static void put( SmbFile f2 ) throws Exception {
+        int i;
+        byte[] buf = new byte[8192];
+
+        FileInputStream in = new FileInputStream( f2.getName() );
+        SmbFileOutputStream out = new SmbFileOutputStream( f2 );
+
+        while(( i = in.read( buf )) > 0 ) {
+            out.write( buf, 0, i );
+            System.err.print( '-' );
+        }
+
+        in.close();
+        out.close();
+    }
+
+    public static void main(String[] argv) throws Exception {
+        BufferedReader in;
+        String name;
+
+        if( argv.length < 2 ) {
+            System.err.println( "Must provide file of SMB URLs and destination directory" );
+            System.exit( 1 );
+        }
+
+        in = new BufferedReader( new FileReader( argv[0] ));
+        while(( name = in.readLine() ) != null ) {
+            SmbFile f0, f2;
+            File f1;
+
+            System.err.print( name + ": " );
+            f0 = new SmbFile( name );
+            f1 = get( f0 );
+
+            if( f0.length() != f1.length() ) {
+                throw new RuntimeException( "File lengths do not match: f0=" + f0.length() + ",f1=" + f1.length() );
+            }
+
+            f2 = new SmbFile( argv[1] + "/" + f0.getName() );
+            put( f2 );
+
+            if( f1.length() != f2.length() ) {
+                throw new RuntimeException( "File lengths do not match: f1=" + f1.length() + ",f2=" + f2.length() );
+            }
+
+            f1.delete();
+            System.err.println( " ok" );
+        }
+    }
 }
 
index 7d8b6da..4c66152 100644 (file)
@@ -4,75 +4,75 @@ import java.io.*;
 
 public class VerifyReads {
 
-       int maxDepth;
-       byte[] buf = new byte[8192];
+    int maxDepth;
+    byte[] buf = new byte[8192];
 
-       VerifyReads( int maxDepth ) {
-               this.maxDepth = maxDepth;
-       }
+    VerifyReads( int maxDepth ) {
+        this.maxDepth = maxDepth;
+    }
 
-       void mkdir( File dir ) {
-               if( dir != null && !dir.exists() ) {
-                       mkdir( dir.getParentFile() );
-                       dir.mkdir();
-               }
-       }
+    void mkdir( File dir ) {
+        if( dir != null && !dir.exists() ) {
+            mkdir( dir.getParentFile() );
+            dir.mkdir();
+        }
+    }
 
-       void copy( SmbFile f, String path, int depth ) throws MalformedURLException, IOException {
-               int i, d;
-               File localFile, dir;
-               SmbFile[] list;
+    void copy( SmbFile f, String path, int depth ) throws MalformedURLException, IOException {
+        int i, d;
+        File localFile, dir;
+        SmbFile[] list;
 
-               if( depth == 0 ) {
-                       return;
-               }
+        if( depth == 0 ) {
+            return;
+        }
 
-               localFile = new File( path + "/" + f.getName() );
-               d = f.getName().lastIndexOf( '.' );
+        localFile = new File( path + "/" + f.getName() );
+        d = f.getName().lastIndexOf( '.' );
 
-               if( f.isDirectory() ) {
+        if( f.isDirectory() ) {
 
-                       list = f.listFiles();
+            list = f.listFiles();
 
-                       for( i = 0; i < list.length; i++ ) {
-                               copy( list[i], path + "/" + f.getName(), depth - 1 );
-                       }
-               } else if( d > 1 && f.getName().substring( d ).equalsIgnoreCase( ".ini" )) {
+            for( i = 0; i < list.length; i++ ) {
+                copy( list[i], path + "/" + f.getName(), depth - 1 );
+            }
+        } else if( d > 1 && f.getName().substring( d ).equalsIgnoreCase( ".ini" )) {
 
-                       mkdir( new File( path ));
+            mkdir( new File( path ));
 
-                       SmbFileInputStream in = new SmbFileInputStream( f );
-                       FileOutputStream out = new FileOutputStream( localFile );
+            SmbFileInputStream in = new SmbFileInputStream( f );
+            FileOutputStream out = new FileOutputStream( localFile );
 
-                       while(( i = in.read( buf )) > 0 ) {
-                               out.write( buf, 0, i );
-                       }
+            while(( i = in.read( buf )) > 0 ) {
+                out.write( buf, 0, i );
+            }
 
-                       in.close();
-                       out.close();
-               }
-       }
+            in.close();
+            out.close();
+        }
+    }
 
-       public static void main(String[] argv) throws Exception {
-               VerifyReads cd;
-               SmbFile top;
-               int depth;
+    public static void main(String[] argv) throws Exception {
+        VerifyReads cd;
+        SmbFile top;
+        int depth;
 
-               if( argv.length < 2 ) {
-                       System.err.println( "Must specify ini directory location (e.g. smb://mydom\\;user:pass@nyc-19b9/apps) followd by the maximum traversal depth");
-                       System.exit( 1 );
-               }
+        if( argv.length < 2 ) {
+            System.err.println( "Must specify ini directory location (e.g. smb://mydom\\;user:pass@nyc-19b9/apps) followd by the maximum traversal depth");
+            System.exit( 1 );
+        }
 
-               depth = Integer.parseInt( argv[1] );
-               cd = new VerifyReads( depth );
-               top = new SmbFile( argv[0] );
+        depth = Integer.parseInt( argv[1] );
+        cd = new VerifyReads( depth );
+        top = new SmbFile( argv[0] );
 
-               if( !top.isDirectory() ) {
-                       System.err.println( "The path specified is not a directory" );
-                       System.exit( 1 );
-               }
+        if( !top.isDirectory() ) {
+            System.err.println( "The path specified is not a directory" );
+            System.exit( 1 );
+        }
 
-               cd.copy( top, ".", depth );
-       }
+        cd.copy( top, ".", depth );
+    }
 }
 
diff --git a/examples/WaitNamedPipe.java b/examples/WaitNamedPipe.java
new file mode 100644 (file)
index 0000000..5380495
--- /dev/null
@@ -0,0 +1,34 @@
+import jcifs.smb.SmbNamedPipe;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+
+public class WaitNamedPipe {
+
+    public static void main( String[] argv ) throws Exception {
+
+        if( argv.length < 2 ) {
+            throw new IllegalArgumentException( "args: <smburl> <filedatatosend> <filetowriterecvdata>" );
+        }
+
+        byte[] b = new byte[65535];
+        FileInputStream fin = new FileInputStream( argv[1] );
+        FileOutputStream fos = new FileOutputStream( argv[2] );
+
+        SmbNamedPipe pipe = new SmbNamedPipe( argv[0], SmbNamedPipe.PIPE_TYPE_RDWR );
+        OutputStream out = pipe.getNamedPipeOutputStream();
+        InputStream in = pipe.getNamedPipeInputStream();
+
+        int n = fin.read( b );
+        System.out.println( "writing " + n + " bytes" );
+        out.write( b, 0, n );
+        n = in.read(b);
+        System.out.println( "read " + n + " bytes" );
+        fos.write(b, 0, n );
+
+        fin.close();
+        fos.close();
+        out.close();
+    }
+}
index 79fd0c6..2e10ae8 100644 (file)
@@ -1,8 +1,21 @@
-domain=rsch
-username=miallen
-password=Fa!e@s
-;wins=169.249.100.243
-wins=146.125.56.78
-;log=ALL
-;resolveOrder=WINS
-;soTimeout=3000
+jcifs.smb.client.domain = mydom
+jcifs.smb.client.username = miallen
+jcifs.smb.client.password = p@ssw0rd
+;jcifs.netbios.wins = 196.22.20.21
+jcifs.netbios.wins = 164.25.87.5
+;jcifs.util.loglevel = 10
+;jcifs.resolveOrder = WINS,DNS
+;jcifs.netbios.cachePolicy = 3
+;jcifs.smb.client.maxBuffers = 20
+;jcifs.smb.client.soTimeout = 4000
+;jcifs.smb.client.responseTimeout = 15000
+;jcifs.smb.client.maxMpxCount = 10
+;jcifs.smb.client.attrExpirationPeriod = 0
+;jcifs.smb.client.useUnicode = false
+;jcifs.smb.client.disablePlainTextPasswords = false
+;jcifs.smb.client.snd_buf_size = 8192
+;jcifs.smb.client.signingPreferred = true
+;jcifs.smb.client.useNTSmbs = false
+;jcifs.smb.client.useBatching = false
+;jcifs.smb.client.listSize = 1200
+;jcifs.smb.client.listCount = 15
index 7313013..5087008 100644 (file)
@@ -1,38 +1,37 @@
 ! Lookup any domain contorller in the FOONET<1C> domain
 
-;domain=foonet
+;jcifs.smb.client.domain=foonet
 
 ! Or explicitly specify any SMB server to use as a
 ! "Domain Controller". This could be a real PDC or
 ! preferrably a BDC or just a plain workstation
 
-domainController=192.168.1.15
+jcifs.smb.client.domainController=192.168.1.15
 
 ! WINS server is only necessary if you are using the
 ! jcifs.smb.client.domain property to lookup a domain
 ! controller
 
-;wins=136.135.65.85
+;jcifs.netbios.wins=136.135.65.85
 
 ! On machines with multiple interfaces it is usually
 ! necessary to set the broadcast address. See the jCIFS FAQ.
 
-baddr=192.168.1.255
+jcifs.netbios.baddr=192.168.1.255
 
 ! If we're sure we have a WINS server this is a
 ! little more direct
 
-;resolveOrder=WINS
+;jcifs.resolveOrder=WINS
 
 ! Users will have to re-authenticate after 600000ms
 ! (10 minutes) if no clients trigger activity on the socket
 ! to the domain controller
 
-soTimeout=600000
+jcifs.smb.client.soTimeout=600000
 
 ! Uncomment this if it's not working to see what's going on.
 ! Logging output is directed to System.err. On Tomcat this
 ! goes to logs/catalina.out. Not sure about Resin.
 
-;log=ALL
-
+;jcifs.util.loglevel=10
index 4266c32..2c23bf6 100644 (file)
-/* examples for the jcifs smb client library in Java\r
- * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>\r
- *\r
- * This program is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- * \r
- * This program is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
- * GNU General Public License for more details.\r
- * \r
- * You should have received a copy of the GNU General Public License\r
- * along with this program; if not, write to the Free Software\r
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\r
- */\r
-\r
-/* callnp.c - Call a Named Pipe\r
- */\r
-\r
-#include <stdio.h>\r
-#include <Windows.h>\r
-#include <stdlib.h>\r
-\r
-int\r
-hexstrtoi(const char *str)\r
-{\r
-       int i;\r
-       for (i = 0; str[i] != '\0'; i++) {\r
-               if (str[i] != 'x' && (str[i] < 48 || str[i] > 57)) {\r
-                       errno = 1;\r
-                       return 0;\r
-               }\r
-       }\r
-       return (int)strtol(str, NULL, 16);\r
-}\r
-\r
-int\r
-main(int argc, char *argv[])\r
-{\r
-       int i;\r
-       int bufferSize, timeout, bytesRead;\r
-       char *target, *send_buf, *recv_buf;\r
-       HANDLE inFile, outFile;\r
-\r
-       inFile = NULL;\r
-       outFile = NULL;\r
-       bufferSize = 65535;\r
-       bytesRead = 0;\r
-\r
-       if (argc == 1 || argv[1][1] == '\?') {\r
-               printf("defaults\r\n");\r
-               printf("  inFile     = <none>\r\n");\r
-               printf("  outFile    = <none>\r\n");\r
-               printf("  bufferSize = 65535\r\n");\r
-\r
-               printf("\r\ncallnp \\\\server\\pipe\\name /I inFile /O outFile /B bufferSize\r\n");\r
-\r
-               return 0;\r
-       }\r
-\r
-       if(argv[1][0] != '\\' && argv[1][1] != '\\') {\r
-               printf("Error: must specify target\r\n");\r
-       }\r
-       target = argv[1];\r
-       for(i = 2; i < argc; i++) {\r
-               if(argv[i][0] != '/') {\r
-                       printf("Error: invalid switch\r\n");\r
-               }\r
-               errno = 0;\r
-               switch(argv[i++][1]) {\r
-                       case 'I':\r
-                               inFile = CreateFile(argv[i], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); \r
-                               if(outFile == INVALID_HANDLE_VALUE) {\r
-                                       printf("Error: cannot open inFile: %s\r\n", argv[i]);\r
-                                       return 0;\r
-                               }\r
-                               break;\r
-                       case 'O':\r
-                               outFile = CreateFile(argv[i], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); \r
-                               if(outFile == INVALID_HANDLE_VALUE) {\r
-                                       printf("Error: cannot open outFile: %s\r\n", argv[i]);\r
-                                       return 0;\r
-                               }\r
-                               break;\r
-                       case 'B':\r
-                               bufferSize = atoi(argv[i]);\r
-                               break;\r
-                       default:\r
-                               printf("Error: no such option\r\n");\r
-                               return 0;\r
-               }\r
-               if(errno) {\r
-                       printf("Error: values must be in hex.\r\n");\r
-                       return 0;\r
-               }\r
-       }\r
-       send_buf = malloc(bufferSize);\r
-       recv_buf = malloc(bufferSize);\r
-       if(send_buf == NULL || recv_buf == NULL) {\r
-               printf("Error: failed to allocate buffers\r\n");\r
-               return 0;\r
-       }\r
-       if(inFile != NULL && ReadFile(inFile, send_buf, bufferSize, &bytesRead, NULL) == 0) {\r
-               printf("Error: failed to read from inFile\r\n");\r
-               return 0;\r
-       }\r
-       if (WaitNamedPipe(target, NMPWAIT_WAIT_FOREVER) == 0) {\r
-               printf("Error: WaitNamedPipe operation failed: %u\r\n", GetLastError());\r
-               return 0;\r
-       }\r
-       if (CallNamedPipe(target, send_buf, bytesRead, recv_buf, bufferSize, &bytesRead, NMPWAIT_WAIT_FOREVER) == 0) {\r
-               printf("Error: CallNamedPipe operation failed: %u\r\n", GetLastError());\r
-               return 0;\r
-       }\r
-       if(outFile != NULL && WriteFile(outFile, recv_buf, bytesRead, &bytesRead, NULL) == 0) {\r
-               printf("Error: failed to write to outFile\r\n");\r
-       }\r
-       printf("Success: operation performed successfully\r\n");\r
-       return 1;\r
-}\r
-\r
+/* examples for the jcifs smb client library in Java
+ * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ * 
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+/* callnp.c - Call a Named Pipe
+ */
+
+#include <stdio.h>
+#include <Windows.h>
+#include <stdlib.h>
+
+int
+hexstrtoi(const char *str)
+{
+    int i;
+    for (i = 0; str[i] != '\0'; i++) {
+        if (str[i] != 'x' && (str[i] < 48 || str[i] > 57)) {
+            errno = 1;
+            return 0;
+        }
+    }
+    return (int)strtol(str, NULL, 16);
+}
+
+int
+main(int argc, char *argv[])
+{
+    int i;
+    int bufferSize, timeout, bytesRead;
+    char *target, *send_buf, *recv_buf;
+    HANDLE inFile, outFile;
+
+    inFile = NULL;
+    outFile = NULL;
+    bufferSize = 65535;
+    bytesRead = 0;
+
+    if (argc == 1 || argv[1][1] == '\?') {
+        printf("defaults\r\n");
+        printf("  inFile     = <none>\r\n");
+        printf("  outFile    = <none>\r\n");
+        printf("  bufferSize = 65535\r\n");
+
+        printf("\r\ncallnp \\\\server\\pipe\\name /I inFile /O outFile /B bufferSize\r\n");
+
+        return 0;
+    }
+
+    if(argv[1][0] != '\\' && argv[1][1] != '\\') {
+        printf("Error: must specify target\r\n");
+    }
+    target = argv[1];
+    for(i = 2; i < argc; i++) {
+        if(argv[i][0] != '/') {
+            printf("Error: invalid switch\r\n");
+        }
+        errno = 0;
+        switch(argv[i++][1]) {
+            case 'I':
+                inFile = CreateFile(argv[i], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 
+                if(outFile == INVALID_HANDLE_VALUE) {
+                    printf("Error: cannot open inFile: %s\r\n", argv[i]);
+                    return 0;
+                }
+                break;
+            case 'O':
+                outFile = CreateFile(argv[i], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 
+                if(outFile == INVALID_HANDLE_VALUE) {
+                    printf("Error: cannot open outFile: %s\r\n", argv[i]);
+                    return 0;
+                }
+                break;
+            case 'B':
+                bufferSize = atoi(argv[i]);
+                break;
+            default:
+                printf("Error: no such option\r\n");
+                return 0;
+        }
+        if(errno) {
+            printf("Error: values must be in hex.\r\n");
+            return 0;
+        }
+    }
+    send_buf = malloc(bufferSize);
+    recv_buf = malloc(bufferSize);
+    if(send_buf == NULL || recv_buf == NULL) {
+        printf("Error: failed to allocate buffers\r\n");
+        return 0;
+    }
+    if(inFile != NULL && ReadFile(inFile, send_buf, bufferSize, &bytesRead, NULL) == 0) {
+        printf("Error: failed to read from inFile\r\n");
+        return 0;
+    }
+    if (WaitNamedPipe(target, NMPWAIT_WAIT_FOREVER) == 0) {
+        printf("Error: WaitNamedPipe operation failed: %u\r\n", GetLastError());
+        return 0;
+    }
+    if (CallNamedPipe(target, send_buf, bytesRead, recv_buf, bufferSize, &bytesRead, NMPWAIT_WAIT_FOREVER) == 0) {
+        printf("Error: CallNamedPipe operation failed: %u\r\n", GetLastError());
+        return 0;
+    }
+    if(outFile != NULL && WriteFile(outFile, recv_buf, bytesRead, &bytesRead, NULL) == 0) {
+        printf("Error: failed to write to outFile\r\n");
+    }
+    printf("Success: operation performed successfully\r\n");
+    return 1;
+}
+
index 838d7ff..e5c4000 100644 (file)
-/* examples for the jcifs smb client library in Java\r
- * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>\r
- *\r
- * This program is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- * \r
- * This program is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
- * GNU General Public License for more details.\r
- * \r
- * You should have received a copy of the GNU General Public License\r
- * along with this program; if not, write to the Free Software\r
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\r
- */\r
-\r
-/* createf.c - Create a file with the CreateFile call.\r
- */\r
-\r
-\r
-#include <stdio.h>\r
-#include <Windows.h>\r
-#include <stdlib.h>\r
-\r
-#define hexstrtoui(s) ((int)strtoul((s), NULL, 16))\r
-\r
-int\r
-main(int argc, char *argv[])\r
-{\r
-       int i;\r
-       int desiredAccess, shareMode, disposition, flags, bufferSize, bytesRead;\r
-       char *target, *buf;\r
-       HANDLE h, inFile, outFile;\r
-\r
-       inFile = NULL;\r
-       outFile = NULL;\r
-       desiredAccess = GENERIC_READ;\r
-       shareMode = 0;\r
-       disposition = CREATE_ALWAYS;\r
-       flags = FILE_ATTRIBUTE_NORMAL;\r
-       bufferSize = 65535;\r
-\r
-       if (argc == 1 || argv[1][1] == '\?') {\r
-\r
-               /* dwDesiredAccess\r
-                */\r
-               printf("dwDesiredAccess\r\n");\r
-               printf("  0x%08x GENERIC_READ\r\n", GENERIC_READ);\r
-               printf("  0x%08x GENERIC_WRITE\r\n", GENERIC_WRITE);\r
-               printf("  0x%08x DELETE\r\n", DELETE);\r
-               printf("  0x%08x READ_CONTROL\r\n", READ_CONTROL);\r
-               printf("  0x%08x WRITE_DAC\r\n", WRITE_DAC);\r
-               printf("  0x%08x WRITE_OWNER\r\n", WRITE_OWNER);\r
-               printf("  0x%08x SYNCHRONIZE\r\n", SYNCHRONIZE);\r
-               printf("  0x%08x STANDARD_RIGHTS_REQUIRED\r\n", STANDARD_RIGHTS_REQUIRED);\r
-               printf("  0x%08x STANDARD_RIGHTS_READ\r\n", STANDARD_RIGHTS_READ);\r
-               printf("  0x%08x STANDARD_RIGHTS_WRITE\r\n", STANDARD_RIGHTS_WRITE);\r
-               printf("  0x%08x STANDARD_RIGHTS_EXECUTE\r\n", STANDARD_RIGHTS_EXECUTE);\r
-               printf("  0x%08x STANDARD_RIGHTS_ALL\r\n", STANDARD_RIGHTS_ALL);\r
-               printf("  0x%08x SPECIFIC_RIGHTS_ALL\r\n", SPECIFIC_RIGHTS_ALL);\r
-               printf("  0x%08x ACCESS_SYSTEM_SECURITY\r\n", ACCESS_SYSTEM_SECURITY);\r
-               printf("  0x%08x MAXIMUM_ALLOWED\r\n", MAXIMUM_ALLOWED);\r
-               printf("  0x%08x GENERIC_EXECUTE\r\n", GENERIC_EXECUTE);\r
-               printf("  0x%08x GENERIC_ALL\r\n", GENERIC_ALL);\r
-               /* dwShareMode\r
-                */\r
-               printf("dwShareMode\n");\r
-               printf("  0x%08x FILE_SHARE_DELETE\r\n", FILE_SHARE_DELETE);\r
-               printf("  0x%08x FILE_SHARE_READ\r\n", FILE_SHARE_READ);\r
-               printf("  0x%08x FILE_SHARE_WRITE\r\n", FILE_SHARE_WRITE);\r
-               printf("  0x%08x the file cannot be shared\r\n", 0);\r
-               /* dwCreateDisposition\r
-                */\r
-               printf("dwCreateDisposition\r\n");\r
-               printf("  0x%08x CREATE_NEW\r\n", CREATE_NEW);\r
-               printf("  0x%08x CREATE_ALWAYS\r\n", CREATE_ALWAYS);\r
-               printf("  0x%08x OPEN_EXISTING\r\n", OPEN_EXISTING);\r
-               printf("  0x%08x OPEN_ALWAYS\r\n", OPEN_ALWAYS);\r
-               printf("  0x%08x TRUNCATE_EXISTING\r\n", TRUNCATE_EXISTING);\r
-               /* dwFlagsAndAttributes\r
-                */\r
-               printf("dwFlagsAndAttributes\r\n");\r
-               printf("  0x%08x FILE_ATTRIBUTE_ARCHIVE\r\n", FILE_ATTRIBUTE_ARCHIVE);\r
-               printf("  0x%08x FILE_ATTRIBUTE_ENCRYPTED\r\n", FILE_ATTRIBUTE_ENCRYPTED);\r
-               printf("  0x%08x FILE_ATTRIBUTE_HIDDEN\r\n", FILE_ATTRIBUTE_HIDDEN);\r
-               printf("  0x%08x FILE_ATTRIBUTE_NORMAL\r\n", FILE_ATTRIBUTE_NORMAL);\r
-               printf("  0x%08x FILE_ATTRIBUTE_NOT_CONTENT_INDEXED\r\n", FILE_ATTRIBUTE_NOT_CONTENT_INDEXED);\r
-               printf("  0x%08x FILE_ATTRIBUTE_OFFLINE\r\n", FILE_ATTRIBUTE_OFFLINE);\r
-               printf("  0x%08x FILE_ATTRIBUTE_READONLY\r\n", FILE_ATTRIBUTE_READONLY);\r
-               printf("  0x%08x FILE_ATTRIBUTE_SYSTEM\r\n", FILE_ATTRIBUTE_SYSTEM);\r
-               printf("  0x%08x FILE_ATTRIBUTE_TEMPORARY\r\n", FILE_ATTRIBUTE_TEMPORARY);\r
-               \r
-               printf("  0x%08x FILE_FLAG_WRITE_THROUGH\r\n", FILE_FLAG_WRITE_THROUGH);\r
-               printf("  0x%08x FILE_FLAG_OVERLAPPED\r\n", FILE_FLAG_OVERLAPPED);\r
-               printf("  0x%08x FILE_FLAG_NO_BUFFERING\r\n", FILE_FLAG_NO_BUFFERING);\r
-               printf("  0x%08x FILE_FLAG_RANDOM_ACCESS\r\n", FILE_FLAG_RANDOM_ACCESS);\r
-               printf("  0x%08x FILE_FLAG_SEQUENTIAL_SCAN\r\n", FILE_FLAG_SEQUENTIAL_SCAN);\r
-               printf("  0x%08x FILE_FLAG_DELETE_ON_CLOSE\r\n", FILE_FLAG_DELETE_ON_CLOSE);\r
-               printf("  0x%08x FILE_FLAG_BACKUP_SEMANTICS\r\n", FILE_FLAG_BACKUP_SEMANTICS);\r
-               printf("  0x%08x FILE_FLAG_POSIX_SEMANTICS\r\n", FILE_FLAG_POSIX_SEMANTICS);\r
-               \r
-               printf("  0x%08x FILE_FLAG_OPEN_REPARSE_POINT\r\n", FILE_FLAG_OPEN_REPARSE_POINT);\r
-               printf("  0x%08x FILE_FLAG_OPEN_NO_RECALL\r\n", FILE_FLAG_OPEN_NO_RECALL);\r
-               printf("  0x%08x SECURITY_ANONYMOUS\r\n", SECURITY_ANONYMOUS);\r
-               printf("  0x%08x SECURITY_IDENTIFICATION\r\n", SECURITY_IDENTIFICATION);\r
-               printf("  0x%08x SECURITY_IMPERSONATION\r\n", SECURITY_IMPERSONATION);\r
-               printf("  0x%08x SECURITY_DELEGATION\r\n", SECURITY_DELEGATION);\r
-               printf("  0x%08x SECURITY_CONTEXT_TRACKING\r\n", SECURITY_CONTEXT_TRACKING);\r
-               printf("  0x%08x SECURITY_EFFECTIVE_ONLY\r\n", SECURITY_EFFECTIVE_ONLY);\r
-\r
-               printf("defaults\r\n");\r
-               printf("  dwDesiredAccess      = GENERIC_READ\r\n");\r
-               printf("  dwShareMode          = FILE_SHARE_READ\r\n");\r
-               printf("  dwCreateDisposition  = CREATE_ALWAYS\r\n");\r
-               printf("  dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL\r\n");\r
-               printf("  inFile               = none\r\n");\r
-               printf("  outFile              = none\r\n");\r
-               printf("  bufferSize           = 65535\r\n");\r
-\r
-               printf("\r\ncreatef \\\\server\\share\\path /A access /S share /D disposition /F flags /I inFile /O outFile /B bufferSize\r\n");\r
-\r
-               return 0;\r
-       }\r
-\r
-       if(argv[1][0] != '\\' && argv[1][1] != '\\') {\r
-               printf("Error: must specify target\r\n");\r
-       }\r
-       target = argv[1];\r
-       for(i = 2; i < argc; i++) {\r
-               if(argv[i][0] != '/') {\r
-                       printf("Error: invalid switch\r\n");\r
-               }\r
-               errno = 0;\r
-               switch(argv[i++][1]) {\r
-                       case 'A':\r
-                               desiredAccess = hexstrtoui(&argv[i][2]);\r
-                               break;\r
-                       case 'S':\r
-                               shareMode = hexstrtoui(argv[i]);\r
-                               break;\r
-                       case 'D':\r
-                               disposition = hexstrtoui(argv[i]);\r
-                               break;\r
-                       case 'F':\r
-                               flags = hexstrtoui(argv[i]);\r
-                               break;\r
-                       case 'I':\r
-                               inFile = CreateFile(argv[i], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); \r
-                               if(inFile == INVALID_HANDLE_VALUE) {\r
-                                       printf("Error: cannot open inFile: %s\r\n", argv[i]);\r
-                                       CloseHandle(outFile);\r
-                                       return 0;\r
-                               }\r
-                               break;\r
-                       case 'O':\r
-                               outFile = CreateFile(argv[i], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); \r
-                               if(outFile == INVALID_HANDLE_VALUE) {\r
-                                       printf("Error: cannot open outFile: %s\r\n", argv[i]);\r
-                                       CloseHandle(inFile);\r
-                                       return 0;\r
-                               }\r
-                               break;\r
-                       default:\r
-                               printf("Error: no such option\r\n");\r
-                               return 0;\r
-               }\r
-               if(errno) {\r
-                       printf("Error: %s\r\n", strerror(errno));\r
-                       return 0;\r
-               }\r
-       }\r
-\r
-       buf = malloc(bufferSize);\r
-       if(buf == NULL) {\r
-               printf("Error: failed to allocate buffer\r\n");\r
-               CloseHandle(inFile);\r
-               CloseHandle(outFile);\r
-               return 0;\r
-       }\r
-       h = CreateFile(target, desiredAccess, shareMode, NULL, disposition, flags, NULL);\r
-       if (h == INVALID_HANDLE_VALUE) {\r
-               printf("Error: CreateFile operation failed: %u\r\n", GetLastError());\r
-               CloseHandle(inFile);\r
-               CloseHandle(outFile);\r
-               return 0;\r
-       }\r
-       if(inFile != NULL || outFile != NULL) {\r
-               /* need to do reading or writing of some sort on the pipe */\r
-\r
-               if(inFile == NULL) {\r
-                       inFile = h;\r
-               }\r
-               if(outFile == NULL) {\r
-                       outFile = h;\r
-               }\r
-               while(ReadFile(inFile, buf, bufferSize, &bytesRead, NULL) > 0) {\r
-                       WriteFile(outFile, buf, bytesRead, &bytesRead, NULL);\r
-               }\r
-       }\r
-       printf("Success: operation performed successfully\r\n");\r
-       CloseHandle(inFile);\r
-       CloseHandle(outFile);\r
-       CloseHandle(h);\r
-       return 1;\r
-}\r
-\r
+/* examples for the jcifs smb client library in Java
+ * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ * 
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+/* createf.c - Create a file with the CreateFile call.
+ */
+
+
+#include <stdio.h>
+#include <Windows.h>
+#include <stdlib.h>
+
+#define hexstrtoui(s) ((int)strtoul((s), NULL, 16))
+
+int
+main(int argc, char *argv[])
+{
+    int i;
+    int desiredAccess, shareMode, disposition, flags, bufferSize, bytesRead;
+    char *target, *buf;
+    HANDLE h, inFile, outFile;
+
+    inFile = NULL;
+    outFile = NULL;
+    desiredAccess = GENERIC_READ;
+    shareMode = 0;
+    disposition = CREATE_ALWAYS;
+    flags = FILE_ATTRIBUTE_NORMAL;
+    bufferSize = 65535;
+
+    if (argc == 1 || argv[1][1] == '\?') {
+
+        /* dwDesiredAccess
+         */
+        printf("dwDesiredAccess\r\n");
+        printf("  0x%08x GENERIC_READ\r\n", GENERIC_READ);
+        printf("  0x%08x GENERIC_WRITE\r\n", GENERIC_WRITE);
+        printf("  0x%08x DELETE\r\n", DELETE);
+        printf("  0x%08x READ_CONTROL\r\n", READ_CONTROL);
+        printf("  0x%08x WRITE_DAC\r\n", WRITE_DAC);
+        printf("  0x%08x WRITE_OWNER\r\n", WRITE_OWNER);
+        printf("  0x%08x SYNCHRONIZE\r\n", SYNCHRONIZE);
+        printf("  0x%08x STANDARD_RIGHTS_REQUIRED\r\n", STANDARD_RIGHTS_REQUIRED);
+        printf("  0x%08x STANDARD_RIGHTS_READ\r\n", STANDARD_RIGHTS_READ);
+        printf("  0x%08x STANDARD_RIGHTS_WRITE\r\n", STANDARD_RIGHTS_WRITE);
+        printf("  0x%08x STANDARD_RIGHTS_EXECUTE\r\n", STANDARD_RIGHTS_EXECUTE);
+        printf("  0x%08x STANDARD_RIGHTS_ALL\r\n", STANDARD_RIGHTS_ALL);
+        printf("  0x%08x SPECIFIC_RIGHTS_ALL\r\n", SPECIFIC_RIGHTS_ALL);
+        printf("  0x%08x ACCESS_SYSTEM_SECURITY\r\n", ACCESS_SYSTEM_SECURITY);
+        printf("  0x%08x MAXIMUM_ALLOWED\r\n", MAXIMUM_ALLOWED);
+        printf("  0x%08x GENERIC_EXECUTE\r\n", GENERIC_EXECUTE);
+        printf("  0x%08x GENERIC_ALL\r\n", GENERIC_ALL);
+        /* dwShareMode
+         */
+        printf("dwShareMode\n");
+        printf("  0x%08x FILE_SHARE_DELETE\r\n", FILE_SHARE_DELETE);
+        printf("  0x%08x FILE_SHARE_READ\r\n", FILE_SHARE_READ);
+        printf("  0x%08x FILE_SHARE_WRITE\r\n", FILE_SHARE_WRITE);
+        printf("  0x%08x the file cannot be shared\r\n", 0);
+        /* dwCreateDisposition
+         */
+        printf("dwCreateDisposition\r\n");
+        printf("  0x%08x CREATE_NEW\r\n", CREATE_NEW);
+        printf("  0x%08x CREATE_ALWAYS\r\n", CREATE_ALWAYS);
+        printf("  0x%08x OPEN_EXISTING\r\n", OPEN_EXISTING);
+        printf("  0x%08x OPEN_ALWAYS\r\n", OPEN_ALWAYS);
+        printf("  0x%08x TRUNCATE_EXISTING\r\n", TRUNCATE_EXISTING);
+        /* dwFlagsAndAttributes
+         */
+        printf("dwFlagsAndAttributes\r\n");
+        printf("  0x%08x FILE_ATTRIBUTE_ARCHIVE\r\n", FILE_ATTRIBUTE_ARCHIVE);
+        printf("  0x%08x FILE_ATTRIBUTE_ENCRYPTED\r\n", FILE_ATTRIBUTE_ENCRYPTED);
+        printf("  0x%08x FILE_ATTRIBUTE_HIDDEN\r\n", FILE_ATTRIBUTE_HIDDEN);
+        printf("  0x%08x FILE_ATTRIBUTE_NORMAL\r\n", FILE_ATTRIBUTE_NORMAL);
+        printf("  0x%08x FILE_ATTRIBUTE_NOT_CONTENT_INDEXED\r\n", FILE_ATTRIBUTE_NOT_CONTENT_INDEXED);
+        printf("  0x%08x FILE_ATTRIBUTE_OFFLINE\r\n", FILE_ATTRIBUTE_OFFLINE);
+        printf("  0x%08x FILE_ATTRIBUTE_READONLY\r\n", FILE_ATTRIBUTE_READONLY);
+        printf("  0x%08x FILE_ATTRIBUTE_SYSTEM\r\n", FILE_ATTRIBUTE_SYSTEM);
+        printf("  0x%08x FILE_ATTRIBUTE_TEMPORARY\r\n", FILE_ATTRIBUTE_TEMPORARY);
+        
+        printf("  0x%08x FILE_FLAG_WRITE_THROUGH\r\n", FILE_FLAG_WRITE_THROUGH);
+        printf("  0x%08x FILE_FLAG_OVERLAPPED\r\n", FILE_FLAG_OVERLAPPED);
+        printf("  0x%08x FILE_FLAG_NO_BUFFERING\r\n", FILE_FLAG_NO_BUFFERING);
+        printf("  0x%08x FILE_FLAG_RANDOM_ACCESS\r\n", FILE_FLAG_RANDOM_ACCESS);
+        printf("  0x%08x FILE_FLAG_SEQUENTIAL_SCAN\r\n", FILE_FLAG_SEQUENTIAL_SCAN);
+        printf("  0x%08x FILE_FLAG_DELETE_ON_CLOSE\r\n", FILE_FLAG_DELETE_ON_CLOSE);
+        printf("  0x%08x FILE_FLAG_BACKUP_SEMANTICS\r\n", FILE_FLAG_BACKUP_SEMANTICS);
+        printf("  0x%08x FILE_FLAG_POSIX_SEMANTICS\r\n", FILE_FLAG_POSIX_SEMANTICS);
+        
+        printf("  0x%08x FILE_FLAG_OPEN_REPARSE_POINT\r\n", FILE_FLAG_OPEN_REPARSE_POINT);
+        printf("  0x%08x FILE_FLAG_OPEN_NO_RECALL\r\n", FILE_FLAG_OPEN_NO_RECALL);
+        printf("  0x%08x SECURITY_ANONYMOUS\r\n", SECURITY_ANONYMOUS);
+        printf("  0x%08x SECURITY_IDENTIFICATION\r\n", SECURITY_IDENTIFICATION);
+        printf("  0x%08x SECURITY_IMPERSONATION\r\n", SECURITY_IMPERSONATION);
+        printf("  0x%08x SECURITY_DELEGATION\r\n", SECURITY_DELEGATION);
+        printf("  0x%08x SECURITY_CONTEXT_TRACKING\r\n", SECURITY_CONTEXT_TRACKING);
+        printf("  0x%08x SECURITY_EFFECTIVE_ONLY\r\n", SECURITY_EFFECTIVE_ONLY);
+
+        printf("defaults\r\n");
+        printf("  dwDesiredAccess      = GENERIC_READ\r\n");
+        printf("  dwShareMode          = FILE_SHARE_READ\r\n");
+        printf("  dwCreateDisposition  = CREATE_ALWAYS\r\n");
+        printf("  dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL\r\n");
+        printf("  inFile               = none\r\n");
+        printf("  outFile              = none\r\n");
+        printf("  bufferSize           = 65535\r\n");
+
+        printf("\r\ncreatef \\\\server\\share\\path /A access /S share /D disposition /F flags /I inFile /O outFile /B bufferSize\r\n");
+
+        return 0;
+    }
+
+    if(argv[1][0] != '\\' && argv[1][1] != '\\') {
+        printf("Error: must specify target\r\n");
+    }
+    target = argv[1];
+    for(i = 2; i < argc; i++) {
+        if(argv[i][0] != '/') {
+            printf("Error: invalid switch\r\n");
+        }
+        errno = 0;
+        switch(argv[i++][1]) {
+            case 'A':
+                desiredAccess = hexstrtoui(&argv[i][2]);
+                break;
+            case 'S':
+                shareMode = hexstrtoui(argv[i]);
+                break;
+            case 'D':
+                disposition = hexstrtoui(argv[i]);
+                break;
+            case 'F':
+                flags = hexstrtoui(argv[i]);
+                break;
+            case 'I':
+                inFile = CreateFile(argv[i], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 
+                if(inFile == INVALID_HANDLE_VALUE) {
+                    printf("Error: cannot open inFile: %s\r\n", argv[i]);
+                    CloseHandle(outFile);
+                    return 0;
+                }
+                break;
+            case 'O':
+                outFile = CreateFile(argv[i], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 
+                if(outFile == INVALID_HANDLE_VALUE) {
+                    printf("Error: cannot open outFile: %s\r\n", argv[i]);
+                    CloseHandle(inFile);
+                    return 0;
+                }
+                break;
+            default:
+                printf("Error: no such option\r\n");
+                return 0;
+        }
+        if(errno) {
+            printf("Error: %s\r\n", strerror(errno));
+            return 0;
+        }
+    }
+
+    buf = malloc(bufferSize);
+    if(buf == NULL) {
+        printf("Error: failed to allocate buffer\r\n");
+        CloseHandle(inFile);
+        CloseHandle(outFile);
+        return 0;
+    }
+    h = CreateFile(target, desiredAccess, shareMode, NULL, disposition, flags, NULL);
+    if (h == INVALID_HANDLE_VALUE) {
+        printf("Error: CreateFile operation failed: %u\r\n", GetLastError());
+        CloseHandle(inFile);
+        CloseHandle(outFile);
+        return 0;
+    }
+    if(inFile != NULL || outFile != NULL) {
+        /* need to do reading or writing of some sort on the pipe */
+
+        if(inFile == NULL) {
+            inFile = h;
+        }
+        if(outFile == NULL) {
+            outFile = h;
+        }
+        while(ReadFile(inFile, buf, bufferSize, &bytesRead, NULL) > 0) {
+            WriteFile(outFile, buf, bytesRead, &bytesRead, NULL);
+        }
+    }
+    printf("Success: operation performed successfully\r\n");
+    CloseHandle(inFile);
+    CloseHandle(outFile);
+    CloseHandle(h);
+    return 1;
+}
+
index 04e115d..56858db 100644 (file)
-/* examples for the jcifs smb client library in Java\r
- * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>\r
- *\r
- * This program is free software; you can redistribute it and/or modify\r
- * it under the terms of the GNU General Public License as published by\r
- * the Free Software Foundation; either version 2 of the License, or\r
- * (at your option) any later version.\r
- * \r
- * This program is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
- * GNU General Public License for more details.\r
- * \r
- * You should have received a copy of the GNU General Public License\r
- * along with this program; if not, write to the Free Software\r
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\r
- */\r
-\r
-/* createnp.c - Create a named pipe with CreateNamedPipe.\r
- */\r
-\r
-#include <stdio.h>\r
-#include <Windows.h>\r
-#include <stdlib.h>\r
-\r
-#define hexstrtoui(s) ((int)strtoul((s), NULL, 16))\r
-\r
-int\r
-main(int argc, char *argv[])\r
-{\r
-       int i;\r
-       int openMode, pipeMode, bufferSize, defaultTimeout, bytesRead;\r
-       char *target, *buf;\r
-       HANDLE h, inFile, outFile;\r
-\r
-       inFile = NULL;\r
-       outFile = NULL;\r
-       openMode = PIPE_ACCESS_DUPLEX;\r
-       pipeMode = PIPE_TYPE_BYTE | PIPE_WAIT;\r
-       bufferSize = 65535;\r
-\r
-       if (argc == 1 || argv[1][1] == '\?') {\r
-\r
-               /* dwOpenMode\r
-                */\r
-               printf("dwOpenMode\r\n");\r
-               printf("  0x%08x PIPE_ACCESS_DUPLEX\r\n", PIPE_ACCESS_DUPLEX);\r
-               printf("  0x%08x PIPE_ACCESS_INBOUND\r\n", PIPE_ACCESS_INBOUND);\r
-               printf("  0x%08x PIPE_ACCESS_OUTBOUND\r\n", PIPE_ACCESS_OUTBOUND);\r
-               printf("  0x%08x FILE_FLAG_WRITE_THROUGH\r\n", FILE_FLAG_WRITE_THROUGH);\r
-               printf("  0x%08x FILE_FLAG_OVERLAPPED\r\n", FILE_FLAG_OVERLAPPED);\r
-               printf("  0x%08x WRITE_DAC\r\n", WRITE_DAC);\r
-               printf("  0x%08x WRITE_OWNER\r\n", WRITE_OWNER);\r
-               printf("  0x%08x ACCESS_SYSTEM_SECURITY\r\n", ACCESS_SYSTEM_SECURITY);\r
-               /* dwPipeMode\r
-                */\r
-               printf("dwPipeMode\r\n");\r
-               printf("  0x%08x PIPE_TYPE_BYTE\r\n", PIPE_TYPE_BYTE);\r
-               printf("  0x%08x PIPE_TYPE_MESSAGE\r\n", PIPE_TYPE_MESSAGE);\r
-               printf("  0x%08x PIPE_READMODE_BYTE\r\n", PIPE_READMODE_BYTE);\r
-               printf("  0x%08x PIPE_READMODE_MESSAGE\r\n", PIPE_READMODE_MESSAGE);\r
-               printf("  0x%08x PIPE_WAIT\r\n", PIPE_WAIT);\r
-               printf("  0x%08x PIPE_NOWAIT\r\n", PIPE_NOWAIT);\r
-\r
-               printf("defaults\r\n");\r
-               printf("  inFile     = <read from pipe input>\r\n");\r
-               printf("  outFile    = <write to pipe output>\r\n");\r
-               printf("  dwOpenMode = PIPE_ACCESS_DUPLEX\r\n");\r
-               printf("  dwPipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT\r\n");\r
-               printf("  bufferSize = 65535\r\n");\r
-\r
-               printf("\r\ncreatenp \\\\.\\pipe\\name /I inFile /O outFile /M mode /P pmode /B bufferSize\r\n");\r
-\r
-               return 0;\r
-       }\r
-\r
-       if(argv[1][0] != '\\' && argv[1][1] != '\\') {\r
-               printf("Error: must specify target\r\n");\r
-       }\r
-       target = argv[1];\r
-       for(i = 2; i < argc; i++) {\r
-               if(argv[i][0] != '/') {\r
-                       printf("Error: invalid switch\r\n");\r
-               }\r
-               errno = 0;\r
-               switch(argv[i++][1]) {\r
-                       case 'I':\r
-                               inFile = CreateFile(argv[i], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); \r
-                               if(inFile == INVALID_HANDLE_VALUE) {\r
-                                       printf("Error: cannot open inFile: %s\r\n", argv[i]);\r
-                                       CloseHandle(outFile);\r
-                                       return 0;\r
-                               }\r
-                               break;\r
-                       case 'O':\r
-                               outFile = CreateFile(argv[i], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); \r
-                               if(outFile == INVALID_HANDLE_VALUE) {\r
-                                       printf("Error: cannot open outFile: %s\r\n", argv[i]);\r
-                                       CloseHandle(inFile);\r
-                                       return 0;\r
-                               }\r
-                               break;\r
-                       case 'M':\r
-                               openMode = hexstrtoui(argv[i]);\r
-                               break;\r
-                       case 'P':\r
-                               pipeMode = hexstrtoui(argv[i]);\r
-                               break;\r
-                       case 'B':\r
-                               bufferSize = atoi(argv[i]);\r
-                               break;\r
-                       default:\r
-                               printf("Error: no such option\r\n");\r
-                               CloseHandle(inFile);\r
-                               CloseHandle(outFile);\r
-                               return 0;\r
-               }\r
-               if(errno) {\r
-                       printf("Error: values must be in hex.\r\n");\r
-                       CloseHandle(inFile);\r
-                       CloseHandle(outFile);\r
-                       return 0;\r
-               }\r
-       }\r
-       h = CreateNamedPipe(target, openMode, pipeMode, 1, bufferSize, bufferSize, NMPWAIT_WAIT_FOREVER, NULL);\r
-       if (h == INVALID_HANDLE_VALUE) {\r
-               printf("Error: CreateNamedPipe operation failed: %u\r\n", GetLastError());\r
-               CloseHandle(inFile);\r
-               CloseHandle(outFile);\r
-               return 0;\r
-       }\r
-       if(ConnectNamedPipe(h, NULL) == 0 && GetLastError() != ERROR_PIPE_CONNECTED) {\r
-               printf("Error: ConnectNamedPipe operation failed: %u\r\n", GetLastError());\r
-               CloseHandle(inFile);\r
-               CloseHandle(outFile);\r
-               CloseHandle(h);\r
-               return 0;\r
-       }\r
-       buf = malloc(bufferSize);\r
-       if(buf == NULL) {\r
-               printf("Error: failed to allocate buffer\r\n");\r
-               CloseHandle(inFile);\r
-               CloseHandle(outFile);\r
-               DisconnectNamedPipe(h);\r
-               CloseHandle(h);\r
-               return 0;\r
-       }\r
-       if(inFile == NULL) {\r
-               inFile = h;\r
-       }\r
-       if(outFile == NULL) {\r
-               outFile = h;\r
-       }\r
-       while(ReadFile(inFile, buf, bufferSize, &bytesRead, NULL) > 0) {\r
-               WriteFile(outFile, buf, bytesRead, &bytesRead, NULL);\r
-       }\r
-       printf("Success: operation performed successfully\r\n");\r
-       CloseHandle(inFile);\r
-       CloseHandle(outFile);\r
-       DisconnectNamedPipe(h);\r
-       CloseHandle(h);\r
-       return 1;\r
-}\r
-\r
+/* examples for the jcifs smb client library in Java
+ * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ * 
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+/* createnp.c - Create a named pipe with CreateNamedPipe.
+ */
+
+#include <stdio.h>
+#include <Windows.h>
+#include <stdlib.h>
+
+#define hexstrtoui(s) ((int)strtoul((s), NULL, 16))
+
+int
+main(int argc, char *argv[])
+{
+    int i;
+    int openMode, pipeMode, bufferSize, defaultTimeout, bytesRead;
+    char *target, *buf;
+    HANDLE h, inFile, outFile;
+
+    inFile = NULL;
+    outFile = NULL;
+    openMode = PIPE_ACCESS_DUPLEX;
+    pipeMode = PIPE_TYPE_BYTE | PIPE_WAIT;
+    bufferSize = 65535;
+
+    if (argc == 1 || argv[1][1] == '\?') {
+
+        /* dwOpenMode
+         */
+        printf("dwOpenMode\r\n");
+        printf("  0x%08x PIPE_ACCESS_DUPLEX\r\n", PIPE_ACCESS_DUPLEX);
+        printf("  0x%08x PIPE_ACCESS_INBOUND\r\n", PIPE_ACCESS_INBOUND);
+        printf("  0x%08x PIPE_ACCESS_OUTBOUND\r\n", PIPE_ACCESS_OUTBOUND);
+        printf("  0x%08x FILE_FLAG_WRITE_THROUGH\r\n", FILE_FLAG_WRITE_THROUGH);
+        printf("  0x%08x FILE_FLAG_OVERLAPPED\r\n", FILE_FLAG_OVERLAPPED);
+        printf("  0x%08x WRITE_DAC\r\n", WRITE_DAC);
+        printf("  0x%08x WRITE_OWNER\r\n", WRITE_OWNER);
+        printf("  0x%08x ACCESS_SYSTEM_SECURITY\r\n", ACCESS_SYSTEM_SECURITY);
+        /* dwPipeMode
+         */
+        printf("dwPipeMode\r\n");
+        printf("  0x%08x PIPE_TYPE_BYTE\r\n", PIPE_TYPE_BYTE);
+        printf("  0x%08x PIPE_TYPE_MESSAGE\r\n", PIPE_TYPE_MESSAGE);
+        printf("  0x%08x PIPE_READMODE_BYTE\r\n", PIPE_READMODE_BYTE);
+        printf("  0x%08x PIPE_READMODE_MESSAGE\r\n", PIPE_READMODE_MESSAGE);
+        printf("  0x%08x PIPE_WAIT\r\n", PIPE_WAIT);
+        printf("  0x%08x PIPE_NOWAIT\r\n", PIPE_NOWAIT);
+
+        printf("defaults\r\n");
+        printf("  inFile     = <read from pipe input>\r\n");
+        printf("  outFile    = <write to pipe output>\r\n");
+        printf("  dwOpenMode = PIPE_ACCESS_DUPLEX\r\n");
+        printf("  dwPipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT\r\n");
+        printf("  bufferSize = 65535\r\n");
+
+        printf("\r\ncreatenp \\\\.\\pipe\\name /I inFile /O outFile /M mode /P pmode /B bufferSize\r\n");
+
+        return 0;
+    }
+
+    if(argv[1][0] != '\\' && argv[1][1] != '\\') {
+        printf("Error: must specify target\r\n");
+    }
+    target = argv[1];
+    for(i = 2; i < argc; i++) {
+        if(argv[i][0] != '/') {
+            printf("Error: invalid switch\r\n");
+        }
+        errno = 0;
+        switch(argv[i++][1]) {
+            case 'I':
+                inFile = CreateFile(argv[i], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 
+                if(inFile == INVALID_HANDLE_VALUE) {
+                    printf("Error: cannot open inFile: %s\r\n", argv[i]);
+                    CloseHandle(outFile);
+                    return 0;
+                }
+                break;
+            case 'O':
+                outFile = CreateFile(argv[i], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 
+                if(outFile == INVALID_HANDLE_VALUE) {
+                    printf("Error: cannot open outFile: %s\r\n", argv[i]);
+                    CloseHandle(inFile);
+                    return 0;
+                }
+                break;
+            case 'M':
+                openMode = hexstrtoui(argv[i]);
+                break;
+            case 'P':
+                pipeMode = hexstrtoui(argv[i]);
+                break;
+            case 'B':
+                bufferSize = atoi(argv[i]);
+                break;
+            default:
+                printf("Error: no such option\r\n");
+                CloseHandle(inFile);
+                CloseHandle(outFile);
+                return 0;
+        }
+        if(errno) {
+            printf("Error: values must be in hex.\r\n");
+            CloseHandle(inFile);
+            CloseHandle(outFile);
+            return 0;
+        }
+    }
+    h = CreateNamedPipe(target, openMode, pipeMode, 1, bufferSize, bufferSize, NMPWAIT_WAIT_FOREVER, NULL);
+    if (h == INVALID_HANDLE_VALUE) {
+        printf("Error: CreateNamedPipe operation failed: %u\r\n", GetLastError());
+        CloseHandle(inFile);
+        CloseHandle(outFile);
+        return 0;
+    }
+    if(ConnectNamedPipe(h, NULL) == 0 && GetLastError() != ERROR_PIPE_CONNECTED) {
+        printf("Error: ConnectNamedPipe operation failed: %u\r\n", GetLastError());
+        CloseHandle(inFile);
+        CloseHandle(outFile);
+        CloseHandle(h);
+        return 0;
+    }
+    buf = malloc(bufferSize);
+    if(buf == NULL) {
+        printf("Error: failed to allocate buffer\r\n");
+        CloseHandle(inFile);
+        CloseHandle(outFile);
+        DisconnectNamedPipe(h);
+        CloseHandle(h);
+        return 0;
+    }
+    if(inFile == NULL) {
+        inFile = h;
+    }
+    if(outFile == NULL) {
+        outFile = h;
+    }
+    while(ReadFile(inFile, buf, bufferSize, &bytesRead, NULL) > 0) {
+        WriteFile(outFile, buf, bytesRead, &bytesRead, NULL);
+    }
+    printf("Success: operation performed successfully\r\n");
+    CloseHandle(inFile);
+    CloseHandle(outFile);
+    DisconnectNamedPipe(h);
+    CloseHandle(h);
+    return 1;
+}
+
index 026620f..0940d65 100644 (file)
@@ -31,8 +31,8 @@ $RUN GetDate ${URL_SHARE}${FILE1}
 $RUN Get ${URL_SHARE}${FILE1}
 $RUN GetType ${URL_SHARE}
 $RUN GrowWrite ${URL_WRITE_DIR}GrowWrite.txt
-$RUN GetURL ${URL_WRITE_DIR}GrowWrite.txt
-$RUN HttpURL ${URL_WRITE_DIR} GrowWrite.txt
+$RUN GetURL ${URL_WRITE_DIR}Append.txt
+$RUN HttpURL ${URL_WRITE_DIR}Append.txt
 $RUN Interleave ${URL_WRITE_DIR} 3
 $RUN IsDir ${URL_SHARE}${SRC_DIR}/
 $RUN Length ${URL_SHARE}${FILE1}
index 17f606e..e3faadb 100644 (file)
 
 package jcifs;
 
-import jcifs.util.Log;
 import java.util.Properties;
-import java.util.StringTokenizer;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.io.FileInputStream;
-import java.io.IOException;
+import java.io.*;
 import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.StringTokenizer;
+import jcifs.util.LogStream;
 
 /**
- * This class mananges configuration information specific to the jCIFS library. There are several ways to set jCIFS properties. See the <a href="../overview-summary.html#scp">overview page of the API documentation</a> for details.
+ * This class uses a static {@link java.util.Properties} to act
+ * as a cental repository for all jCIFS configuration properties. It cannot be
+ * instantiated. Similar to <code>System</code> properties the namespace
+ * is global therefore property names should be unique. Before use,
+ * the <code>load</code> method should be called with the name of a
+ * <code>Properties</code> file (or <code>null</code> indicating no
+ * file) to initialize the <code>Config</code>. The <code>System</code>
+ * properties will then populate the <code>Config</code> as well potentially
+ * overwriting properties from the file. Thus properties provided on the
+ * commandline with the <code>-Dproperty.name=value</code> VM parameter
+ * will override properties from the configuration file.
+ * <p>
+ * There are several ways to set jCIFS properties. See
+ * the <a href="../overview-summary.html#scp">overview page of the API
+ * documentation</a> for details.
  */
 
 public class Config {
 
-/**
- * This static method registers the SMB URL protocol handler which is required to use SMB URLs with the <tt>java.net.URL</tt> class. If this method is not called before attempting to create an SMB URL with the URL class the following exception will occur:
-<blockquote><pre>
-Exception MalformedURLException: unknown protocol: smb
-      at java.net.URL.<init>(URL.java:480)
-      at java.net.URL.<init>(URL.java:376)
-      at java.net.URL.<init>(URL.java:330)
-      at jcifs.smb.SmbFile.<init>(SmbFile.java:355)
-      ...
-</pre><blockquote>
- */
+    /**
+     * The static <code>Properties</code>.
+     */
+
+    private static Properties prp = new Properties();
+    private static LogStream log;
+
+    static {
+        String filename;
+        int level;
+        FileInputStream in = null;
+
+        log = LogStream.getInstance();
+
+        try {
+            filename = System.getProperty( "jcifs.properties" );
+            if( filename != null && filename.length() > 1 ) {
+                in = new FileInputStream( filename );
+            }
+            Config.load( in );
+        } catch( IOException ioe ) {
+            if( log.level > 0 )
+                ioe.printStackTrace( log );
+        }
+
+        if(( level = Config.getInt( "jcifs.util.loglevel", -1 )) != -1 ) {
+            LogStream.setLevel( level );
+        }
+
+        if( log.level > 2 ) {
+            try {
+                prp.store( log, "JCIFS PROPERTIES" );
+            } catch( IOException ioe ) {
+            }
+        }
+    }
+
+    /**
+     * This static method registers the SMB URL protocol handler which is
+     * required to use SMB URLs with the <tt>java.net.URL</tt> class. If this
+     * method is not called before attempting to create an SMB URL with the
+     * URL class the following exception will occur:
+     * <blockquote><pre>
+     * Exception MalformedURLException: unknown protocol: smb
+     *       at java.net.URL.<init>(URL.java:480)
+     *       at java.net.URL.<init>(URL.java:376)
+     *       at java.net.URL.<init>(URL.java:330)
+     *       at jcifs.smb.SmbFile.<init>(SmbFile.java:355)
+     *       ...
+     * </pre><blockquote>
+     */
+
+    public static void registerSmbURLHandler() {
+        String ver, pkgs;
+
+        ver = System.getProperty( "java.version" );
+        if( ver.startsWith( "1.1." ) || ver.startsWith( "1.2." )) {
+             throw new RuntimeException( "jcifs-0.7.0b4+ requires Java 1.3 or above. You are running " + ver );
+        }
+        pkgs = System.getProperty( "java.protocol.handler.pkgs" );
+        if( pkgs == null ) {
+            pkgs = "jcifs";
+        } else {
+            pkgs += "|jcifs";
+        }
+        System.setProperty( "java.protocol.handler.pkgs", pkgs );
+    }
+
+    // supress javadoc constructor summary by removing 'protected'
+    Config() {}
+
+    /**
+     * Set the default properties of the static Properties used by <tt>Config</tt>. This permits
+     * a different Properties object/file to be used as the source of properties for
+     * use by the jCIFS library. The Properties must be set <i>before jCIFS
+     * classes are accessed</i> as most jCIFS classes load properties statically once.
+     * Using this method will also override properties loaded
+     * using the <tt>-Djcifs.properties=</tt> commandline parameter.
+     */
+
+    public static void setProperties( Properties prp ) {
+        Config.prp = new Properties( prp );
+        Config.prp.putAll( System.getProperties() );
+    }
+
+    /**
+     * Load the <code>Config</code> with properties from the stream
+     * <code>in</code> from a <code>Properties</code> file.
+     */
+
+    public static void load( InputStream in ) throws IOException {
+        if( in != null ) {
+            prp.load( in );
+        }
+        prp.putAll( System.getProperties() );
+    }
+
+    public static void store( OutputStream out, String header ) throws IOException {
+        prp.store( out, header );
+    }
+
+    /**
+     * List the properties in the <code>Code</code>.
+     */
+
+    public static void list( PrintStream out ) throws IOException {
+        prp.list( out );
+    }
+
+    /**
+     * Add a property.
+     */
+
+    public static Object setProperty( String key, String value ) {
+        return prp.setProperty( key, value );
+    }
+
+    /**
+     * Retrieve a property as an <code>Object</code>.
+     */
+
+    public static Object get( String key ) {
+        return prp.get( key );
+    }
+
+    /**
+     * Retrieve a <code>String</code>. If the key cannot be found,
+     * the provided <code>def</code> default parameter will be returned.
+     */
+
+    public static String getProperty( String key, String def ) {
+        return prp.getProperty( key, def );
+    }
+
+    /**
+     * Retrieve a <code>String</code>. If the property is not found, <code>null</code> is returned.
+     */
+
+    public static String getProperty( String key ) {
+        return prp.getProperty( key );
+    }
+
+    /**
+     * Retrieve an <code>int</code>. If the key does not exist or
+     * cannot be converted to an <code>int</code>, the provided default
+     * argument will be returned.
+     */
+
+    public static int getInt( String key, int def ) {
+        String s = prp.getProperty( key );
+        if( s != null ) {
+            try {
+                def = Integer.parseInt( s );
+            } catch( NumberFormatException nfe ) {
+                if( log.level > 0 )
+                    nfe.printStackTrace( log );
+            }
+        }
+        return def;
+    }
+
+    /**
+     * Retrieve an <code>int</code>. If the property is not found, <code>-1</code> is returned.
+     */
+
+    public static int getInt( String key ) {
+        String s = prp.getProperty( key );
+        int result = -1;
+        if( s != null ) {
+            try {
+                result = Integer.parseInt( s );
+            } catch( NumberFormatException nfe ) {
+                if( log.level > 0 )
+                    nfe.printStackTrace( log );
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Retrieve a <code>long</code>. If the key does not exist or
+     * cannot be converted to a <code>long</code>, the provided default
+     * argument will be returned.
+     */
+
+    public static long getLong( String key, long def ) {
+        String s = prp.getProperty( key );
+        if( s != null ) {
+            try {
+                def = Long.parseLong( s );
+            } catch( NumberFormatException nfe ) {
+                if( log.level > 0 )
+                    nfe.printStackTrace( log );
+            }
+        }
+        return def;
+    }
+
+    /** 
+     * Retrieve an <code>InetAddress</code>. If the address is not
+     * an IP address and cannot be resolved <code>null</code> will
+     * be returned.
+     */
+
+    public static InetAddress getInetAddress( String key, InetAddress def ) {
+        String addr = prp.getProperty( key );
+        if( addr != null ) {
+            try {
+                def = InetAddress.getByName( addr );
+            } catch( UnknownHostException uhe ) {
+                if( log.level > 0 ) {
+                    log.println( addr );
+                    uhe.printStackTrace( log );
+                }
+            }
+        }
+        return def;
+    }
+
+    /**
+     * Retrieve a boolean value. If the property is not found, the value of <code>def</code> is returned.
+     */
+
+    public static boolean getBoolean( String key, boolean def ) {
+        String b = getProperty( key );
+        if( b != null ) {
+            def = b.toLowerCase().equals( "true" );
+        }
+        return def;
+    }
 
-       public static void registerSmbURLHandler() {
-               String ver, pkgs;
-
-               ver = System.getProperty( "java.version" );
-               if( ver.startsWith( "1.1." ) || ver.startsWith( "1.2." )) {
-                    throw new RuntimeException( "jcifs-0.7.0b4+ requires Java 1.3 or above. You are running " + ver );
-               }
-               pkgs = System.getProperty( "java.protocol.handler.pkgs" );
-               if( pkgs == null ) {
-                       pkgs = "jcifs";
-               } else {
-                       pkgs += "|jcifs";
-               }
-               System.setProperty( "java.protocol.handler.pkgs", pkgs );
-       }
-
-       static {
-               String filename, mask;
-               FileInputStream in = null;
-
-               try {
-                       filename = System.getProperty( "jcifs.properties" );
-                       if( filename != null && filename.length() > 1 ) {
-                               in = new FileInputStream( filename );
-                       }
-                       jcifs.util.Config.load( in );
-               } catch( IOException ioe ) {
-                       ioe.printStackTrace();
-               }
-
-               if(( mask = jcifs.util.Config.getProperty( "jcifs.util.log" )) != null ) {
-
-                       StringTokenizer st = new StringTokenizer( mask, "," );
-                       while( st.hasMoreTokens() ) {
-                               String s = st.nextToken().toUpperCase();
-                               if( s.startsWith( "ALL" )) {
-                                       Log.addMask( Log.ALL );
-                               } else if( s.startsWith( "EXC" )) {
-                                       Log.addMask( Log.EXCEPTIONS );
-                               } else if( s.startsWith( "WAR" )) {
-                                       Log.addMask( Log.WARNINGS );
-                               } else if( s.startsWith( "DEB" )) {
-                                       Log.addMask( Log.DEBUGGING );
-                               } else if( s.startsWith( "HEX" )) {
-                                       Log.addMask( Log.HEX_DUMPS );
-                               } else if( s.startsWith( "NON" )) {
-                                       Log.setMask( Log.NONE );
-                                       break;
-                               }
-                       }
-               }
-               jcifs.util.Config.printProperties( "properties loaded" );
-       }
-
-       public static void load( InputStream in ) throws IOException {
-               jcifs.util.Config.load( in );
-       }
-       public static void list( PrintStream out ) throws IOException {
-               jcifs.util.Config.list( out );
-       }
-       public static String setProperty( String key, String value ) {
-               return jcifs.util.Config.setProperty( key, value );
-       }
-       public static Object get( String key ) {
-               return jcifs.util.Config.get( key );
-       }
-       public static String getProperty( String key, String def ) {
-               return jcifs.util.Config.getProperty( key, def );
-       }
-       public static String getProperty( String key ) {
-               return jcifs.util.Config.getProperty( key );
-       }
-       public static int getInt( String key, int def ) {
-               return jcifs.util.Config.getInt( key, def );
-       }
-       public static int getInt( String key ) {
-               return jcifs.util.Config.getInt( key );
-       }
-       public static InetAddress getInetAddress( String key, InetAddress def ) {
-               return jcifs.util.Config.getInetAddress( key, def );
-       }
-       public static boolean getBoolean( String key, boolean def ) {
-               return jcifs.util.Config.getBoolean( key, def );
-       }
+    public static InetAddress[] getInetAddressArray( String key, String delim, InetAddress[] def ) {
+        String p = getProperty( key );
+        if( p != null ) {
+            StringTokenizer tok = new StringTokenizer( p, delim );
+            int len = tok.countTokens();
+            InetAddress[] arr = new InetAddress[len];
+            for( int i = 0; i < len; i++ ) {
+                String addr = tok.nextToken();
+                try {
+                    arr[i] = InetAddress.getByName( addr );
+                } catch( UnknownHostException uhe ) {
+                    if( log.level > 0 ) {
+                        log.println( addr );
+                        uhe.printStackTrace( log );
+                    }
+                    return def;
+                }
+            }
+            return arr;
+        }
+        return def;
+    }
 }
 
index 92d7b24..ef27421 100644 (file)
@@ -22,9 +22,9 @@ import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.io.IOException;
 import java.util.StringTokenizer;
-import jcifs.util.Log;
 import jcifs.netbios.NbtAddress;
 import jcifs.netbios.Lmhosts;
+import jcifs.util.LogStream;
 
 /**
  * <p>Under normal conditions it is not necessary to use
@@ -46,144 +46,146 @@ import jcifs.netbios.Lmhosts;
 
 public class UniAddress {
 
-       static final int RESOLVER_WINS    = 0;
-       static final int RESOLVER_BCAST   = 1;
-       static final int RESOLVER_DNS     = 2;
-       static final int RESOLVER_LMHOSTS = 3;
-
-       static int[] resolveOrder;
-       static InetAddress nbns, baddr;
-
-       static {
-               String ro = Config.getProperty( "jcifs.resolveOrder" );
-               nbns = Config.getInetAddress( "jcifs.netbios.wins", null );
-
-               try {
-                       baddr = Config.getInetAddress( "jcifs.netbios.baddr",
-                                                               InetAddress.getByName( "255.255.255.255" ));
-               } catch( UnknownHostException uhe ) {
-               }
-
-               if( ro == null || ro.length() == 0 ) {
-
-                       /* No resolveOrder has been specified, use the
-                        * default which is LMHOSTS,WINS,BCAST,DNS or just
-                        * LMHOSTS,BCAST,DNS if jcifs.netbios.wins has not
-                        * been specified.
-                        */
-
-                       if( nbns == null ) {
-                               resolveOrder = new int[3];
-                               resolveOrder[0] = RESOLVER_LMHOSTS;
-                               resolveOrder[1] = RESOLVER_BCAST;
-                               resolveOrder[2] = RESOLVER_DNS;
-                       } else {
-                               resolveOrder = new int[4];
-                               resolveOrder[0] = RESOLVER_LMHOSTS;
-                               resolveOrder[1] = RESOLVER_WINS;
-                               resolveOrder[2] = RESOLVER_BCAST;
-                               resolveOrder[3] = RESOLVER_DNS;
-                       }
-               } else {
-                       int[] tmp = new int[4];
-                       StringTokenizer st = new StringTokenizer( ro, "," );
-                       int i = 0;
-                       while( st.hasMoreTokens() ) {
-                               String s = st.nextToken().trim();
-                               if( s.equalsIgnoreCase( "LMHOSTS" )) {
-                                       tmp[i++] = RESOLVER_LMHOSTS;
-                               } else if( s.equalsIgnoreCase( "WINS" )) {
-                                       if( nbns == null ) {
-                                               Log.println( Log.WARNINGS, "netbios name service warning",
-                                                               " resolveOrder specifies WINS however the " +
-                                                               "jcifs.netbios.wins property has not been set" );
-                                               continue;
-                                       }
-                                       tmp[i++] = RESOLVER_WINS;
-                               } else if( s.equalsIgnoreCase( "BCAST" )) {
-                                       tmp[i++] = RESOLVER_BCAST;
-                               } else if( s.equalsIgnoreCase( "DNS" )) {
-                                       tmp[i++] = RESOLVER_DNS;
-                               } else {
-                                       Log.println( Log.WARNINGS, "netbios name service warning",
-                                                               "unknown resolver method: " + s );
-                               }
-                       }
-                       resolveOrder = new int[i];
-                       System.arraycopy( tmp, 0, resolveOrder, 0, i );
-               }
-       }
-
-       static class Sem {
-               Sem( int count ) {
-                       this.count = count;
-               }
-               int count;
-       }
-
-       static class QueryThread extends Thread {
-       
-               Sem sem;
-               String host, scope;
-               int type;
-               NbtAddress ans = null;
-               InetAddress svr;
-               UnknownHostException uhe;
-       
-               QueryThread( Sem sem, String host, int type,
-                                               String scope, InetAddress svr ) {
-                       super( "JCIFS-QueryThread: " + host );
-                       this.sem = sem;
-                       this.host = host;
-                       this.type = type;
-                       this.scope = scope;
-                       this.svr = svr;
-               }
-               public void run() {
-                       try {
-                               ans = NbtAddress.getByName( host, type, scope, svr );
-                       } catch( UnknownHostException uhe ) {
-                               this.uhe = uhe;
-                       } catch( Exception ex ) {
-                               this.uhe = new UnknownHostException( ex.getMessage() );
-                       } finally {
-                               synchronized( sem ) {
-                                       sem.count--;
-                                       sem.notify();
-                               }
-                       }
-               }
-       }
-
-       static NbtAddress lookupServerOrWorkgroup( String name, InetAddress svr )
-                                                                                                       throws UnknownHostException {
-               Sem sem = new Sem( 2 );
-               int type = svr == nbns ? 0x1b : 0x1d;
-               QueryThread q1x = new QueryThread( sem, name, type, null, svr );
-               QueryThread q20 = new QueryThread( sem, name, 0x20, null, svr );
-               q1x.setDaemon( true );
-               q20.setDaemon( true );
-               try {
-                       synchronized( sem ) {
-                               q1x.start();
-                               q20.start();
-
-                               while( sem.count > 0 && q1x.ans == null && q20.ans == null ) {
-//System.out.println( "sem.count=" + sem.count + ",q1x.ans=" + q1x.ans + ",q20.ans=" + q20.ans );
-                                       sem.wait();
-                               }
-                       }
-               } catch( InterruptedException ie ) {
-                       throw new UnknownHostException( name );
-               }
-               if( q1x.ans != null ) {
-                       return q1x.ans;
-               } else if( q20.ans != null ) {
-                       return q20.ans;
-               } else {
-                       throw q1x.uhe;
-               }
-       }
+    private static final int RESOLVER_WINS    = 0;
+    private static final int RESOLVER_BCAST   = 1;
+    private static final int RESOLVER_DNS     = 2;
+    private static final int RESOLVER_LMHOSTS = 3;
+
+    private static int[] resolveOrder;
+    private static InetAddress baddr;
+
+    private static LogStream log = LogStream.getInstance();
+
+    static {
+        String ro = Config.getProperty( "jcifs.resolveOrder" );
+        InetAddress nbns = NbtAddress.getNBNSAddress();
+
+        try {
+            baddr = Config.getInetAddress( "jcifs.netbios.baddr",
+                                InetAddress.getByName( "255.255.255.255" ));
+        } catch( UnknownHostException uhe ) {
+        }
+
+        if( ro == null || ro.length() == 0 ) {
+
+            /* No resolveOrder has been specified, use the
+             * default which is LMHOSTS,WINS,BCAST,DNS or just
+             * LMHOSTS,BCAST,DNS if jcifs.netbios.wins has not
+             * been specified.
+             */
+
+            if( nbns == null ) {
+                resolveOrder = new int[3];
+                resolveOrder[0] = RESOLVER_LMHOSTS;
+                resolveOrder[1] = RESOLVER_BCAST;
+                resolveOrder[2] = RESOLVER_DNS;
+            } else {
+                resolveOrder = new int[4];
+                resolveOrder[0] = RESOLVER_LMHOSTS;
+                resolveOrder[1] = RESOLVER_WINS;
+                resolveOrder[2] = RESOLVER_BCAST;
+                resolveOrder[3] = RESOLVER_DNS;
+            }
+        } else {
+            int[] tmp = new int[4];
+            StringTokenizer st = new StringTokenizer( ro, "," );
+            int i = 0;
+            while( st.hasMoreTokens() ) {
+                String s = st.nextToken().trim();
+                if( s.equalsIgnoreCase( "LMHOSTS" )) {
+                    tmp[i++] = RESOLVER_LMHOSTS;
+                } else if( s.equalsIgnoreCase( "WINS" )) {
+                    if( nbns == null ) {
+                        if( log.level > 1 ) {
+                            log.println( "UniAddress resolveOrder specifies WINS however the " +
+                                    "jcifs.netbios.wins property has not been set" );
+                        }
+                        continue;
+                    }
+                    tmp[i++] = RESOLVER_WINS;
+                } else if( s.equalsIgnoreCase( "BCAST" )) {
+                    tmp[i++] = RESOLVER_BCAST;
+                } else if( s.equalsIgnoreCase( "DNS" )) {
+                    tmp[i++] = RESOLVER_DNS;
+                } else if( log.level > 1 ) {
+                    log.println( "unknown resolver method: " + s );
+                }
+            }
+            resolveOrder = new int[i];
+            System.arraycopy( tmp, 0, resolveOrder, 0, i );
+        }
+    }
+
+    static class Sem {
+        Sem( int count ) {
+            this.count = count;
+        }
+        int count;
+    }
+
+    static class QueryThread extends Thread {
+    
+        Sem sem;
+        String host, scope;
+        int type;
+        NbtAddress ans = null;
+        InetAddress svr;
+        UnknownHostException uhe;
+    
+        QueryThread( Sem sem, String host, int type,
+                        String scope, InetAddress svr ) {
+            super( "JCIFS-QueryThread: " + host );
+            this.sem = sem;
+            this.host = host;
+            this.type = type;
+            this.scope = scope;
+            this.svr = svr;
+        }
+        public void run() {
+            try {
+                ans = NbtAddress.getByName( host, type, scope, svr );
+            } catch( UnknownHostException uhe ) {
+                this.uhe = uhe;
+            } catch( Exception ex ) {
+                this.uhe = new UnknownHostException( ex.getMessage() );
+            } finally {
+                synchronized( sem ) {
+                    sem.count--;
+                    sem.notify();
+                }
+            }
+        }
+    }
+
+    static NbtAddress lookupServerOrWorkgroup( String name, InetAddress svr )
+                                                    throws UnknownHostException {
+        Sem sem = new Sem( 2 );
+        int type = NbtAddress.isNBNS( svr ) ? 0x1b : 0x1d;
+
+        QueryThread q1x = new QueryThread( sem, name, type, null, svr );
+        QueryThread q20 = new QueryThread( sem, name, 0x20, null, svr );
+        q1x.setDaemon( true );
+        q20.setDaemon( true );
+        try {
+            synchronized( sem ) {
+                q1x.start();
+                q20.start();
+
+                while( sem.count > 0 && q1x.ans == null && q20.ans == null ) {
+                    sem.wait();
+                }
+            }
+        } catch( InterruptedException ie ) {
+            throw new UnknownHostException( name );
+        }
+        if( q1x.ans != null ) {
+            return q1x.ans;
+        } else if( q20.ans != null ) {
+            return q20.ans;
+        } else {
+            throw q1x.uhe;
+        }
+    }
 
 /** 
  * Determines the address of a host given it's host name. The name can be a
@@ -193,174 +195,174 @@ public class UniAddress {
  * @throws java.net.UnknownHostException if there is an error resolving the name
  */
 
-       public static UniAddress getByName( String hostname )
-                                                                               throws UnknownHostException {
-               return getByName( hostname, false );
-       }
-
-       static boolean isDotQuadIP( String hostname ) {
-               if( Character.isDigit( hostname.charAt( 0 ))) {
-                       int i, len, dots;
-                       char[] data;
-
-                       i = dots = 0;                    /* quick IP address validation */
-                       len = hostname.length();
-                       data = hostname.toCharArray();
-                       while( i < len && Character.isDigit( data[i++] )) {
-                               if( i == len && dots == 3 ) {
-                                       // probably an IP address
-                                       return true;
-                               }
-                               if( i < len && data[i] == '.' ) {
-                                       dots++;
-                                       i++;
-                               }
-                       }
-               }
-
-               return false;
-       }
-
-       static boolean isValidDnsName( String hostname ) {
-               // Simple for now. Just handles "1" --> 1/0.0.0.1 kind of stuff
-               return Character.isDigit( hostname.charAt( 0 )) == false;
-       }
-
-       public static UniAddress getByName( String hostname,
-                                                                               boolean possibleNTDomainOrWorkgroup )
-                                                                               throws UnknownHostException {
-               Object addr;
-               int i;
-
-               if( hostname == null || hostname.length() == 0 ) {
-                       throw new UnknownHostException();
-               }
-
-               if( isDotQuadIP( hostname )) {
-                       return new UniAddress( NbtAddress.getByName( hostname ));
-               }
-
-               for( i = 0; i < resolveOrder.length; i++ ) {
-                       try {
-                               switch( resolveOrder[i] ) {
-                                       case RESOLVER_LMHOSTS:
-                                               if(( addr = Lmhosts.getByName( hostname )) == null ) {
-                                                       continue;
-                                               }
-                                               break;
-                                       case RESOLVER_WINS:
-                                               if( hostname == NbtAddress.MASTER_BROWSER_NAME ||
-                                                                                                       hostname.length() > 15 ) {
-                                                                                                       // invalid netbios name
-                                                       continue;
-                                               }
-                                               if( possibleNTDomainOrWorkgroup ) {
-                                                       addr = lookupServerOrWorkgroup( hostname, nbns );
-                                               } else {
-                                                       addr = NbtAddress.getByName( hostname, 0x20, null, nbns );
-                                               }
-                                               break;
-                                       case RESOLVER_BCAST:
-                                               if( hostname.length() > 15 ) {
-                                                       // invalid netbios name
-                                                       continue;
-                                               }
-                                               if( possibleNTDomainOrWorkgroup ) {
-                                                       addr = lookupServerOrWorkgroup( hostname, baddr );
-                                               } else {
-                                                       addr = NbtAddress.getByName( hostname, 0x20, null, baddr );
-                                               }
-                                               break;
-                                       case RESOLVER_DNS:
-                                               if( isValidDnsName( hostname ) == false ) {
-                                                       throw new UnknownHostException( hostname );
-                                               }
-                                               addr = InetAddress.getByName( hostname );
-                                               break;
-                                       default:
-                                               throw new UnknownHostException( hostname );
-                               }
-                               return new UniAddress( addr ); // Success
-                       } catch( IOException ioe ) {
-                               // Failure
-                       }
-               }
-               throw new UnknownHostException( hostname );
-       }
-
-       Object addr;
-       String calledName;
-
-       /**
-        * Wrap an <tt>InetAddress</tt> or <tt>NbtAddress</tt>.
-        */
-       public UniAddress( Object addr ) {
-               if( addr == null ) {
-                       throw new IllegalArgumentException();
-               }
-               this.addr = addr;
-       }
-
-       public int hashCode() {
-               return addr.hashCode();
-       }
-       public boolean equals( Object obj ) {
-               return obj instanceof UniAddress && addr.hashCode() == obj.hashCode();
+    public static UniAddress getByName( String hostname )
+                                        throws UnknownHostException {
+        return getByName( hostname, false );
+    }
+
+    static boolean isDotQuadIP( String hostname ) {
+        if( Character.isDigit( hostname.charAt( 0 ))) {
+            int i, len, dots;
+            char[] data;
+
+            i = dots = 0;                    /* quick IP address validation */
+            len = hostname.length();
+            data = hostname.toCharArray();
+            while( i < len && Character.isDigit( data[i++] )) {
+                if( i == len && dots == 3 ) {
+                    // probably an IP address
+                    return true;
+                }
+                if( i < len && data[i] == '.' ) {
+                    dots++;
+                    i++;
+                }
+            }
+        }
+
+        return false;
+    }
+
+    static boolean isValidDnsName( String hostname ) {
+        // Simple for now. Just handles "1" --> 1/0.0.0.1 kind of stuff
+        return Character.isDigit( hostname.charAt( 0 )) == false;
+    }
+
+    public static UniAddress getByName( String hostname,
+                                        boolean possibleNTDomainOrWorkgroup )
+                                        throws UnknownHostException {
+        Object addr;
+        int i;
+
+        if( hostname == null || hostname.length() == 0 ) {
+            throw new UnknownHostException();
+        }
+
+        if( isDotQuadIP( hostname )) {
+            return new UniAddress( NbtAddress.getByName( hostname ));
+        }
+
+        for( i = 0; i < resolveOrder.length; i++ ) {
+            try {
+                switch( resolveOrder[i] ) {
+                    case RESOLVER_LMHOSTS:
+                        if(( addr = Lmhosts.getByName( hostname )) == null ) {
+                            continue;
+                        }
+                        break;
+                    case RESOLVER_WINS:
+                        if( hostname == NbtAddress.MASTER_BROWSER_NAME ||
+                                                    hostname.length() > 15 ) {
+                                                    // invalid netbios name
+                            continue;
+                        }
+                        if( possibleNTDomainOrWorkgroup ) {
+                            addr = lookupServerOrWorkgroup( hostname, NbtAddress.getNBNSAddress() );
+                        } else {
+                            addr = NbtAddress.getByName( hostname, 0x20, null, NbtAddress.getNBNSAddress() );
+                        }
+                        break;
+                    case RESOLVER_BCAST:
+                        if( hostname.length() > 15 ) {
+                            // invalid netbios name
+                            continue;
+                        }
+                        if( possibleNTDomainOrWorkgroup ) {
+                            addr = lookupServerOrWorkgroup( hostname, baddr );
+                        } else {
+                            addr = NbtAddress.getByName( hostname, 0x20, null, baddr );
+                        }
+                        break;
+                    case RESOLVER_DNS:
+                        if( isValidDnsName( hostname ) == false ) {
+                            throw new UnknownHostException( hostname );
+                        }
+                        addr = InetAddress.getByName( hostname );
+                        break;
+                    default:
+                        throw new UnknownHostException( hostname );
+                }
+                return new UniAddress( addr ); // Success
+            } catch( IOException ioe ) {
+                // Failure
+            }
+        }
+        throw new UnknownHostException( hostname );
+    }
+
+    Object addr;
+    String calledName;
+
+    /**
+     * Wrap an <tt>InetAddress</tt> or <tt>NbtAddress</tt>.
+     */
+    public UniAddress( Object addr ) {
+        if( addr == null ) {
+            throw new IllegalArgumentException();
+        }
+        this.addr = addr;
+    }
+
+    public int hashCode() {
+        return addr.hashCode();
+    }
+    public boolean equals( Object obj ) {
+        return obj instanceof UniAddress && addr.hashCode() == obj.hashCode();
 // addr.equals( ((UniAddress)obj).addr );
-       }
+    }
 
 /** Guess first called name to try for session establishment. This
  * methods are used by the smb package.
  */
-       public String firstCalledName() {
-               if( addr instanceof NbtAddress ) {
-                       return ((NbtAddress)addr).firstCalledName();
-               } else {
-                       calledName = ((InetAddress)addr).getHostName();
-                       if( isDotQuadIP( calledName )) {
-                               calledName = NbtAddress.SMBSERVER_NAME;
-                       } else {
-                               int i = calledName.indexOf( '.' );
-                               if( i > 1 && i < 15 ) {
-                                       calledName = calledName.substring( 0, i ).toUpperCase();
-                               } else if( calledName.length() > 15 ) {
-                                       calledName = NbtAddress.SMBSERVER_NAME;
-                               } else {
-                                       calledName = calledName.toUpperCase();
-                               }
-                       }
-               }
-
-               return calledName;
+    public String firstCalledName() {
+        if( addr instanceof NbtAddress ) {
+            return ((NbtAddress)addr).firstCalledName();
+        } else {
+            calledName = ((InetAddress)addr).getHostName();
+            if( isDotQuadIP( calledName )) {
+                calledName = NbtAddress.SMBSERVER_NAME;
+            } else {
+                int i = calledName.indexOf( '.' );
+                if( i > 1 && i < 15 ) {
+                    calledName = calledName.substring( 0, i ).toUpperCase();
+                } else if( calledName.length() > 15 ) {
+                    calledName = NbtAddress.SMBSERVER_NAME;
+                } else {
+                    calledName = calledName.toUpperCase();
+                }
+            }
+        }
+
+        return calledName;
     }
 /** Guess next called name to try for session establishment. This
  * methods are used by the smb package.
  */
-       public String nextCalledName() {
-               if( addr instanceof NbtAddress ) {
-                       return ((NbtAddress)addr).nextCalledName();
-               } else if( calledName != NbtAddress.SMBSERVER_NAME ) {
-                       calledName = NbtAddress.SMBSERVER_NAME;
-                       return calledName;
-               }
-               return null;
-       }
-       public Object getAddress() {
-               return addr;
-       }
-       public String getHostName() {
-               if( addr instanceof NbtAddress ) {
-                       return ((NbtAddress)addr).getHostName();
-               }
-               return ((InetAddress)addr).getHostName();
-       }
-       public String getHostAddress() {
-               if( addr instanceof NbtAddress ) {
-                       return ((NbtAddress)addr).getHostAddress();
-               }
-               return ((InetAddress)addr).getHostAddress();
-       }
+    public String nextCalledName() {
+        if( addr instanceof NbtAddress ) {
+            return ((NbtAddress)addr).nextCalledName();
+        } else if( calledName != NbtAddress.SMBSERVER_NAME ) {
+            calledName = NbtAddress.SMBSERVER_NAME;
+            return calledName;
+        }
+        return null;
+    }
+    public Object getAddress() {
+        return addr;
+    }
+    public String getHostName() {
+        if( addr instanceof NbtAddress ) {
+            return ((NbtAddress)addr).getHostName();
+        }
+        return ((InetAddress)addr).getHostName();
+    }
+    public String getHostAddress() {
+        if( addr instanceof NbtAddress ) {
+            return ((NbtAddress)addr).getHostAddress();
+        }
+        return ((InetAddress)addr).getHostAddress();
+    }
     public String toString() {
         return addr.toString();
-       }
+    }
 }
index d915faa..b077c06 100644 (file)
@@ -1,6 +1,6 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                      "Eric Glass" <jcifs at samba dot org>
+ *                   "Eric Glass" <jcifs at samba dot org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
index 005e6e5..c6af505 100644 (file)
@@ -42,460 +42,461 @@ import jcifs.util.Base64;
 
 public class NetworkExplorer extends HttpServlet {
 
-       private MimeMap mimeMap;
-       private String style;
-       private NtlmSsp ntlmSsp;
-       private boolean credentialsSupplied;
-       private boolean enableBasic;
-       private boolean insecureBasic;
-       private String realm, defaultDomain;
-
-       public void init() throws ServletException {
-               InputStream is;
-               StringBuffer sb = new StringBuffer();
-               byte[] buf = new byte[1024];
-               int n;
-               String name;
-
-               Config.setProperty( "jcifs.smb.client.soTimeout", "300000" );
-               Config.setProperty( "jcifs.smb.client.attrExpirationPeriod", "120000" );
-
-               Enumeration e = getInitParameterNames();
-               while( e.hasMoreElements() ) {
-                       name = (String)e.nextElement();
-                       if( name.startsWith( "jcifs." )) {
-                               Config.setProperty( name, getInitParameter( name ));
-                       }
-               }
-
-               if( Config.getProperty( "jcifs.smb.client.username" ) == null ) {
-                       ntlmSsp = new NtlmSsp();
-               } else {
-                       credentialsSupplied = true;
-               }
-
-               try {
-                       mimeMap = new MimeMap();
-                       is = getClass().getClassLoader().getResourceAsStream( "jcifs/http/ne.css" );
-                       while(( n = is.read( buf )) != -1 ) {
-                               sb.append( new String( buf, 0, n, "ISO8859_1" ));
-                       }
-                       style = sb.toString();
-               } catch( IOException ioe ) {
-                       throw new ServletException( ioe.getMessage() );
-               }
-
-               enableBasic = Config.getBoolean("jcifs.http.enableBasic", false );
-               insecureBasic = Config.getBoolean("jcifs.http.insecureBasic", false );
-               realm = Config.getProperty("jcifs.http.basicRealm");
-               if (realm == null) realm = "jCIFS";
-               defaultDomain = Config.getProperty("jcifs.smb.client.domain");
-       }
-
-       void doFile( HttpServletRequest req,
-                               HttpServletResponse resp, SmbFile file ) throws IOException {
-               byte[] buf = new byte[8192];
-               SmbFileInputStream in;
-               ServletOutputStream out;
-               String url, type;
-               int n;
-
-               in = new SmbFileInputStream( file );
-               out = resp.getOutputStream();
-               url = file.getPath();
-
-               resp.setContentType( "text/plain" );
-
-               if(( n = url.lastIndexOf( '.' )) > 0 &&
-                               ( type = url.substring( n + 1 )) != null &&
-                               type.length() > 1 && type.length() < 6 ) {
-                       resp.setContentType( mimeMap.getMimeType( type ));
-               }
-               resp.setHeader( "Content-Length", file.length() + "" );
-               resp.setHeader( "Accept-Ranges", "Bytes" );
-
-               while(( n = in.read( buf )) != -1 ) {
-                       out.write( buf, 0, n );
-               }
-       }
-       int compareNames( SmbFile f1, String f1name, SmbFile f2 ) throws IOException {
-               if( f1.isDirectory() != f2.isDirectory() ) {
-                       return f1.isDirectory() ? -1 : 1;
-               }
-               return f1name.compareToIgnoreCase( f2.getName() );
-       }
-       int compareSizes( SmbFile f1, String f1name, SmbFile f2 ) throws IOException {
-               long diff;
-
-               if( f1.isDirectory() != f2.isDirectory() ) {
-                       return f1.isDirectory() ? -1 : 1;
-               }
-               if( f1.isDirectory() ) {
-                       return f1name.compareToIgnoreCase( f2.getName() );
-               }
-               diff = f1.length() - f2.length();
-               if( diff == 0 ) {
-                       return f1name.compareToIgnoreCase( f2.getName() );
-               }
-               return diff > 0 ? -1 : 1;
-       }
-       int compareTypes( SmbFile f1, String f1name, SmbFile f2 ) throws IOException {
-               String f2name, t1, t2;
-               int i;
-
-               if( f1.isDirectory() != f2.isDirectory() ) {
-                       return f1.isDirectory() ? -1 : 1;
-               }
-               f2name = f2.getName();
-               if( f1.isDirectory() ) {
-                       return f1name.compareToIgnoreCase( f2name );
-               }
-               i = f1name.lastIndexOf( '.' );
-               t1 = i == -1 ? "" : f1name.substring( i + 1 );
-               i = f2name.lastIndexOf( '.' );
-               t2 = i == -1 ? "" : f2name.substring( i + 1 );
-
-               i = t1.compareToIgnoreCase( t2 );
-               if( i == 0 ) {
-                       return f1name.compareToIgnoreCase( f2name );
-               }
-               return i;
-       }
-       int compareDates( SmbFile f1, String f1name, SmbFile f2 ) throws IOException {
-               if( f1.isDirectory() != f2.isDirectory() ) {
-                       return f1.isDirectory() ? -1 : 1;
-               }
-               if( f1.isDirectory() ) {
-                       return f1name.compareToIgnoreCase( f2.getName() );
-               }
-               return f1.lastModified() > f2.lastModified() ? -1 : 1;
-       }
-       void doDirectory( HttpServletRequest req, HttpServletResponse resp, SmbFile dir ) throws IOException {
-               PrintWriter out;
-               SmbFile[] dirents;
-               SmbFile f;
-               int i, j, len, maxLen, dirCount, fileCount, sort;
-               String str, name, path, fmt;
-               LinkedList sorted;
-               ListIterator iter;
-               SimpleDateFormat sdf = new SimpleDateFormat( "MM/d/yy h:mm a" );
-               GregorianCalendar cal = new GregorianCalendar();
-
-               sdf.setCalendar( cal );
-
-               dirents = dir.listFiles();
-               sorted = new LinkedList();
-               if(( fmt = req.getParameter( "fmt" )) == null ) {
-                       fmt = "col";
-               }
-               sort = 0;
-               if(( str = req.getParameter( "sort" )) == null || str.equals( "name" )) {
-                       sort = 0;
-               } else if( str.equals( "size" )) {
-                       sort = 1;
-               } else if( str.equals( "type" )) {
-                       sort = 2;
-               } else if( str.equals( "date" )) {
-                       sort = 3;
-               }
-               dirCount = fileCount = 0;
-               maxLen = 28;
-               for( i = 0; i < dirents.length; i++ ) {
-                       try {
-                               if( dirents[i].getType() == SmbFile.TYPE_NAMED_PIPE ) {
-                                       continue;
-                               }
-                       } catch( SmbAuthException sae ) {
-                       }
-                       if( dirents[i].isDirectory() ) {
-                               dirCount++;
-                       } else {
-                               fileCount++;
-                       }
-
-                       name = dirents[i].getName();
-                       len = name.length(); 
-                       if( len > maxLen ) {
-                               maxLen = len;
-                       }
-
-                       iter = sorted.listIterator();
-                       for( j = 0; iter.hasNext(); j++ ) {
-                               if( sort == 0 ) {
-                                       if( compareNames( dirents[i], name, (SmbFile)iter.next() ) < 0 ) {
-                                               break;
-                                       }
-                               } else if( sort == 1 ) {
-                                       if( compareSizes( dirents[i], name, (SmbFile)iter.next() ) < 0 ) {
-                                               break;
-                                       }
-                               } else if( sort == 2 ) {
-                                       if( compareTypes( dirents[i], name, (SmbFile)iter.next() ) < 0 ) {
-                                               break;
-                                       }
-                               } else if( sort == 3 ) {
-                                       if( compareDates( dirents[i], name, (SmbFile)iter.next() ) < 0 ) {
-                                               break;
-                                       }
-                               }
-                       }
-                       sorted.add( j, dirents[i] );
-               }
-               if( maxLen > 50 ) {
-                       maxLen = 50;
-               }
-               maxLen *= 9; /* convert to px */
-
-               out = resp.getWriter();
-
-               resp.setContentType( "text/html" );
-
-               out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">" );
-               out.println( "<html><head><title>Network Explorer</title>" );
-               out.println( "<meta HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">" );
-               out.println( "<style TYPE=\"text/css\">" );
-
-               out.println( style );
-
-               if( dirents.length < 200 ) {
-                       out.println( "    a:hover {" );
-                       out.println( "        background: #a2ff01;" );
-                       out.println( "    }" );
-               }
-
-               out.println( "</STYLE>" );
-               out.println( "</head><body>" );
-
-               out.print( "<a class=\"sort\" style=\"width: " + maxLen + ";\" href=\"?fmt=detail&sort=name\">Name</a>" );
-               out.println( "<a class=\"sort\" href=\"?fmt=detail&sort=size\">Size</a>" );
-               out.println( "<a class=\"sort\" href=\"?fmt=detail&sort=type\">Type</a>" );
-               out.println( "<a class=\"sort\" style=\"width: 180\" href=\"?fmt=detail&sort=date\">Modified</a><br clear='all'><p>" );
-
-               path = dir.getCanonicalPath();
-
-               if( path.length() < 7 ) {
-                       out.println( "<b><big>smb://</big></b><br>" );
-                       path = ".";
-               } else {
-                       out.println( "<b><big>" + path + "</big></b><br>" );
-                       path = "../";
-               }
-               out.println( (dirCount + fileCount) + " objects (" + dirCount + " directories, " + fileCount + " files)<br>" );
-               out.println( "<b><a class=\"plain\" href=\".\">normal</a> | <a class=\"plain\" href=\"?fmt=detail\">detailed</a></b>" );
-               out.println( "<p><table border='0' cellspacing='0' cellpadding='0'><tr><td>" );
-
-               out.print( "<A style=\"width: " + maxLen );
-               out.print( "; height: 18;\" HREF=\"" );
-               out.print( path );
-               out.println( "\"><b>&uarr;</b></a>" );
-               if( fmt.equals( "detail" )) {
-                       out.println( "<br clear='all'>" );
-               }
-
-               if( path.length() == 1 || dir.getType() != SmbFile.TYPE_WORKGROUP ) {
-                       path = "";
-               }
-
-               iter = sorted.listIterator();
-               while( iter.hasNext() ) {
-                       f = (SmbFile)iter.next();
-                       name = f.getName();
-
-                       if( fmt.equals( "detail" )) {
-                               out.print( "<A style=\"width: " + maxLen );
-                               out.print( "; height: 18;\" HREF=\"" );
-                               out.print( path );
-                               out.print( name );
-
-                               if( f.isDirectory() ) {
-                                       out.print( "?fmt=detail\"><b>" );
-                                       out.print( name );
-                                       out.print( "</b></a>" );
-                               } else {
-                                       out.print( "\"><b>" );
-                                       out.print( name );
-                                       out.print( "</b></a><div align='right'>" );
-                                       out.print( (f.length() / 1024) + " KB </div><div>" );
-                                       i = name.lastIndexOf( '.' ) + 1;
-                                       if( i > 1 && (name.length() - i) < 6 ) {
-                                               out.print( name.substring( i ).toUpperCase() + "</div class='ext'>" );
-                                       } else {
-                                               out.print( "&nbsp;</div>" );
-                                       }
-                                       out.print( "<div style='width: 180'>" );
-                                       out.print( sdf.format( new Date( f.lastModified() )));
-                                       out.print( "</div>" );
-                               }
-                               out.println( "<br clear='all'>" );
-                       } else {
-                               out.print( "<A style=\"width: " + maxLen );
-                               if( f.isDirectory() ) {
-                                       out.print( "; height: 18;\" HREF=\"" );
-                                       out.print( path );
-                                       out.print( name );
-                                       out.print( "\"><b>" );
-                                       out.print( name );
-                                       out.print( "</b></a>" );
-                               } else {
-                                       out.print( ";\" HREF=\"" );
-                                       out.print( path );
-                                       out.print( name );
-                                       out.print( "\"><b>" );
-                                       out.print( name );
-                                       out.print( "</b><br><small>" );
-                                       out.print( (f.length() / 1024) + "KB <br>" );
-                                       out.print( sdf.format( new Date( f.lastModified() )));
-                                       out.print( "</small>" );
-                                       out.println( "</a>" );
-                               }
-                       }
-               }
-
-               out.println( "</td></tr></table>" );
-               out.println( "</BODY></HTML>" );
-               out.close();
-       }
-       String parseServerAndShare( String pathInfo ) {
-               char[] out = new char[256];
-               char ch;
-               int len, p, i;
-
-               if( pathInfo == null ) {
-                       return null;
-               }
-               len = pathInfo.length();
-
-               p = i = 0;
-               while( p < len && pathInfo.charAt( p ) == '/' ) {
-                       p++;
-               }
-               if( p == len ) {
-                       return null;
-               }
-               do {                                   /* collect server name */
-                       out[i++] = (ch = pathInfo.charAt( p++ ));
-               } while( p < len && ch != '/' );
-               while( p < len && pathInfo.charAt( p ) == '/' ) {
-                       p++;
-               }
-               if( p < len ) {                 /* then there must be a share */
-                       out[i++] = '/';
-                       do {                            /* collect the share name */
-                               out[i++] = (ch = pathInfo.charAt( p++ ));
-                       } while( p < len && ch != '/' );
-               }
-               return new String( out, 0, i );
-       }
-       public void doGet( HttpServletRequest req,
-                               HttpServletResponse resp ) throws IOException, ServletException {
-               UniAddress dc;
-               String msg, pathInfo, server = null;
-               boolean offerBasic, possibleWorkgroup = true;
-               NtlmPasswordAuthentication ntlm = null;
-               HttpSession ssn = req.getSession( false );
-
-               if(( pathInfo = req.getPathInfo() ) != null ) {
-                       int i;
-                       server = parseServerAndShare( pathInfo );
-                       if( server != null && ( i = server.indexOf( '/' )) > 0 ) {
-                               server = server.substring( 0, i ).toLowerCase();
-                               possibleWorkgroup = false;
-                       } 
-               }
-
-               msg = req.getHeader( "Authorization" );
-               offerBasic = enableBasic && (insecureBasic || req.isSecure());
-
-               if( msg != null && (msg.startsWith( "NTLM " ) || (offerBasic && msg.startsWith("Basic ")))) {
-
-                       if( msg.startsWith("NTLM ")) {
-                               byte[] challenge;
-
-                               if( pathInfo == null || server == null ) {
-                                       String mb = NbtAddress.getByName( NbtAddress.MASTER_BROWSER_NAME, 0x01, null ).getHostAddress();
-                                       dc = UniAddress.getByName( mb );
-                               } else {
-                                       dc = UniAddress.getByName( server, possibleWorkgroup );
-                               }
-
-                               challenge = SmbSession.getChallenge( dc );
-                               if(( ntlm = NtlmSsp.authenticate( req, resp, challenge )) == null ) {
-                                       return;
-                               }
-                       } else {
-                               String auth = new String( Base64.decode( msg.substring(6) ), "US-ASCII" );
-                               int index = auth.indexOf( ':' );
-                               String user = (index != -1) ? auth.substring(0, index) : auth;
-                               String password = (index != -1) ? auth.substring(index + 1) : "";
-                               index = user.indexOf('\\');
-                               if (index == -1) index = user.indexOf('/');
-                               String domain = (index != -1) ? user.substring(0, index) : defaultDomain;
-                               user = (index != -1) ? user.substring(index + 1) : user;
-                               ntlm = new NtlmPasswordAuthentication(domain, user, password);
-                       }
-
-                       req.getSession().setAttribute( "npa-" + server, ntlm );
-
-               } else if( !credentialsSupplied ) {
-                       if( ssn != null ) {
-                               ntlm = (NtlmPasswordAuthentication)ssn.getAttribute( "npa-" + server );
-                       }
-                       if( ntlm == null ) {
-                               resp.setHeader( "WWW-Authenticate", "NTLM" );
-                               if (offerBasic) {
-                                       resp.addHeader( "WWW-Authenticate", "Basic realm=\"" + realm + "\"");
-                               }
-                               resp.setHeader( "Connection", "close" );
-                               resp.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
-                               resp.flushBuffer();
-                               return;
-                       }
-               }
-
-               try {
-                       SmbFile file;
-
-                       if( ntlm != null ) {
-                               file = new SmbFile( "smb:/" + pathInfo , ntlm );
-                       } else if( server == null ) {
-                               file = new SmbFile( "smb://" );
-                       } else {
-                               file = new SmbFile( "smb:/" + pathInfo );
-                       }
-
-                       if( file.isDirectory() ) {
-                               doDirectory( req, resp, file );
-                       } else {
-                               doFile( req, resp, file );
-                       }
-               } catch( SmbAuthException sae ) {
-                       if( ssn != null ) {
-                               ssn.removeAttribute( "npa-" + server );
-                       }
-                       resp.setHeader( "WWW-Authenticate", "NTLM" );
-                       if (offerBasic) {
-                               resp.addHeader( "WWW-Authenticate", "Basic realm=\"" + realm + "\"");
-                       }
-                       resp.setHeader( "Connection", "close" );
-                       resp.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
-                       resp.flushBuffer();
-                       return;
-               } catch( DfsReferral dr ) {
-                       StringBuffer redir = req.getRequestURL();
-                       String qs = req.getQueryString();
+    private MimeMap mimeMap;
+    private String style;
+    private NtlmSsp ntlmSsp;
+    private boolean credentialsSupplied;
+    private boolean enableBasic;
+    private boolean insecureBasic;
+    private String realm, defaultDomain;
+
+    public void init() throws ServletException {
+        InputStream is;
+        StringBuffer sb = new StringBuffer();
+        byte[] buf = new byte[1024];
+        int n;
+        String name;
+
+        Config.setProperty( "jcifs.smb.client.soTimeout", "300000" );
+        Config.setProperty( "jcifs.smb.client.attrExpirationPeriod", "120000" );
+
+        Enumeration e = getInitParameterNames();
+        while( e.hasMoreElements() ) {
+            name = (String)e.nextElement();
+            if( name.startsWith( "jcifs." )) {
+                Config.setProperty( name, getInitParameter( name ));
+            }
+        }
+
+        if( Config.getProperty( "jcifs.smb.client.username" ) == null ) {
+            ntlmSsp = new NtlmSsp();
+        } else {
+            credentialsSupplied = true;
+        }
+
+        try {
+            mimeMap = new MimeMap();
+            is = getClass().getClassLoader().getResourceAsStream( "jcifs/http/ne.css" );
+            while(( n = is.read( buf )) != -1 ) {
+                sb.append( new String( buf, 0, n, "ISO8859_1" ));
+            }
+            style = sb.toString();
+        } catch( IOException ioe ) {
+            throw new ServletException( ioe.getMessage() );
+        }
+
+        enableBasic = Config.getBoolean("jcifs.http.enableBasic", false );
+        insecureBasic = Config.getBoolean("jcifs.http.insecureBasic", false );
+        realm = Config.getProperty("jcifs.http.basicRealm");
+        if (realm == null) realm = "jCIFS";
+        defaultDomain = Config.getProperty("jcifs.smb.client.domain");
+    }
+
+    protected void doFile( HttpServletRequest req,
+                HttpServletResponse resp, SmbFile file ) throws IOException {
+        byte[] buf = new byte[8192];
+        SmbFileInputStream in;
+        ServletOutputStream out;
+        String url, type;
+        int n;
+
+        in = new SmbFileInputStream( file );
+        out = resp.getOutputStream();
+        url = file.getPath();
+
+        resp.setContentType( "text/plain" );
+
+        if(( n = url.lastIndexOf( '.' )) > 0 &&
+                ( type = url.substring( n + 1 )) != null &&
+                type.length() > 1 && type.length() < 6 ) {
+            resp.setContentType( mimeMap.getMimeType( type ));
+        }
+        resp.setHeader( "Content-Length", file.length() + "" );
+        resp.setHeader( "Accept-Ranges", "Bytes" );
+
+        while(( n = in.read( buf )) != -1 ) {
+            out.write( buf, 0, n );
+        }
+    }
+    protected int compareNames( SmbFile f1, String f1name, SmbFile f2 ) throws IOException {
+        if( f1.isDirectory() != f2.isDirectory() ) {
+            return f1.isDirectory() ? -1 : 1;
+        }
+        return f1name.compareToIgnoreCase( f2.getName() );
+    }
+    protected int compareSizes( SmbFile f1, String f1name, SmbFile f2 ) throws IOException {
+        long diff;
+
+        if( f1.isDirectory() != f2.isDirectory() ) {
+            return f1.isDirectory() ? -1 : 1;
+        }
+        if( f1.isDirectory() ) {
+            return f1name.compareToIgnoreCase( f2.getName() );
+        }
+        diff = f1.length() - f2.length();
+        if( diff == 0 ) {
+            return f1name.compareToIgnoreCase( f2.getName() );
+        }
+        return diff > 0 ? -1 : 1;
+    }
+    protected int compareTypes( SmbFile f1, String f1name, SmbFile f2 ) throws IOException {
+        String f2name, t1, t2;
+        int i;
+
+        if( f1.isDirectory() != f2.isDirectory() ) {
+            return f1.isDirectory() ? -1 : 1;
+        }
+        f2name = f2.getName();
+        if( f1.isDirectory() ) {
+            return f1name.compareToIgnoreCase( f2name );
+        }
+        i = f1name.lastIndexOf( '.' );
+        t1 = i == -1 ? "" : f1name.substring( i + 1 );
+        i = f2name.lastIndexOf( '.' );
+        t2 = i == -1 ? "" : f2name.substring( i + 1 );
+
+        i = t1.compareToIgnoreCase( t2 );
+        if( i == 0 ) {
+            return f1name.compareToIgnoreCase( f2name );
+        }
+        return i;
+    }
+    protected int compareDates( SmbFile f1, String f1name, SmbFile f2 ) throws IOException {
+        if( f1.isDirectory() != f2.isDirectory() ) {
+            return f1.isDirectory() ? -1 : 1;
+        }
+        if( f1.isDirectory() ) {
+            return f1name.compareToIgnoreCase( f2.getName() );
+        }
+        return f1.lastModified() > f2.lastModified() ? -1 : 1;
+    }
+    protected void doDirectory( HttpServletRequest req, HttpServletResponse resp, SmbFile dir ) throws IOException {
+        PrintWriter out;
+        SmbFile[] dirents;
+        SmbFile f;
+        int i, j, len, maxLen, dirCount, fileCount, sort;
+        String str, name, path, fmt;
+        LinkedList sorted;
+        ListIterator iter;
+        SimpleDateFormat sdf = new SimpleDateFormat( "MM/d/yy h:mm a" );
+        GregorianCalendar cal = new GregorianCalendar();
+
+        sdf.setCalendar( cal );
+
+        dirents = dir.listFiles();
+        sorted = new LinkedList();
+        if(( fmt = req.getParameter( "fmt" )) == null ) {
+            fmt = "col";
+        }
+        sort = 0;
+        if(( str = req.getParameter( "sort" )) == null || str.equals( "name" )) {
+            sort = 0;
+        } else if( str.equals( "size" )) {
+            sort = 1;
+        } else if( str.equals( "type" )) {
+            sort = 2;
+        } else if( str.equals( "date" )) {
+            sort = 3;
+        }
+        dirCount = fileCount = 0;
+        maxLen = 28;
+        for( i = 0; i < dirents.length; i++ ) {
+            try {
+                if( dirents[i].getType() == SmbFile.TYPE_NAMED_PIPE ) {
+                    continue;
+                }
+            } catch( SmbAuthException sae ) {
+            }
+            if( dirents[i].isDirectory() ) {
+                dirCount++;
+            } else {
+                fileCount++;
+            }
+
+            name = dirents[i].getName();
+            len = name.length(); 
+            if( len > maxLen ) {
+                maxLen = len;
+            }
+
+            iter = sorted.listIterator();
+            for( j = 0; iter.hasNext(); j++ ) {
+                if( sort == 0 ) {
+                    if( compareNames( dirents[i], name, (SmbFile)iter.next() ) < 0 ) {
+                        break;
+                    }
+                } else if( sort == 1 ) {
+                    if( compareSizes( dirents[i], name, (SmbFile)iter.next() ) < 0 ) {
+                        break;
+                    }
+                } else if( sort == 2 ) {
+                    if( compareTypes( dirents[i], name, (SmbFile)iter.next() ) < 0 ) {
+                        break;
+                    }
+                } else if( sort == 3 ) {
+                    if( compareDates( dirents[i], name, (SmbFile)iter.next() ) < 0 ) {
+                        break;
+                    }
+                }
+            }
+            sorted.add( j, dirents[i] );
+        }
+        if( maxLen > 50 ) {
+            maxLen = 50;
+        }
+        maxLen *= 9; /* convert to px */
+
+        out = resp.getWriter();
+
+        resp.setContentType( "text/html" );
+
+        out.println( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">" );
+        out.println( "<html><head><title>Network Explorer</title>" );
+        out.println( "<meta HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">" );
+        out.println( "<style TYPE=\"text/css\">" );
+
+        out.println( style );
+
+        if( dirents.length < 200 ) {
+            out.println( "    a:hover {" );
+            out.println( "        background: #a2ff01;" );
+            out.println( "    }" );
+        }
+
+        out.println( "</STYLE>" );
+        out.println( "</head><body>" );
+
+        out.print( "<a class=\"sort\" style=\"width: " + maxLen + ";\" href=\"?fmt=detail&sort=name\">Name</a>" );
+        out.println( "<a class=\"sort\" href=\"?fmt=detail&sort=size\">Size</a>" );
+        out.println( "<a class=\"sort\" href=\"?fmt=detail&sort=type\">Type</a>" );
+        out.println( "<a class=\"sort\" style=\"width: 180\" href=\"?fmt=detail&sort=date\">Modified</a><br clear='all'><p>" );
+
+        path = dir.getCanonicalPath();
+
+        if( path.length() < 7 ) {
+            out.println( "<b><big>smb://</big></b><br>" );
+            path = ".";
+        } else {
+            out.println( "<b><big>" + path + "</big></b><br>" );
+            path = "../";
+        }
+        out.println( (dirCount + fileCount) + " objects (" + dirCount + " directories, " + fileCount + " files)<br>" );
+        out.println( "<b><a class=\"plain\" href=\".\">normal</a> | <a class=\"plain\" href=\"?fmt=detail\">detailed</a></b>" );
+        out.println( "<p><table border='0' cellspacing='0' cellpadding='0'><tr><td>" );
+
+        out.print( "<A style=\"width: " + maxLen );
+        out.print( "; height: 18;\" HREF=\"" );
+        out.print( path );
+        out.println( "\"><b>&uarr;</b></a>" );
+        if( fmt.equals( "detail" )) {
+            out.println( "<br clear='all'>" );
+        }
+
+        if( path.length() == 1 || dir.getType() != SmbFile.TYPE_WORKGROUP ) {
+            path = "";
+        }
+
+        iter = sorted.listIterator();
+        while( iter.hasNext() ) {
+            f = (SmbFile)iter.next();
+            name = f.getName();
+
+            if( fmt.equals( "detail" )) {
+                out.print( "<A style=\"width: " + maxLen );
+                out.print( "; height: 18;\" HREF=\"" );
+                out.print( path );
+                out.print( name );
+
+                if( f.isDirectory() ) {
+                    out.print( "?fmt=detail\"><b>" );
+                    out.print( name );
+                    out.print( "</b></a>" );
+                } else {
+                    out.print( "\"><b>" );
+                    out.print( name );
+                    out.print( "</b></a><div align='right'>" );
+                    out.print( (f.length() / 1024) + " KB </div><div>" );
+                    i = name.lastIndexOf( '.' ) + 1;
+                    if( i > 1 && (name.length() - i) < 6 ) {
+                        out.print( name.substring( i ).toUpperCase() + "</div class='ext'>" );
+                    } else {
+                        out.print( "&nbsp;</div>" );
+                    }
+                    out.print( "<div style='width: 180'>" );
+                    out.print( sdf.format( new Date( f.lastModified() )));
+                    out.print( "</div>" );
+                }
+                out.println( "<br clear='all'>" );
+            } else {
+                out.print( "<A style=\"width: " + maxLen );
+                if( f.isDirectory() ) {
+                    out.print( "; height: 18;\" HREF=\"" );
+                    out.print( path );
+                    out.print( name );
+                    out.print( "\"><b>" );
+                    out.print( name );
+                    out.print( "</b></a>" );
+                } else {
+                    out.print( ";\" HREF=\"" );
+                    out.print( path );
+                    out.print( name );
+                    out.print( "\"><b>" );
+                    out.print( name );
+                    out.print( "</b><br><small>" );
+                    out.print( (f.length() / 1024) + "KB <br>" );
+                    out.print( sdf.format( new Date( f.lastModified() )));
+                    out.print( "</small>" );
+                    out.println( "</a>" );
+                }
+            }
+        }
+
+        out.println( "</td></tr></table>" );
+        out.println( "</BODY></HTML>" );
+        out.close();
+    }
+    private String parseServerAndShare( String pathInfo ) {
+        char[] out = new char[256];
+        char ch;
+        int len, p, i;
+
+        if( pathInfo == null ) {
+            return null;
+        }
+        len = pathInfo.length();
+
+        p = i = 0;
+        while( p < len && pathInfo.charAt( p ) == '/' ) {
+            p++;
+        }
+        if( p == len ) {
+            return null;
+        }
+        do {                                   /* collect server name */
+            out[i++] = (ch = pathInfo.charAt( p++ ));
+        } while( p < len && ch != '/' );
+        while( p < len && pathInfo.charAt( p ) == '/' ) {
+            p++;
+        }
+        if( p < len ) {                 /* then there must be a share */
+            out[i++] = '/';
+            do {                            /* collect the share name */
+                out[i++] = (ch = pathInfo.charAt( p++ ));
+            } while( p < len && ch != '/' );
+        }
+        return new String( out, 0, i );
+    }
+    public void doGet( HttpServletRequest req,
+                HttpServletResponse resp ) throws IOException, ServletException {
+        UniAddress dc;
+        String msg, pathInfo, server = null;
+        boolean offerBasic, possibleWorkgroup = true;
+        NtlmPasswordAuthentication ntlm = null;
+        HttpSession ssn = req.getSession( false );
+
+        if(( pathInfo = req.getPathInfo() ) != null ) {
+            int i;
+            server = parseServerAndShare( pathInfo );
+            if( server != null && ( i = server.indexOf( '/' )) > 0 ) {
+                server = server.substring( 0, i ).toLowerCase();
+                possibleWorkgroup = false;
+            } 
+        }
+
+        msg = req.getHeader( "Authorization" );
+        offerBasic = enableBasic && (insecureBasic || req.isSecure());
+
+        if( msg != null && (msg.startsWith( "NTLM " ) || (offerBasic && msg.startsWith("Basic ")))) {
+
+            if( msg.startsWith("NTLM ")) {
+                byte[] challenge;
+
+                if( pathInfo == null || server == null ) {
+                    String mb = NbtAddress.getByName( NbtAddress.MASTER_BROWSER_NAME, 0x01, null ).getHostAddress();
+                    dc = UniAddress.getByName( mb );
+                } else {
+                    dc = UniAddress.getByName( server, possibleWorkgroup );
+                }
+
+                req.getSession();
+                challenge = SmbSession.getChallenge( dc );
+                if(( ntlm = NtlmSsp.authenticate( req, resp, challenge )) == null ) {
+                    return;
+                }
+            } else {
+                String auth = new String( Base64.decode( msg.substring(6) ), "US-ASCII" );
+                int index = auth.indexOf( ':' );
+                String user = (index != -1) ? auth.substring(0, index) : auth;
+                String password = (index != -1) ? auth.substring(index + 1) : "";
+                index = user.indexOf('\\');
+                if (index == -1) index = user.indexOf('/');
+                String domain = (index != -1) ? user.substring(0, index) : defaultDomain;
+                user = (index != -1) ? user.substring(index + 1) : user;
+                ntlm = new NtlmPasswordAuthentication(domain, user, password);
+            }
+
+            req.getSession().setAttribute( "npa-" + server, ntlm );
+
+        } else if( !credentialsSupplied ) {
+            if( ssn != null ) {
+                ntlm = (NtlmPasswordAuthentication)ssn.getAttribute( "npa-" + server );
+            }
+            if( ntlm == null ) {
+                resp.setHeader( "WWW-Authenticate", "NTLM" );
+                if (offerBasic) {
+                    resp.addHeader( "WWW-Authenticate", "Basic realm=\"" + realm + "\"");
+                }
+                resp.setHeader( "Connection", "close" );
+                resp.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
+                resp.flushBuffer();
+                return;
+            }
+        }
+
+        try {
+            SmbFile file;
+
+            if( ntlm != null ) {
+                file = new SmbFile( "smb:/" + pathInfo , ntlm );
+            } else if( server == null ) {
+                file = new SmbFile( "smb://" );
+            } else {
+                file = new SmbFile( "smb:/" + pathInfo );
+            }
+
+            if( file.isDirectory() ) {
+                doDirectory( req, resp, file );
+            } else {
+                doFile( req, resp, file );
+            }
+        } catch( SmbAuthException sae ) {
+            if( ssn != null ) {
+                ssn.removeAttribute( "npa-" + server );
+            }
+            resp.setHeader( "WWW-Authenticate", "NTLM" );
+            if (offerBasic) {
+                resp.addHeader( "WWW-Authenticate", "Basic realm=\"" + realm + "\"");
+            }
+            resp.setHeader( "Connection", "close" );
+            resp.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
+            resp.flushBuffer();
+            return;
+        } catch( DfsReferral dr ) {
+            StringBuffer redir = req.getRequestURL();
+            String qs = req.getQueryString();
 if( true ) {
-       throw new RuntimeException( "DFS referrals with NetworkExplorer are currently disabled because they can lead to account lockout." );
+    throw new RuntimeException( "DFS referrals with NetworkExplorer are currently disabled because they can lead to account lockout." );
 }
-                       redir = new StringBuffer( redir.substring( 0, redir.length() - req.getPathInfo().length() ));
-                       redir.append( dr.node.replace( '\\', '/' ));
-                       redir.append( '/' );
-                       if( qs != null ) {
-                               redir.append( req.getQueryString() );
-                       }
-                       resp.sendRedirect( redir.toString() );
-                       resp.flushBuffer();
-                       return;
-               }
-       }
+            redir = new StringBuffer( redir.substring( 0, redir.length() - req.getPathInfo().length() ));
+            redir.append( dr.node.replace( '\\', '/' ));
+            redir.append( '/' );
+            if( qs != null ) {
+                redir.append( req.getQueryString() );
+            }
+            resp.sendRedirect( redir.toString() );
+            resp.flushBuffer();
+            return;
+        }
+    }
 }
 
index 3cbff62..fc6b940 100644 (file)
@@ -1,8 +1,8 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                      "Jason Pugsley" <jcifs at samba dot org>
- *                                      "skeetz" <jcifs at samba dot org>
- *                                      "Eric Glass" <jcifs at samba dot org>
+ *                   "Jason Pugsley" <jcifs at samba dot org>
+ *                   "skeetz" <jcifs at samba dot org>
+ *                   "Eric Glass" <jcifs at samba dot org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -44,131 +44,132 @@ import jcifs.netbios.NbtAddress;
 
 public class NtlmHttpFilter implements Filter {
 
-       private String defaultDomain;
-
-       private String domainController;
-
-       private boolean loadBalance;
-
-       private boolean enableBasic;
-
-       private boolean insecureBasic;
-
-       private String realm;
-
-       public void init( FilterConfig filterConfig ) throws ServletException {
-               String name;
-
-               /* Set jcifs properties we know we want; soTimeout and cachePolicy to 10min.
-                */
-               Config.setProperty( "jcifs.smb.client.soTimeout", "300000" );
-               Config.setProperty( "jcifs.netbios.cachePolicy", "600" );
-
-               Enumeration e = filterConfig.getInitParameterNames();
-               while( e.hasMoreElements() ) {
-                       name = (String)e.nextElement();
-                       if( name.startsWith( "jcifs." )) {
-                               Config.setProperty( name, filterConfig.getInitParameter( name ));
-                       }
-               }
-               defaultDomain = Config.getProperty("jcifs.smb.client.domain");
-               domainController = Config.getProperty( "jcifs.http.domainController" );
-               if( domainController == null ) {
-                       domainController = defaultDomain;
-                       loadBalance = Config.getBoolean( "jcifs.http.loadBalance", true );
-               }
-               enableBasic = Boolean.valueOf(
-                               Config.getProperty("jcifs.http.enableBasic")).booleanValue();
-               insecureBasic = Boolean.valueOf(
-                               Config.getProperty("jcifs.http.insecureBasic")).booleanValue();
-               realm = Config.getProperty("jcifs.http.basicRealm");
-               if (realm == null) realm = "jCIFS";
-       }
-       public void destroy() {
-       }
-       public void doFilter( ServletRequest request,
-                               ServletResponse response,
-                               FilterChain chain ) throws IOException, ServletException {
-               HttpServletRequest req;
-               HttpServletResponse resp;
-               UniAddress dc;
-               String msg;
-
-               NtlmPasswordAuthentication ntlm = null;
-               req = (HttpServletRequest)request;
-               resp = (HttpServletResponse)response;
-               msg = req.getHeader( "Authorization" );
-               boolean offerBasic = enableBasic && (insecureBasic || req.isSecure());
-
-               if( msg != null && (msg.startsWith( "NTLM " ) ||
-                                       (offerBasic && msg.startsWith("Basic ")))) {
-                       if( loadBalance ) {
-                               dc = new UniAddress( NbtAddress.getByName( domainController, 0x1C, null ));
-                       } else {
-                               dc = UniAddress.getByName( domainController, true );
-                       }
-                       if (msg.startsWith("NTLM ")) {
-                               byte[] challenge = SmbSession.getChallenge( dc );
-                               if(( ntlm = NtlmSsp.authenticate( req, resp, challenge )) == null ) {
-                                       return;
-                               }
-                       } else {
-                               String auth = new String(Base64.decode(msg.substring(6)),
-                                               "US-ASCII");
-                               int index = auth.indexOf(':');
-                               String user = (index != -1) ? auth.substring(0, index) : auth;
-                               String password = (index != -1) ? auth.substring(index + 1) :
-                                               "";
-                               index = user.indexOf('\\');
-                               if (index == -1) index = user.indexOf('/');
-                               String domain = (index != -1) ? user.substring(0, index) :
-                                               defaultDomain;
-                               user = (index != -1) ? user.substring(index + 1) : user;
-                               ntlm = new NtlmPasswordAuthentication(domain, user, password);
-                       }
-                       try {
-                               SmbSession.logon( dc, ntlm );
-                       } catch( SmbAuthException sae ) {
-                               resp.setHeader( "WWW-Authenticate", "NTLM" );
-                               if (offerBasic) {
-                                       resp.addHeader( "WWW-Authenticate", "Basic realm=\"" +
-                                                       realm + "\"");
-                               }
-                               resp.setHeader( "Connection", "close" );
-                               resp.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
-                               resp.flushBuffer();
-                               return;
-                       }
-                       req.getSession().setAttribute( "NtlmHttpAuth", ntlm );
-               } else {
-                       HttpSession ssn = req.getSession(false);
-                       if (ssn == null || (ntlm = (NtlmPasswordAuthentication)
-                                       ssn.getAttribute("NtlmHttpAuth")) == null) {
-                               resp.setHeader( "WWW-Authenticate", "NTLM" );
-                               if (offerBasic) {
-                                       resp.addHeader( "WWW-Authenticate", "Basic realm=\"" +
-                                                       realm + "\"");
-                               }
-                               resp.setHeader( "Connection", "close" );
-                               resp.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
-                               resp.flushBuffer();
-                               return;
-                       }
-               }
-
-               chain.doFilter( new NtlmHttpServletRequest( req, ntlm ), response );
-       }
-
-       // Added by cgross to work with weblogic 6.1.
-       public void setFilterConfig( FilterConfig f ) {
-               try {
-                       init( f );
-               } catch( Exception e ) {
-                       e.printStackTrace();
-               }
-       }
-       public FilterConfig getFilterConfig() {
-               return null;
-       }
+    private String defaultDomain;
+
+    private String domainController;
+
+    private boolean loadBalance;
+
+    private boolean enableBasic;
+
+    private boolean insecureBasic;
+
+    private String realm;
+
+    public void init( FilterConfig filterConfig ) throws ServletException {
+        String name;
+
+        /* Set jcifs properties we know we want; soTimeout and cachePolicy to 10min.
+         */
+        Config.setProperty( "jcifs.smb.client.soTimeout", "300000" );
+        Config.setProperty( "jcifs.netbios.cachePolicy", "600" );
+
+        Enumeration e = filterConfig.getInitParameterNames();
+        while( e.hasMoreElements() ) {
+            name = (String)e.nextElement();
+            if( name.startsWith( "jcifs." )) {
+                Config.setProperty( name, filterConfig.getInitParameter( name ));
+            }
+        }
+        defaultDomain = Config.getProperty("jcifs.smb.client.domain");
+        domainController = Config.getProperty( "jcifs.http.domainController" );
+        if( domainController == null ) {
+            domainController = defaultDomain;
+            loadBalance = Config.getBoolean( "jcifs.http.loadBalance", true );
+        }
+        enableBasic = Boolean.valueOf(
+                Config.getProperty("jcifs.http.enableBasic")).booleanValue();
+        insecureBasic = Boolean.valueOf(
+                Config.getProperty("jcifs.http.insecureBasic")).booleanValue();
+        realm = Config.getProperty("jcifs.http.basicRealm");
+        if (realm == null) realm = "jCIFS";
+    }
+    public void destroy() {
+    }
+    public void doFilter( ServletRequest request,
+                ServletResponse response,
+                FilterChain chain ) throws IOException, ServletException {
+        HttpServletRequest req;
+        HttpServletResponse resp;
+        UniAddress dc;
+        String msg;
+
+        NtlmPasswordAuthentication ntlm = null;
+        req = (HttpServletRequest)request;
+        resp = (HttpServletResponse)response;
+        msg = req.getHeader( "Authorization" );
+        boolean offerBasic = enableBasic && (insecureBasic || req.isSecure());
+
+        if( msg != null && (msg.startsWith( "NTLM " ) ||
+                    (offerBasic && msg.startsWith("Basic ")))) {
+            if( loadBalance ) {
+                dc = new UniAddress( NbtAddress.getByName( domainController, 0x1C, null ));
+            } else {
+                dc = UniAddress.getByName( domainController, true );
+            }
+            if (msg.startsWith("NTLM ")) {
+                req.getSession();
+                byte[] challenge = SmbSession.getChallenge( dc );
+                if(( ntlm = NtlmSsp.authenticate( req, resp, challenge )) == null ) {
+                    return;
+                }
+            } else {
+                String auth = new String(Base64.decode(msg.substring(6)),
+                        "US-ASCII");
+                int index = auth.indexOf(':');
+                String user = (index != -1) ? auth.substring(0, index) : auth;
+                String password = (index != -1) ? auth.substring(index + 1) :
+                        "";
+                index = user.indexOf('\\');
+                if (index == -1) index = user.indexOf('/');
+                String domain = (index != -1) ? user.substring(0, index) :
+                        defaultDomain;
+                user = (index != -1) ? user.substring(index + 1) : user;
+                ntlm = new NtlmPasswordAuthentication(domain, user, password);
+            }
+            try {
+                SmbSession.logon( dc, ntlm );
+            } catch( SmbAuthException sae ) {
+                resp.setHeader( "WWW-Authenticate", "NTLM" );
+                if (offerBasic) {
+                    resp.addHeader( "WWW-Authenticate", "Basic realm=\"" +
+                            realm + "\"");
+                }
+                resp.setHeader( "Connection", "close" );
+                resp.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
+                resp.flushBuffer();
+                return;
+            }
+            req.getSession().setAttribute( "NtlmHttpAuth", ntlm );
+        } else {
+            HttpSession ssn = req.getSession(false);
+            if (ssn == null || (ntlm = (NtlmPasswordAuthentication)
+                    ssn.getAttribute("NtlmHttpAuth")) == null) {
+                resp.setHeader( "WWW-Authenticate", "NTLM" );
+                if (offerBasic) {
+                    resp.addHeader( "WWW-Authenticate", "Basic realm=\"" +
+                            realm + "\"");
+                }
+                resp.setHeader( "Connection", "close" );
+                resp.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
+                resp.flushBuffer();
+                return;
+            }
+        }
+
+        chain.doFilter( new NtlmHttpServletRequest( req, ntlm ), response );
+    }
+
+    // Added by cgross to work with weblogic 6.1.
+    public void setFilterConfig( FilterConfig f ) {
+        try {
+            init( f );
+        } catch( Exception e ) {
+            e.printStackTrace();
+        }
+    }
+    public FilterConfig getFilterConfig() {
+        return null;
+    }
 }
 
index 47629a9..3aadc45 100644 (file)
@@ -1,6 +1,6 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                      "Eric Glass" <jcifs at samba dot org>
+ *                   "Eric Glass" <jcifs at samba dot org>
  * 
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -25,20 +25,20 @@ import javax.servlet.http.HttpServletRequestWrapper;
 
 class NtlmHttpServletRequest extends HttpServletRequestWrapper {
 
-       Principal principal;
+    Principal principal;
 
-       NtlmHttpServletRequest( HttpServletRequest req, Principal principal ) {
-               super( req );
-               this.principal = principal;
-       }
-       public String getRemoteUser() {
-               return principal.getName();
-       }
-       public Principal getUserPrincipal() {
-               return principal;
-       }
-       public String getAuthType() {
-               return "NTLM";
-       }
+    NtlmHttpServletRequest( HttpServletRequest req, Principal principal ) {
+        super( req );
+        this.principal = principal;
+    }
+    public String getRemoteUser() {
+        return principal.getName();
+    }
+    public Principal getUserPrincipal() {
+        return principal;
+    }
+    public String getAuthType() {
+        return "NTLM";
+    }
 }
 
index 5dd30f4..83bf518 100644 (file)
@@ -1,6 +1,6 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                      "Eric Glass" <jcifs at samba dot org>
+ *                   "Eric Glass" <jcifs at samba dot org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -57,507 +57,507 @@ import jcifs.util.Base64;
  */
 public class NtlmHttpURLConnection extends HttpURLConnection {
 
-       private static final int MAX_REDIRECTS =
-                       Integer.parseInt(System.getProperty("http.maxRedirects", "20"));
-
-       private static final int LM_COMPATIBILITY =
-                       Config.getInt("jcifs.smb.lmCompatibility", 0);
-
-       private static final String DEFAULT_DOMAIN;
-
-       private HttpURLConnection connection;
-
-       private Map requestProperties;
-
-       private Map headerFields;
-
-       private String authProperty;
-
-       private String method;
-
-       static {
-               String domain = System.getProperty("http.auth.ntlm.domain");
-               if (domain == null) domain = Type3Message.getDefaultDomain();
-               DEFAULT_DOMAIN = domain;
-       }
-
-       public NtlmHttpURLConnection(HttpURLConnection connection) {
-               super(connection.getURL());
-               this.connection = connection;
-               requestProperties = new HashMap();
-       }
-
-       public void connect() throws IOException {
-               if (connected) return;
-               doConnect();
-               connected = true;
-       }
-
-       public URL getURL() {
-               return connection.getURL();
-       }
-
-       public int getContentLength() {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getContentLength();
-       }
-
-       public String getContentType() {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getContentType();
-       }
-
-       public String getContentEncoding() {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getContentEncoding();
-       }
-
-       public long getExpiration() {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getExpiration();
-       }
-
-       public long getDate() {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getDate();
-       }
-
-       public long getLastModified() {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getLastModified();
-       }
-
-       public String getHeaderField(String header) {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getHeaderField(header);
-       }
-
-       private synchronized Map getHeaderFields0() {
-               if (headerFields != null) return headerFields;
-               Map map = new HashMap();
-               String key = connection.getHeaderFieldKey(0);
-               String value = connection.getHeaderField(0);
-               for (int i = 1; key != null || value != null; i++) {
-                       List values = (List) map.get(key);
-                       if (values == null) {
-                               values = new ArrayList();
-                               map.put(key, values);
-                       }
-                       values.add(value);
-                       key = connection.getHeaderFieldKey(i);
-                       value = connection.getHeaderField(i);
-               }
-               Iterator entries = map.entrySet().iterator();
-               while (entries.hasNext()) {
-                       Map.Entry entry = (Map.Entry) entries.next();
-                       entry.setValue(Collections.unmodifiableList((List)
-                                       entry.getValue()));
-               }
-               return (headerFields = Collections.unmodifiableMap(map));
-       }
-
-       public Map getHeaderFields() {
-               synchronized (this) {
-                       if (headerFields != null) return headerFields;
-               }
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return getHeaderFields0();
-       }
-
-       public int getHeaderFieldInt(String header, int def) {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getHeaderFieldInt(header, def);
-       }
-
-       public long getHeaderFieldDate(String header, long def) {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getHeaderFieldDate(header, def);
-       }
-
-       public String getHeaderFieldKey(int index) {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getHeaderFieldKey(index);
-       }
-
-       public String getHeaderField(int index) {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getHeaderField(index);
-       }
-
-       public Object getContent() throws IOException {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getContent();
-       }
-
-       public Object getContent(Class[] classes) throws IOException {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getContent(classes);
-       }
-
-       public Permission getPermission() throws IOException {
-               return connection.getPermission();
-       }
-
-       public InputStream getInputStream() throws IOException {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getInputStream();
-       }
-
-       public OutputStream getOutputStream() throws IOException {
-               try {
-                       connect();
-               } catch (IOException ex) { }
-               return connection.getOutputStream();
-       }
-
-       public String toString() {
-               return connection.toString();
-       }
-
-       public void setDoInput(boolean doInput) {
-               connection.setDoInput(doInput);
-               this.doInput = doInput;
-       }
-
-       public boolean getDoInput() {
-               return connection.getDoInput();
-       }
-
-       public void setDoOutput(boolean doOutput) {
-               connection.setDoOutput(doOutput);
-               this.doOutput = doOutput;
-       }
-
-       public boolean getDoOutput() {
-               return connection.getDoOutput();
-       }
-
-       public void setAllowUserInteraction(boolean allowUserInteraction) {
-               connection.setAllowUserInteraction(allowUserInteraction);
-               this.allowUserInteraction = allowUserInteraction;
-       }
-
-       public boolean getAllowUserInteraction() {
-               return connection.getAllowUserInteraction();
-       }
-
-       public void setUseCaches(boolean useCaches) {
-               connection.setUseCaches(useCaches);
-               this.useCaches = useCaches;
-       }
-
-       public boolean getUseCaches() {
-               return connection.getUseCaches();
-       }
-
-       public void setIfModifiedSince(long ifModifiedSince) {
-               connection.setIfModifiedSince(ifModifiedSince);
-               this.ifModifiedSince = ifModifiedSince;
-       }
-
-       public long getIfModifiedSince() {
-               return connection.getIfModifiedSince();
-       }
-
-       public boolean getDefaultUseCaches() {
-               return connection.getDefaultUseCaches();
-       }
-
-       public void setDefaultUseCaches(boolean defaultUseCaches) {
-               connection.setDefaultUseCaches(defaultUseCaches);
-       }
-
-       public void setRequestProperty(String key, String value) {
-               if (key == null) throw new NullPointerException();
-               List values = new ArrayList();
-               values.add(value);
-               boolean found = false;
-               synchronized (requestProperties) {
-                       Iterator entries = requestProperties.entrySet().iterator();
-                       while (entries.hasNext()) {
-                               Map.Entry entry = (Map.Entry) entries.next();
-                               if (key.equalsIgnoreCase((String) entry.getKey())) {
-                                       entry.setValue(value);
-                                       found = true;
-                                       break;
-                               }
-                       }
-                       if (!found) requestProperties.put(key, values);
-               }
-               connection.setRequestProperty(key, value);
-       }
-
-       public void addRequestProperty(String key, String value) {
-               if (key == null) throw new NullPointerException();
-               List values = null;
-               synchronized (requestProperties) {
-                       Iterator entries = requestProperties.entrySet().iterator();
-                       while (entries.hasNext()) {
-                               Map.Entry entry = (Map.Entry) entries.next();
-                               if (key.equalsIgnoreCase((String) entry.getKey())) {
-                                       values = (List) entry.getValue();
-                                       values.add(value);
-                                       break;
-                               }
-                       }
-                       if (values == null) {
-                               values = new ArrayList();
-                               values.add(value);
-                               requestProperties.put(key, values);
-                       }
-               }
-               // 1.3-compatible.
-               StringBuffer buffer = new StringBuffer();
-               Iterator propertyValues = values.iterator();
-               while (propertyValues.hasNext()) {
-                       buffer.append(propertyValues.next());
-                       if (propertyValues.hasNext()) {
-                               buffer.append(", ");
-                       }
-               }
-               connection.setRequestProperty(key, buffer.toString());
-       }
-
-       public String getRequestProperty(String key) {
-               return connection.getRequestProperty(key);
-       }
-
-       public Map getRequestProperties() {
-               Map map = new HashMap();
-               synchronized (requestProperties) {
-                       Iterator entries = requestProperties.entrySet().iterator();
-                       while (entries.hasNext()) {
-                               Map.Entry entry = (Map.Entry) entries.next();
-                               map.put(entry.getKey(),
-                                               Collections.unmodifiableList((List) entry.getValue()));
-                       }
-               }
-               return Collections.unmodifiableMap(map);
-       }
-
-       public void setInstanceFollowRedirects(boolean instanceFollowRedirects) {
-               connection.setInstanceFollowRedirects(instanceFollowRedirects);
-       }
-
-       public boolean getInstanceFollowRedirects() {
-               return connection.getInstanceFollowRedirects();
-       }
-
-       public void setRequestMethod(String requestMethod)
-                       throws ProtocolException {
-               connection.setRequestMethod(requestMethod);
-       }
-
-       public String getRequestMethod() {
-               return connection.getRequestMethod();
-       }
-
-       public int getResponseCode() throws IOException {
-               return connection.getResponseCode();
-       }
-
-       public String getResponseMessage() throws IOException {
-               return connection.getResponseMessage();
-       }
-
-       public void disconnect() {
-               connection.disconnect();
-               connected = false;
-       }
-
-       public boolean usingProxy() {
-               return connection.usingProxy();
-       }
-
-       public InputStream getErrorStream() {
-               return connection.getErrorStream();
-       }
-
-       private int parseResponseCode() throws IOException {
-               try {
-                       String response = connection.getHeaderField(0);
-                       int index = response.indexOf(' ');
-                       while (response.charAt(index) == ' ') index++;
-                       return Integer.parseInt(response.substring(index, index + 3));
-               } catch (Exception ex) {
-                       throw new IOException(ex.getMessage());
-               }
-       }
-
-       private synchronized void doConnect() throws IOException {
-               connection.connect();
-               int response = parseResponseCode();
-               if (response != HTTP_UNAUTHORIZED && response != HTTP_PROXY_AUTH) {
-                       return;
-               }
-               Type1Message type1 = (Type1Message) attemptNegotiation(response);
-               if (type1 == null) return; // no NTLM
-               int attempt = 0;
-               while (attempt < MAX_REDIRECTS) {
-                       connection.setRequestProperty(authProperty, method + ' ' +
-                                       Base64.encode(type1.toByteArray()));
-                       connection.connect(); // send type 1
-                       response = parseResponseCode();
-                       if (response != HTTP_UNAUTHORIZED && response != HTTP_PROXY_AUTH) {
-                               return;
-                       }
-                       Type3Message type3 = (Type3Message) attemptNegotiation(response);
-                       if (type3 == null) return;
-                       connection.setRequestProperty(authProperty, method + ' ' +
-                                       Base64.encode(type3.toByteArray()));
-                       connection.connect(); // send type 3
-                       response = parseResponseCode();
-                       if (response != HTTP_UNAUTHORIZED && response != HTTP_PROXY_AUTH) {
-                               return;
-                       }
-                       attempt++;
-                       if (attempt < MAX_REDIRECTS) reconnect();
-               }
-               throw new IOException("Unable to negotiate NTLM authentication.");
-       }
-
-       private NtlmMessage attemptNegotiation(int response) throws IOException {
-               authProperty = null;
-               method = null;
-               InputStream errorStream = connection.getErrorStream();
-               if (errorStream != null && errorStream.available() != 0) {
-                       int count;
-                       byte[] buf = new byte[1024];
-                       while ((count = errorStream.read(buf, 0, 1024)) != -1);
-               }
-               String authHeader;
-               if (response == HTTP_UNAUTHORIZED) {
-                       authHeader = "WWW-Authenticate";
-                       authProperty = "Authorization";
-               } else {
-                       authHeader = "Proxy-Authenticate";
-                       authProperty = "Proxy-Authorization";
-               }
-               String authorization = null;
-               List methods = (List) getHeaderFields0().get(authHeader);
-               if (methods == null) return null;
-               Iterator iterator = methods.iterator();
-               while (iterator.hasNext()) {
-                       String authMethod = (String) iterator.next();
-                       if (authMethod.startsWith("NTLM")) {
-                               if (authMethod.length() == 4) {
-                                       method = "NTLM";
-                                       break;
-                               }
-                               if (authMethod.indexOf(' ') != 4) continue;
-                               method = "NTLM";
-                               authorization = authMethod.substring(5).trim();
-                               break;
-                       } else if (authMethod.startsWith("Negotiate")) {
-                               if (authMethod.length() == 9) {
-                                       method = "Negotiate";
-                                       break;
-                               }
-                               if (authMethod.indexOf(' ') != 9) continue;
-                               method = "Negotiate";
-                               authorization = authMethod.substring(10).trim();
-                               break;
-                       }
-               }
-               if (method == null) return null;
-               NtlmMessage message = (authorization != null) ?
-                               new Type2Message(Base64.decode(authorization)) : null;
-               reconnect();
-               if (message == null) {
-                       message = new Type1Message();
-                       if (LM_COMPATIBILITY > 2) {
-                               message.setFlag(NtlmFlags.NTLMSSP_REQUEST_TARGET, true);
-                       }
-               } else {
-                       String domain = DEFAULT_DOMAIN;
-                       String user = Type3Message.getDefaultUser();
-                       String password = Type3Message.getDefaultPassword();
-                       String userInfo = url.getUserInfo();
-                       if (userInfo != null) {
-                               userInfo = URLDecoder.decode(userInfo);
-                               int index = userInfo.indexOf(':');
-                               user = (index != -1) ? userInfo.substring(0, index) : userInfo;
-                               if (index != -1) password = userInfo.substring(index + 1);
-                               index = user.indexOf('\\');
-                               if (index == -1) index = user.indexOf('/');
-                               domain = (index != -1) ? user.substring(0, index) : domain;
-                               user = (index != -1) ? user.substring(index + 1) : user;
-                       }
-                       if (user == null) {
-                               try {
-                                       URL url = getURL();
-                                       String protocol = url.getProtocol();
-                                       int port = url.getPort();
-                                       if (port == -1) {
-                                               port = "https".equalsIgnoreCase(protocol) ? 443 : 80;
-                                       }
-                                       PasswordAuthentication auth =
-                                                       Authenticator.requestPasswordAuthentication(null,
-                                                                       port, protocol, "", method);
-                                       if (auth != null) {
-                                               user = auth.getUserName();
-                                               password = new String(auth.getPassword());
-                                       }
-                               } catch (Exception ex) { }
-                       }
-                       Type2Message type2 = (Type2Message) message;
-                       message = new Type3Message(type2, password, domain, user,
-                                       Type3Message.getDefaultWorkstation());
-               }
-               return message;
-       }
-
-       private void reconnect() throws IOException {
-               connection = (HttpURLConnection) connection.getURL().openConnection();
-               headerFields = null;
-               synchronized (requestProperties) {
-                       Iterator properties = requestProperties.entrySet().iterator();
-                       while (properties.hasNext()) {
-                               Map.Entry property = (Map.Entry) properties.next();
-                               String key = (String) property.getKey();
-                               StringBuffer value = new StringBuffer();
-                               Iterator values = ((List) property.getValue()).iterator();
-                               while (values.hasNext()) {
-                                       value.append(values.next());
-                                       if (values.hasNext()) value.append(", ");
-                               }
-                               connection.setRequestProperty(key, value.toString());
-                       }
-               }
-               connection.setAllowUserInteraction(allowUserInteraction);
-               connection.setDoInput(doInput);
-               connection.setDoOutput(doOutput);
-               connection.setIfModifiedSince(ifModifiedSince);
-               connection.setUseCaches(useCaches);
-       }
+    private static final int MAX_REDIRECTS =
+            Integer.parseInt(System.getProperty("http.maxRedirects", "20"));
+
+    private static final int LM_COMPATIBILITY =
+            Config.getInt("jcifs.smb.lmCompatibility", 0);
+
+    private static final String DEFAULT_DOMAIN;
+
+    private HttpURLConnection connection;
+
+    private Map requestProperties;
+
+    private Map headerFields;
+
+    private String authProperty;
+
+    private String method;
+
+    static {
+        String domain = System.getProperty("http.auth.ntlm.domain");
+        if (domain == null) domain = Type3Message.getDefaultDomain();
+        DEFAULT_DOMAIN = domain;
+    }
+
+    public NtlmHttpURLConnection(HttpURLConnection connection) {
+        super(connection.getURL());
+        this.connection = connection;
+        requestProperties = new HashMap();
+    }
+
+    public void connect() throws IOException {
+        if (connected) return;
+        doConnect();
+        connected = true;
+    }
+
+    public URL getURL() {
+        return connection.getURL();
+    }
+
+    public int getContentLength() {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getContentLength();
+    }
+
+    public String getContentType() {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getContentType();
+    }
+
+    public String getContentEncoding() {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getContentEncoding();
+    }
+
+    public long getExpiration() {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getExpiration();
+    }
+
+    public long getDate() {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getDate();
+    }
+
+    public long getLastModified() {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getLastModified();
+    }
+
+    public String getHeaderField(String header) {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getHeaderField(header);
+    }
+
+    private synchronized Map getHeaderFields0() {
+        if (headerFields != null) return headerFields;
+        Map map = new HashMap();
+        String key = connection.getHeaderFieldKey(0);
+        String value = connection.getHeaderField(0);
+        for (int i = 1; key != null || value != null; i++) {
+            List values = (List) map.get(key);
+            if (values == null) {
+                values = new ArrayList();
+                map.put(key, values);
+            }
+            values.add(value);
+            key = connection.getHeaderFieldKey(i);
+            value = connection.getHeaderField(i);
+        }
+        Iterator entries = map.entrySet().iterator();
+        while (entries.hasNext()) {
+            Map.Entry entry = (Map.Entry) entries.next();
+            entry.setValue(Collections.unmodifiableList((List)
+                    entry.getValue()));
+        }
+        return (headerFields = Collections.unmodifiableMap(map));
+    }
+
+    public Map getHeaderFields() {
+        synchronized (this) {
+            if (headerFields != null) return headerFields;
+        }
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return getHeaderFields0();
+    }
+
+    public int getHeaderFieldInt(String header, int def) {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getHeaderFieldInt(header, def);
+    }
+
+    public long getHeaderFieldDate(String header, long def) {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getHeaderFieldDate(header, def);
+    }
+
+    public String getHeaderFieldKey(int index) {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getHeaderFieldKey(index);
+    }
+
+    public String getHeaderField(int index) {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getHeaderField(index);
+    }
+
+    public Object getContent() throws IOException {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getContent();
+    }
+
+    public Object getContent(Class[] classes) throws IOException {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getContent(classes);
+    }
+
+    public Permission getPermission() throws IOException {
+        return connection.getPermission();
+    }
+
+    public InputStream getInputStream() throws IOException {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getInputStream();
+    }
+
+    public OutputStream getOutputStream() throws IOException {
+        try {
+            connect();
+        } catch (IOException ex) { }
+        return connection.getOutputStream();
+    }
+
+    public String toString() {
+        return connection.toString();
+    }
+
+    public void setDoInput(boolean doInput) {
+        connection.setDoInput(doInput);
+        this.doInput = doInput;
+    }
+
+    public boolean getDoInput() {
+        return connection.getDoInput();
+    }
+
+    public void setDoOutput(boolean doOutput) {
+        connection.setDoOutput(doOutput);
+        this.doOutput = doOutput;
+    }
+
+    public boolean getDoOutput() {
+        return connection.getDoOutput();
+    }
+
+    public void setAllowUserInteraction(boolean allowUserInteraction) {
+        connection.setAllowUserInteraction(allowUserInteraction);
+        this.allowUserInteraction = allowUserInteraction;
+    }
+
+    public boolean getAllowUserInteraction() {
+        return connection.getAllowUserInteraction();
+    }
+
+    public void setUseCaches(boolean useCaches) {
+        connection.setUseCaches(useCaches);
+        this.useCaches = useCaches;
+    }
+
+    public boolean getUseCaches() {
+        return connection.getUseCaches();
+    }
+
+    public void setIfModifiedSince(long ifModifiedSince) {
+        connection.setIfModifiedSince(ifModifiedSince);
+        this.ifModifiedSince = ifModifiedSince;
+    }
+
+    public long getIfModifiedSince() {
+        return connection.getIfModifiedSince();
+    }
+
+    public boolean getDefaultUseCaches() {
+        return connection.getDefaultUseCaches();
+    }
+
+    public void setDefaultUseCaches(boolean defaultUseCaches) {
+        connection.setDefaultUseCaches(defaultUseCaches);
+    }
+
+    public void setRequestProperty(String key, String value) {
+        if (key == null) throw new NullPointerException();
+        List values = new ArrayList();
+        values.add(value);
+        boolean found = false;
+        synchronized (requestProperties) {
+            Iterator entries = requestProperties.entrySet().iterator();
+            while (entries.hasNext()) {
+                Map.Entry entry = (Map.Entry) entries.next();
+                if (key.equalsIgnoreCase((String) entry.getKey())) {
+                    entry.setValue(value);
+                    found = true;
+                    break;
+                }
+            }
+            if (!found) requestProperties.put(key, values);
+        }
+        connection.setRequestProperty(key, value);
+    }
+
+    public void addRequestProperty(String key, String value) {
+        if (key == null) throw new NullPointerException();
+        List values = null;
+        synchronized (requestProperties) {
+            Iterator entries = requestProperties.entrySet().iterator();
+            while (entries.hasNext()) {
+                Map.Entry entry = (Map.Entry) entries.next();
+                if (key.equalsIgnoreCase((String) entry.getKey())) {
+                    values = (List) entry.getValue();
+                    values.add(value);
+                    break;
+                }
+            }
+            if (values == null) {
+                values = new ArrayList();
+                values.add(value);
+                requestProperties.put(key, values);
+            }
+        }
+        // 1.3-compatible.
+        StringBuffer buffer = new StringBuffer();
+        Iterator propertyValues = values.iterator();
+        while (propertyValues.hasNext()) {
+            buffer.append(propertyValues.next());
+            if (propertyValues.hasNext()) {
+                buffer.append(", ");
+            }
+        }
+        connection.setRequestProperty(key, buffer.toString());
+    }
+
+    public String getRequestProperty(String key) {
+        return connection.getRequestProperty(key);
+    }
+
+    public Map getRequestProperties() {
+        Map map = new HashMap();
+        synchronized (requestProperties) {
+            Iterator entries = requestProperties.entrySet().iterator();
+            while (entries.hasNext()) {
+                Map.Entry entry = (Map.Entry) entries.next();
+                map.put(entry.getKey(),
+                        Collections.unmodifiableList((List) entry.getValue()));
+            }
+        }
+        return Collections.unmodifiableMap(map);
+    }
+
+    public void setInstanceFollowRedirects(boolean instanceFollowRedirects) {
+        connection.setInstanceFollowRedirects(instanceFollowRedirects);
+    }
+
+    public boolean getInstanceFollowRedirects() {
+        return connection.getInstanceFollowRedirects();
+    }
+
+    public void setRequestMethod(String requestMethod)
+            throws ProtocolException {
+        connection.setRequestMethod(requestMethod);
+    }
+
+    public String getRequestMethod() {
+        return connection.getRequestMethod();
+    }
+
+    public int getResponseCode() throws IOException {
+        return connection.getResponseCode();
+    }
+
+    public String getResponseMessage() throws IOException {
+        return connection.getResponseMessage();
+    }
+
+    public void disconnect() {
+        connection.disconnect();
+        connected = false;
+    }
+
+    public boolean usingProxy() {
+        return connection.usingProxy();
+    }
+
+    public InputStream getErrorStream() {
+        return connection.getErrorStream();
+    }
+
+    private int parseResponseCode() throws IOException {
+        try {
+            String response = connection.getHeaderField(0);
+            int index = response.indexOf(' ');
+            while (response.charAt(index) == ' ') index++;
+            return Integer.parseInt(response.substring(index, index + 3));
+        } catch (Exception ex) {
+            throw new IOException(ex.getMessage());
+        }
+    }
+
+    private synchronized void doConnect() throws IOException {
+        connection.connect();
+        int response = parseResponseCode();
+        if (response != HTTP_UNAUTHORIZED && response != HTTP_PROXY_AUTH) {
+            return;
+        }
+        Type1Message type1 = (Type1Message) attemptNegotiation(response);
+        if (type1 == null) return; // no NTLM
+        int attempt = 0;
+        while (attempt < MAX_REDIRECTS) {
+            connection.setRequestProperty(authProperty, method + ' ' +
+                    Base64.encode(type1.toByteArray()));
+            connection.connect(); // send type 1
+            response = parseResponseCode();
+            if (response != HTTP_UNAUTHORIZED && response != HTTP_PROXY_AUTH) {
+                return;
+            }
+            Type3Message type3 = (Type3Message) attemptNegotiation(response);
+            if (type3 == null) return;
+            connection.setRequestProperty(authProperty, method + ' ' +
+                    Base64.encode(type3.toByteArray()));
+            connection.connect(); // send type 3
+            response = parseResponseCode();
+            if (response != HTTP_UNAUTHORIZED && response != HTTP_PROXY_AUTH) {
+                return;
+            }
+            attempt++;
+            if (attempt < MAX_REDIRECTS) reconnect();
+        }
+        throw new IOException("Unable to negotiate NTLM authentication.");
+    }
+
+    private NtlmMessage attemptNegotiation(int response) throws IOException {
+        authProperty = null;
+        method = null;
+        InputStream errorStream = connection.getErrorStream();
+        if (errorStream != null && errorStream.available() != 0) {
+            int count;
+            byte[] buf = new byte[1024];
+            while ((count = errorStream.read(buf, 0, 1024)) != -1);
+        }
+        String authHeader;
+        if (response == HTTP_UNAUTHORIZED) {
+            authHeader = "WWW-Authenticate";
+            authProperty = "Authorization";
+        } else {
+            authHeader = "Proxy-Authenticate";
+            authProperty = "Proxy-Authorization";
+        }
+        String authorization = null;
+        List methods = (List) getHeaderFields0().get(authHeader);
+        if (methods == null) return null;
+        Iterator iterator = methods.iterator();
+        while (iterator.hasNext()) {
+            String authMethod = (String) iterator.next();
+            if (authMethod.startsWith("NTLM")) {
+                if (authMethod.length() == 4) {
+                    method = "NTLM";
+                    break;
+                }
+                if (authMethod.indexOf(' ') != 4) continue;
+                method = "NTLM";
+                authorization = authMethod.substring(5).trim();
+                break;
+            } else if (authMethod.startsWith("Negotiate")) {
+                if (authMethod.length() == 9) {
+                    method = "Negotiate";
+                    break;
+                }
+                if (authMethod.indexOf(' ') != 9) continue;
+                method = "Negotiate";
+                authorization = authMethod.substring(10).trim();
+                break;
+            }
+        }
+        if (method == null) return null;
+        NtlmMessage message = (authorization != null) ?
+                new Type2Message(Base64.decode(authorization)) : null;
+        reconnect();
+        if (message == null) {
+            message = new Type1Message();
+            if (LM_COMPATIBILITY > 2) {
+                message.setFlag(NtlmFlags.NTLMSSP_REQUEST_TARGET, true);
+            }
+        } else {
+            String domain = DEFAULT_DOMAIN;
+            String user = Type3Message.getDefaultUser();
+            String password = Type3Message.getDefaultPassword();
+            String userInfo = url.getUserInfo();
+            if (userInfo != null) {
+                userInfo = URLDecoder.decode(userInfo);
+                int index = userInfo.indexOf(':');
+                user = (index != -1) ? userInfo.substring(0, index) : userInfo;
+                if (index != -1) password = userInfo.substring(index + 1);
+                index = user.indexOf('\\');
+                if (index == -1) index = user.indexOf('/');
+                domain = (index != -1) ? user.substring(0, index) : domain;
+                user = (index != -1) ? user.substring(index + 1) : user;
+            }
+            if (user == null) {
+                try {
+                    URL url = getURL();
+                    String protocol = url.getProtocol();
+                    int port = url.getPort();
+                    if (port == -1) {
+                        port = "https".equalsIgnoreCase(protocol) ? 443 : 80;
+                    }
+                    PasswordAuthentication auth =
+                            Authenticator.requestPasswordAuthentication(null,
+                                    port, protocol, "", method);
+                    if (auth != null) {
+                        user = auth.getUserName();
+                        password = new String(auth.getPassword());
+                    }
+                } catch (Exception ex) { }
+            }
+            Type2Message type2 = (Type2Message) message;
+            message = new Type3Message(type2, password, domain, user,
+                    Type3Message.getDefaultWorkstation());
+        }
+        return message;
+    }
+
+    private void reconnect() throws IOException {
+        connection = (HttpURLConnection) connection.getURL().openConnection();
+        headerFields = null;
+        synchronized (requestProperties) {
+            Iterator properties = requestProperties.entrySet().iterator();
+            while (properties.hasNext()) {
+                Map.Entry property = (Map.Entry) properties.next();
+                String key = (String) property.getKey();
+                StringBuffer value = new StringBuffer();
+                Iterator values = ((List) property.getValue()).iterator();
+                while (values.hasNext()) {
+                    value.append(values.next());
+                    if (values.hasNext()) value.append(", ");
+                }
+                connection.setRequestProperty(key, value.toString());
+            }
+        }
+        connection.setAllowUserInteraction(allowUserInteraction);
+        connection.setDoInput(doInput);
+        connection.setDoOutput(doOutput);
+        connection.setIfModifiedSince(ifModifiedSince);
+        connection.setUseCaches(useCaches);
+    }
 }
index 19d7efc..d379cdd 100644 (file)
@@ -1,6 +1,6 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                      "Eric Glass" <jcifs at samba dot org>
+ *                   "Eric Glass" <jcifs at samba dot org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -59,112 +59,112 @@ import jcifs.netbios.NbtAddress;
 
 public abstract class NtlmServlet extends HttpServlet {
 
-       private String defaultDomain;
-
-       private String domainController;
-
-       private boolean loadBalance;
-
-       private boolean enableBasic;
-
-       private boolean insecureBasic;
-
-       private String realm;
-
-       public void init(ServletConfig config) throws ServletException {
-               super.init(config);
-
-               /* Set jcifs properties we know we want; soTimeout and cachePolicy to 10min.
-                */
-               Config.setProperty( "jcifs.smb.client.soTimeout", "300000" );
-               Config.setProperty( "jcifs.netbios.cachePolicy", "600" );
-
-               Enumeration e = config.getInitParameterNames();
-               String name;
-               while (e.hasMoreElements()) {
-                       name = (String) e.nextElement();
-                       if (name.startsWith("jcifs.")) {
-                               Config.setProperty(name, config.getInitParameter(name));
-                       }
-               }
-               defaultDomain = Config.getProperty("jcifs.smb.client.domain");
-               domainController = Config.getProperty("jcifs.http.domainController");
-               if( domainController == null ) {
-                       domainController = defaultDomain;
-                       loadBalance = Config.getBoolean( "jcifs.http.loadBalance", true );
-               }
-               enableBasic = Boolean.valueOf(
-                               Config.getProperty("jcifs.http.enableBasic")).booleanValue();
-               insecureBasic = Boolean.valueOf(
-                               Config.getProperty("jcifs.http.insecureBasic")).booleanValue();
-               realm = Config.getProperty("jcifs.http.basicRealm");
-               if (realm == null) realm = "jCIFS";
-       }
-
-       protected void service(HttpServletRequest request,
-                       HttpServletResponse response) throws ServletException, IOException {
-               UniAddress dc;
-               boolean offerBasic = enableBasic &&
-                               (insecureBasic || request.isSecure());
-               String msg = request.getHeader("Authorization");
-               if (msg != null && (msg.startsWith("NTLM ") ||
-                                       (offerBasic && msg.startsWith("Basic ")))) {
-                       if( loadBalance ) {
-                               dc = new UniAddress( NbtAddress.getByName( domainController, 0x1C, null ));
-                       } else {
-                               dc = UniAddress.getByName( domainController, true );
-                       }
-                       NtlmPasswordAuthentication ntlm;
-                       if (msg.startsWith("NTLM ")) {
-                               byte[] challenge = SmbSession.getChallenge(dc);
-                               ntlm = NtlmSsp.authenticate(request, response, challenge);
-                               if (ntlm == null) return;
-                       } else {
-                               String auth = new String(Base64.decode(msg.substring(6)),
-                                               "US-ASCII");
-                               int index = auth.indexOf(':');
-                               String user = (index != -1) ? auth.substring(0, index) : auth;
-                               String password = (index != -1) ? auth.substring(index + 1) :
-                                               "";
-                               index = user.indexOf('\\');
-                               if (index == -1) index = user.indexOf('/');
-                               String domain = (index != -1) ? user.substring(0, index) :
-                                               defaultDomain;
-                               user = (index != -1) ? user.substring(index + 1) : user;
-                               ntlm = new NtlmPasswordAuthentication(domain, user, password);
-                       }
-                       try {
-                               SmbSession.logon(dc, ntlm);
-                       } catch (SmbAuthException sae) {
-                               response.setHeader("WWW-Authenticate", "NTLM");
-                               if (offerBasic) {
-                                       response.addHeader("WWW-Authenticate", "Basic realm=\"" +
-                                                       realm + "\"");
-                               }
-                               response.setHeader("Connection", "close");
-                               response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
-                               response.flushBuffer();
-                               return;
-                       }
-                       HttpSession ssn = request.getSession();
-                       ssn.setAttribute("NtlmHttpAuth", ntlm);
-                       ssn.setAttribute( "ntlmdomain", ntlm.getDomain() );
-                       ssn.setAttribute( "ntlmuser", ntlm.getUsername() );
-               } else {
-                       HttpSession ssn = request.getSession(false);
-                       if (ssn == null || ssn.getAttribute("NtlmHttpAuth") == null) {
-                               response.setHeader("WWW-Authenticate", "NTLM");
-                               if (offerBasic) {
-                                       response.addHeader("WWW-Authenticate", "Basic realm=\"" +
-                                                       realm + "\"");
-                               }
-                               response.setHeader("Connection", "close");
-                               response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
-                               response.flushBuffer();
-                               return;
-                       }
-               }
-               super.service(request, response);
-       }
+    private String defaultDomain;
+
+    private String domainController;
+
+    private boolean loadBalance;
+
+    private boolean enableBasic;
+
+    private boolean insecureBasic;
+
+    private String realm;
+
+    public void init(ServletConfig config) throws ServletException {
+        super.init(config);
+
+        /* Set jcifs properties we know we want; soTimeout and cachePolicy to 10min.
+         */
+        Config.setProperty( "jcifs.smb.client.soTimeout", "300000" );
+        Config.setProperty( "jcifs.netbios.cachePolicy", "600" );
+
+        Enumeration e = config.getInitParameterNames();
+        String name;
+        while (e.hasMoreElements()) {
+            name = (String) e.nextElement();
+            if (name.startsWith("jcifs.")) {
+                Config.setProperty(name, config.getInitParameter(name));
+            }
+        }
+        defaultDomain = Config.getProperty("jcifs.smb.client.domain");
+        domainController = Config.getProperty("jcifs.http.domainController");
+        if( domainController == null ) {
+            domainController = defaultDomain;
+            loadBalance = Config.getBoolean( "jcifs.http.loadBalance", true );
+        }
+        enableBasic = Boolean.valueOf(
+                Config.getProperty("jcifs.http.enableBasic")).booleanValue();
+        insecureBasic = Boolean.valueOf(
+                Config.getProperty("jcifs.http.insecureBasic")).booleanValue();
+        realm = Config.getProperty("jcifs.http.basicRealm");
+        if (realm == null) realm = "jCIFS";
+    }
+
+    protected void service(HttpServletRequest request,
+            HttpServletResponse response) throws ServletException, IOException {
+        UniAddress dc;
+        boolean offerBasic = enableBasic &&
+                (insecureBasic || request.isSecure());
+        String msg = request.getHeader("Authorization");
+        if (msg != null && (msg.startsWith("NTLM ") ||
+                    (offerBasic && msg.startsWith("Basic ")))) {
+            if( loadBalance ) {
+                dc = new UniAddress( NbtAddress.getByName( domainController, 0x1C, null ));
+            } else {
+                dc = UniAddress.getByName( domainController, true );
+            }
+            NtlmPasswordAuthentication ntlm;
+            if (msg.startsWith("NTLM ")) {
+                byte[] challenge = SmbSession.getChallenge(dc);
+                ntlm = NtlmSsp.authenticate(request, response, challenge);
+                if (ntlm == null) return;
+            } else {
+                String auth = new String(Base64.decode(msg.substring(6)),
+                        "US-ASCII");
+                int index = auth.indexOf(':');
+                String user = (index != -1) ? auth.substring(0, index) : auth;
+                String password = (index != -1) ? auth.substring(index + 1) :
+                        "";
+                index = user.indexOf('\\');
+                if (index == -1) index = user.indexOf('/');
+                String domain = (index != -1) ? user.substring(0, index) :
+                        defaultDomain;
+                user = (index != -1) ? user.substring(index + 1) : user;
+                ntlm = new NtlmPasswordAuthentication(domain, user, password);
+            }
+            try {
+                SmbSession.logon(dc, ntlm);
+            } catch (SmbAuthException sae) {
+                response.setHeader("WWW-Authenticate", "NTLM");
+                if (offerBasic) {
+                    response.addHeader("WWW-Authenticate", "Basic realm=\"" +
+                            realm + "\"");
+                }
+                response.setHeader("Connection", "close");
+                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+                response.flushBuffer();
+                return;
+            }
+            HttpSession ssn = request.getSession();
+            ssn.setAttribute("NtlmHttpAuth", ntlm);
+            ssn.setAttribute( "ntlmdomain", ntlm.getDomain() );
+            ssn.setAttribute( "ntlmuser", ntlm.getUsername() );
+        } else {
+            HttpSession ssn = request.getSession(false);
+            if (ssn == null || ssn.getAttribute("NtlmHttpAuth") == null) {
+                response.setHeader("WWW-Authenticate", "NTLM");
+                if (offerBasic) {
+                    response.addHeader("WWW-Authenticate", "Basic realm=\"" +
+                            realm + "\"");
+                }
+                response.setHeader("Connection", "close");
+                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+                response.flushBuffer();
+                return;
+            }
+        }
+        super.service(request, response);
+    }
 }
 
index 5cab7f2..35e0a68 100644 (file)
@@ -1,8 +1,8 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                      "Eric Glass" <jcifs at samba dot org>
- *                                      "Jason Pugsley" <jcifs at samba dot org>
- *                                      "skeetz" <jcifs at samba dot org>
+ *                   "Eric Glass" <jcifs at samba dot org>
+ *                   "Jason Pugsley" <jcifs at samba dot org>
+ *                   "skeetz" <jcifs at samba dot org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -52,61 +52,61 @@ import jcifs.ntlmssp.Type3Message;
 
 public class NtlmSsp implements NtlmFlags {
 
-       /**
-        * Calls the static {@link #authenticate(HttpServletRequest,
-        * HttpServletResponse, byte[])} method to perform NTLM authentication
-        * for the specified servlet request.
-        *
-        * @param req The request being serviced.
-        * @param resp The response.
-        * @param challenge The domain controller challenge.
-        * @throws IOException If an IO error occurs.
-        * @throws ServletException If an error occurs.
-        */
-       public NtlmPasswordAuthentication doAuthentication(
-                       HttpServletRequest req, HttpServletResponse resp, byte[] challenge)
-                                       throws IOException, ServletException {
-               return authenticate(req, resp, challenge);
-       }
+    /**
+     * Calls the static {@link #authenticate(HttpServletRequest,
+     * HttpServletResponse, byte[])} method to perform NTLM authentication
+     * for the specified servlet request.
+     *
+     * @param req The request being serviced.
+     * @param resp The response.
+     * @param challenge The domain controller challenge.
+     * @throws IOException If an IO error occurs.
+     * @throws ServletException If an error occurs.
+     */
+    public NtlmPasswordAuthentication doAuthentication(
+            HttpServletRequest req, HttpServletResponse resp, byte[] challenge)
+                    throws IOException, ServletException {
+        return authenticate(req, resp, challenge);
+    }
 
-       /**
-        * Performs NTLM authentication for the servlet request.
-        *
-        * @param req The request being serviced.
-        * @param resp The response.
-        * @param challenge The domain controller challenge.
-        * @throws IOException If an IO error occurs.
-        * @throws ServletException If an error occurs.
-        */
-       public static NtlmPasswordAuthentication authenticate(
-                       HttpServletRequest req, HttpServletResponse resp, byte[] challenge)
-                                       throws IOException, ServletException {
-               String msg = req.getHeader("Authorization");
-               if (msg != null && msg.startsWith("NTLM ")) {
-                       byte[] src = Base64.decode(msg.substring(5));
-                       if (src[8] == 1) {
-                               Type1Message type1 = new Type1Message(src);
-                               Type2Message type2 = new Type2Message(type1, challenge, null);
-                               msg = Base64.encode(type2.toByteArray());
-                               resp.setHeader( "WWW-Authenticate", "NTLM " + msg );
-                       } else if (src[8] == 3) {
-                               Type3Message type3 = new Type3Message(src);
-                               byte[] lmResponse = type3.getLMResponse();
-                               if (lmResponse == null) lmResponse = new byte[0];
-                               byte[] ntResponse = type3.getNTResponse();
-                               if (ntResponse == null) ntResponse = new byte[0];
-                               return new NtlmPasswordAuthentication(type3.getDomain(),
-                                               type3.getUser(), lmResponse, ntResponse);
-                       }
-               } else {
-                       resp.setHeader("WWW-Authenticate", "NTLM");
-                       resp.setHeader("Connection", "close");
-               }
-               resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
-               resp.setContentLength( 0 );
-               resp.flushBuffer();
-               return null;
-       }
+    /**
+     * Performs NTLM authentication for the servlet request.
+     *
+     * @param req The request being serviced.
+     * @param resp The response.
+     * @param challenge The domain controller challenge.
+     * @throws IOException If an IO error occurs.
+     * @throws ServletException If an error occurs.
+     */
+    public static NtlmPasswordAuthentication authenticate(
+            HttpServletRequest req, HttpServletResponse resp, byte[] challenge)
+                    throws IOException, ServletException {
+        String msg = req.getHeader("Authorization");
+        if (msg != null && msg.startsWith("NTLM ")) {
+            byte[] src = Base64.decode(msg.substring(5));
+            if (src[8] == 1) {
+                Type1Message type1 = new Type1Message(src);
+                Type2Message type2 = new Type2Message(type1, challenge, null);
+                msg = Base64.encode(type2.toByteArray());
+                resp.setHeader( "WWW-Authenticate", "NTLM " + msg );
+            } else if (src[8] == 3) {
+                Type3Message type3 = new Type3Message(src);
+                byte[] lmResponse = type3.getLMResponse();
+                if (lmResponse == null) lmResponse = new byte[0];
+                byte[] ntResponse = type3.getNTResponse();
+                if (ntResponse == null) ntResponse = new byte[0];
+                return new NtlmPasswordAuthentication(type3.getDomain(),
+                        type3.getUser(), lmResponse, ntResponse);
+            }
+        } else {
+            resp.setHeader("WWW-Authenticate", "NTLM");
+            resp.setHeader("Connection", "close");
+        }
+        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+        resp.setContentLength( 0 );
+        resp.flushBuffer();
+        return null;
+    }
 
 }
 
index 041b008..03cd7c1 100644 (file)
@@ -1,6 +1,6 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                      "Eric Glass" <jcifs at samba dot org>
+ *                   "Eric Glass" <jcifs at samba dot org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
index 1e50925..8f627bd 100644 (file)
@@ -18,8 +18,6 @@
 
 package jcifs.netbios;
 
-import jcifs.Config;
-import jcifs.smb.SmbFileInputStream;
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.FileReader;
@@ -29,123 +27,130 @@ import java.io.BufferedReader;
 import java.io.IOException;
 import java.util.Hashtable;
 import java.net.UnknownHostException;
+import jcifs.Config;
+import jcifs.smb.SmbFileInputStream;
+import jcifs.util.LogStream;
 
 public class Lmhosts {
 
-       static String filename = Config.getProperty( "jcifs.netbios.lmhosts" );
-       static Hashtable tab = new Hashtable();
-       static long lastModified = 1L;
-       static int alt;
-
-       /**
-        * This is really just for {@link jcifs.UniAddress}. It does
-        * not throw an {@link java.net.UnknownHostException} because this
-        * is queried frequently and exceptions would be rather costly to
-        * throw on a regular basis here.
-        */
-
-       public synchronized static NbtAddress getByName( String host ) {
-               return getByName( new Name( host, 0x20, null ));
-       }
-
-       synchronized static NbtAddress getByName( Name name ) {
-               NbtAddress result = null;
-
-               try {
-                       if( filename != null ) {
-                               File f = new File( filename );
-                               long lm;
-
-                               if(( lm = f.lastModified() ) > lastModified ) {
-                                       lastModified = lm;
-                                       tab.clear();
-                                       alt = 0;
-                                       populate( new FileReader( f ));
-                               }
-                               result = (NbtAddress)tab.get( name );
-                       }
-               } catch( FileNotFoundException fnfe ) {
-                       Log.println( Log.WARNINGS, "netbios name service exception",
-                                                                       "lmhosts file not found: " + filename );
-               } catch( IOException ioe ) {
-                       Log.printStackTrace( "netbios name service exception", ioe );
-               }
-               return result;
-       }
-
-       static void populate( Reader r ) throws IOException {
-               String line;
-               BufferedReader br = new BufferedReader( r );
-
-               while(( line = br.readLine() ) != null ) {
-                       line = line.toUpperCase().trim();
-                       if( line.length() == 0 ) {
-                               continue;
-                       } else if( line.charAt( 0 ) == '#' ) {
-                               if( line.startsWith( "#INCLUDE " )) {
-                                       line = line.substring( line.indexOf( '\\' ));
-                                       String url = "smb:" + line.replace( '\\', '/' );
-
-                                       if( alt > 0 ) {
-                                               try {
-                                                       populate( new InputStreamReader( new SmbFileInputStream( url )));
-                                               } catch( IOException ioe ) {
-                                                       Log.println( Log.WARNINGS, "netbios name service warning",
-                                                                               "failed to load lmhosts alternate include: " + url );
-                                                       continue;
-                                               }
-
-                                               /* An include was loaded successfully. We can skip
-                                                * all other includes up to the #END_ALTERNATE tag.
-                                                */
-
-                                               alt--;
-                                               while(( line = br.readLine() ) != null ) {
-                                                       line = line.toUpperCase().trim();
-                                                       if( line.startsWith( "#END_ALTERNATE" )) {
-                                                               break;
-                                                       }
-                                               }
-                                       } else {
-                                               populate( new InputStreamReader( new SmbFileInputStream( url )));
-                                       }
-                               } else if( line.startsWith( "#BEGIN_ALTERNATE" )) {
-                                       alt++;
-                               } else if( line.startsWith( "#END_ALTERNATE" ) && alt > 0 ) {
-                                       alt--;
-                                       throw new IOException( "no lmhosts alternate includes loaded" );
-                               }
-                       } else if( Character.isDigit( line.charAt( 0 ))) {
-                               char[] data = line.toCharArray();
-                               int ip, i, j;
-                               Name name;
-                               NbtAddress addr;
-                               char c;
-
-                               c = '.';
-                               ip = i = 0;
-                               for( ; i < data.length && c == '.'; i++ ) {
-                                       int b = 0x00;
-
-                                       for( ; i < data.length && ( c = data[i] ) >= 48 && c <= 57; i++ ) {
-                                               b = b * 10 + c - '0';
-                                       }
-                                       ip = ( ip << 8 ) + b;
-                               }
-                               while( i < data.length && Character.isWhitespace( data[i] )) {
-                                       i++;
-                               }
-                               j = i;
-                               while( j < data.length && Character.isWhitespace( data[j] ) == false ) {
-                                       j++;
-                               }
-
-                               name = new Name( line.substring( i, j ), 0x20, null );
-                               addr = new NbtAddress( name, ip, false, NbtAddress.B_NODE,
-                                                                       false, false, true, true,
-                                                                       NbtAddress.unknownMacAddress );
-                               tab.put( name, addr );
-                       }
-               }
-       }
+    private static final String FILENAME = Config.getProperty( "jcifs.netbios.lmhosts" );
+    private static final Hashtable TAB = new Hashtable();
+    private static long lastModified = 1L;
+    private static int alt;
+    private static LogStream log = LogStream.getInstance();
+
+    /**
+     * This is really just for {@link jcifs.UniAddress}. It does
+     * not throw an {@link java.net.UnknownHostException} because this
+     * is queried frequently and exceptions would be rather costly to
+     * throw on a regular basis here.
+     */
+
+    public synchronized static NbtAddress getByName( String host ) {
+        return getByName( new Name( host, 0x20, null ));
+    }
+
+    synchronized static NbtAddress getByName( Name name ) {
+        NbtAddress result = null;
+
+        try {
+            if( FILENAME != null ) {
+                File f = new File( FILENAME );
+                long lm;
+
+                if(( lm = f.lastModified() ) > lastModified ) {
+                    lastModified = lm;
+                    TAB.clear();
+                    alt = 0;
+                    populate( new FileReader( f ));
+                }
+                result = (NbtAddress)TAB.get( name );
+            }
+        } catch( FileNotFoundException fnfe ) {
+            if( log.level > 1 ) {
+                log.println( "lmhosts file: " + FILENAME );
+                fnfe.printStackTrace( log );
+            }
+        } catch( IOException ioe ) {
+            if( log.level > 0 )
+                ioe.printStackTrace( log );
+        }
+        return result;
+    }
+
+    static void populate( Reader r ) throws IOException {
+        String line;
+        BufferedReader br = new BufferedReader( r );
+
+        while(( line = br.readLine() ) != null ) {
+            line = line.toUpperCase().trim();
+            if( line.length() == 0 ) {
+                continue;
+            } else if( line.charAt( 0 ) == '#' ) {
+                if( line.startsWith( "#INCLUDE " )) {
+                    line = line.substring( line.indexOf( '\\' ));
+                    String url = "smb:" + line.replace( '\\', '/' );
+
+                    if( alt > 0 ) {
+                        try {
+                            populate( new InputStreamReader( new SmbFileInputStream( url )));
+                        } catch( IOException ioe ) {
+                            log.println( "lmhosts URL: " + url );
+                            ioe.printStackTrace( log );
+                            continue;
+                        }
+
+                        /* An include was loaded successfully. We can skip
+                         * all other includes up to the #END_ALTERNATE tag.
+                         */
+
+                        alt--;
+                        while(( line = br.readLine() ) != null ) {
+                            line = line.toUpperCase().trim();
+                            if( line.startsWith( "#END_ALTERNATE" )) {
+                                break;
+                            }
+                        }
+                    } else {
+                        populate( new InputStreamReader( new SmbFileInputStream( url )));
+                    }
+                } else if( line.startsWith( "#BEGIN_ALTERNATE" )) {
+                    alt++;
+                } else if( line.startsWith( "#END_ALTERNATE" ) && alt > 0 ) {
+                    alt--;
+                    throw new IOException( "no lmhosts alternate includes loaded" );
+                }
+            } else if( Character.isDigit( line.charAt( 0 ))) {
+                char[] data = line.toCharArray();
+                int ip, i, j;
+                Name name;
+                NbtAddress addr;
+                char c;
+
+                c = '.';
+                ip = i = 0;
+                for( ; i < data.length && c == '.'; i++ ) {
+                    int b = 0x00;
+
+                    for( ; i < data.length && ( c = data[i] ) >= 48 && c <= 57; i++ ) {
+                        b = b * 10 + c - '0';
+                    }
+                    ip = ( ip << 8 ) + b;
+                }
+                while( i < data.length && Character.isWhitespace( data[i] )) {
+                    i++;
+                }
+                j = i;
+                while( j < data.length && Character.isWhitespace( data[j] ) == false ) {
+                    j++;
+                }
+
+                name = new Name( line.substring( i, j ), 0x20, null );
+                addr = new NbtAddress( name, ip, false, NbtAddress.B_NODE,
+                                    false, false, true, true,
+                                    NbtAddress.UNKNOWN_MAC_ADDRESS );
+                TAB.put( name, addr );
+            }
+        }
+    }
 }
diff --git a/src/jcifs/netbios/Log.java b/src/jcifs/netbios/Log.java
deleted file mode 100644 (file)
index 2ce7bba..0000000
+++ /dev/null
@@ -1,108 +0,0 @@
-/* jcifs smb client library in Java
- * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-package jcifs.netbios;
-
-import java.util.Hashtable;
-import java.util.Enumeration;
-
-/**
- * Provides logging methods specific to the netbios package. Log class
- * members are applied to the Log's mask(set as an arithmetic expression
- * from {@link jcifs.util.Log#setMask(int mask)}) to "flip on" logging of
- * netbios specific information.
- * <p><blockquote><pre>
- *     Log.setMask( Log.EXCEPTIONS +
- *                 jcifs.netbios.Log.SESSION_SERVICE_PACKET_DATA );
- * </pre></blockquote>
- * <p>
- * See the {@link jcifs.util.Log} parent class for details about this
- * logging style.
- *
- * @see       jcifs.util.Log
- */
-
-public class Log extends jcifs.util.Log {
-
-    // supress javadoc constructor summary
-    Log() {}
-
-    public static final int NONE                        = 0xFFFFFF0F;
-    public static final int ALL                         = 0x000000F0;
-
-/**
- *
- * This mask produces limited netbios name service packet information. See
- * <a href="http://www.cis.ohio-state.edu/rfc/rfc1002.txt">RFC 1002</a>
- * for a detailed description of packet contents and their meaning.
- *
- * @see jcifs.util.Log#setMask(int mask)
- */
-
-    public static final int NAME_SERVICE_PACKET_DATA    = 0x00000010;
-
-    public static final int SESSION_SERVICE_PACKET_DATA = 0x00000020;
-
-/**
- * This mask produces the contents of the netbios address cache.
- *
- * @see jcifs.util.Log#setMask(int mask)
- */
-
-    public static final int ADDRESS_CACHE               = 0x00000040;
-
-/**
- * reserved for this package
- */
-    public static final int RESERVED8                   = 0x00000080;
-
-       static void printPacketData( String desc, SessionServicePacket ssp ) {
-               try { // why do I have try/catch here?
-                       if(( SESSION_SERVICE_PACKET_DATA & mask ) == 0 ) {
-                               return;
-                       }
-            out.println( desc, ssp.toString() );
-        } catch( Exception e ) {
-            Log.printStackTrace( "jcifs.netbios.Log.printPacketData()", e );
-        }
-       }
-
-    static void printPacketData( String desc, NameServicePacket nsp ) {
-        try {
-            if(( NAME_SERVICE_PACKET_DATA & mask ) == 0 ) {
-                return;
-                       }
-                       out.println( desc, nsp.toString() );
-        } catch( Exception e ) {
-            Log.printStackTrace( "jcifs.netbios.Log.printPacketData()", e );
-        }
-    }
-    static void printAddressCache( String desc, Hashtable addressCache ) {
-        if(( ADDRESS_CACHE & mask ) == 0 )
-            return;
-        StringBuffer sb = new StringBuffer();
-        NbtAddress.CacheEntry ce;
-        for( Enumeration e = addressCache.elements(); e.hasMoreElements(); ) {
-            ce = (NbtAddress.CacheEntry)e.nextElement();
-                       sb.append( ' ' ).append( ce.hostName );
-                       sb.append( ' ' ).append( ce.address ).append( NL );
-        }
-        out.println( desc, sb.toString() );
-    }
-}
-
index 330aebd..acc6716 100644 (file)
@@ -21,76 +21,61 @@ package jcifs.netbios;
 
 import java.io.UnsupportedEncodingException;
 import jcifs.Config;
+import jcifs.util.Hexdump;
 
 class Name {
 
-    static final char[] HEX_DIGITS = { 
-    '0' , '1' , '2' , '3' , '4' , '5' ,
-    '6' , '7' , '8' , '9' , 'A' , 'B' ,
-    'C' , 'D' , 'E' , 'F'
-    };
-
-    static String toHexChars( int val ) {
-        int len = 2;
-        char[] tmp = new char[2];
-        while( len > 0 ) {
-            tmp[ len - 1 ] = HEX_DIGITS[val & 0x000F];
-            if( val != 0 ) {
-                val >>>= 4;
-            }
-            len--;
-        }
-        return new String( tmp );
-    }
+    private static final int TYPE_OFFSET = 31;
+    private static final int SCOPE_OFFSET = 33;
+    private static final String DEFAULT_SCOPE = Config.getProperty( "jcifs.netbios.scope" );
 
-       static final int TYPE_OFFSET = 31;
-       static final int SCOPE_OFFSET = 33;
-
-       static String defaultScope = Config.getProperty( "jcifs.netbios.scope" );
-       static String encoding = Config.getProperty( "jcifs.netbios.encoding", "ISO8859_1" );
+    static final String OEM_ENCODING =
+            Config.getProperty( "jcifs.smb.client.codepage",
+                    Config.getProperty( "jcifs.encoding",
+                            System.getProperty( "file.encoding" )));
 
     String name, scope;
     int hexCode;
-       int srcHashCode; /* srcHashCode must be set by name resolution
-                                         * routines before entry into addressCache
-                                         */
+    int srcHashCode; /* srcHashCode must be set by name resolution
+                      * routines before entry into addressCache
+                      */
 
-       Name() {
-       }
+    Name() {
+    }
     Name( String name, int hexCode, String scope ) {
-           if( name.length() > 15 ) {
-                       name = name.substring( 0, 15 );
-               }
-               this.name = name.toUpperCase();
-               this.hexCode = hexCode;
-               this.scope = scope != null && scope.length() > 0 ? scope : defaultScope;
-               this.srcHashCode = 0;
+        if( name.length() > 15 ) {
+            name = name.substring( 0, 15 );
+        }
+        this.name = name.toUpperCase();
+        this.hexCode = hexCode;
+        this.scope = scope != null && scope.length() > 0 ? scope : DEFAULT_SCOPE;
+        this.srcHashCode = 0;
     }
 
-       int writeWireFormat( byte[] dst, int dstIndex ) {
+    int writeWireFormat( byte[] dst, int dstIndex ) {
         // write 0x20 in first byte
         dst[dstIndex] = 0x20;
 
         // write name
-               try {
-               byte tmp[] = name.getBytes( Name.encoding );
-               int i;
-               for( i = 0; i < tmp.length; i++ ) {
-                   dst[dstIndex + ( 2 * i + 1 )] = (byte)((( tmp[i] & 0xF0 ) >> 4 ) + 0x41 );
-                   dst[dstIndex + ( 2 * i + 2 )] = (byte)(( tmp[i] & 0x0F ) + 0x41 );
-               }
-               for( ; i < 15; i++ ) {
-                   dst[dstIndex + ( 2 * i + 1 )] = (byte)0x43;
-                   dst[dstIndex + ( 2 * i + 2 )] = (byte)0x41;
-               }
-               dst[dstIndex + TYPE_OFFSET] = (byte)((( hexCode & 0xF0 ) >> 4 ) + 0x41 );
-               dst[dstIndex + TYPE_OFFSET + 1] = (byte)(( hexCode & 0x0F ) + 0x41 );
-               } catch( UnsupportedEncodingException uee ) {
-               }
-               return SCOPE_OFFSET + writeScopeWireFormat( dst, dstIndex + SCOPE_OFFSET );
-       }
-
-       int readWireFormat( byte[] src, int srcIndex ) {
+        try {
+            byte tmp[] = name.getBytes( Name.OEM_ENCODING );
+            int i;
+            for( i = 0; i < tmp.length; i++ ) {
+                dst[dstIndex + ( 2 * i + 1 )] = (byte)((( tmp[i] & 0xF0 ) >> 4 ) + 0x41 );
+                dst[dstIndex + ( 2 * i + 2 )] = (byte)(( tmp[i] & 0x0F ) + 0x41 );
+            }
+            for( ; i < 15; i++ ) {
+                dst[dstIndex + ( 2 * i + 1 )] = (byte)0x43;
+                dst[dstIndex + ( 2 * i + 2 )] = (byte)0x41;
+            }
+            dst[dstIndex + TYPE_OFFSET] = (byte)((( hexCode & 0xF0 ) >> 4 ) + 0x41 );
+            dst[dstIndex + TYPE_OFFSET + 1] = (byte)(( hexCode & 0x0F ) + 0x41 );
+        } catch( UnsupportedEncodingException uee ) {
+        }
+        return SCOPE_OFFSET + writeScopeWireFormat( dst, dstIndex + SCOPE_OFFSET );
+    }
+
+    int readWireFormat( byte[] src, int srcIndex ) {
 
         byte tmp[] = new byte[SCOPE_OFFSET];
         int length = 15;
@@ -101,102 +86,102 @@ class Name {
                 length = i + 1;
             }
         }
-               try {
-               name = new String( tmp, 0, length, Name.encoding );
-               } catch( UnsupportedEncodingException uee ) {
-               }
+        try {
+            name = new String( tmp, 0, length, Name.OEM_ENCODING );
+        } catch( UnsupportedEncodingException uee ) {
+        }
         hexCode = (( src[srcIndex + TYPE_OFFSET] & 0xFF ) - 0x41 ) << 4;
         hexCode |= (( src[srcIndex + TYPE_OFFSET + 1] & 0xFF ) - 0x41 ) & 0x0F;
-               return SCOPE_OFFSET + readScopeWireFormat( src, srcIndex + SCOPE_OFFSET );
+        return SCOPE_OFFSET + readScopeWireFormat( src, srcIndex + SCOPE_OFFSET );
     }
-       int writeScopeWireFormat( byte[] dst, int dstIndex ) {
-               if( scope == null ) {
-                       dst[dstIndex] = (byte)0x00;
-                       return 1;
-               }
+    int writeScopeWireFormat( byte[] dst, int dstIndex ) {
+        if( scope == null ) {
+            dst[dstIndex] = (byte)0x00;
+            return 1;
+        }
 
         // copy new scope in
         dst[dstIndex++] = (byte)'.';
-               try {
-               System.arraycopy( scope.getBytes( encoding ), 0, dst, dstIndex, scope.length() );
-               } catch( UnsupportedEncodingException uee ) {
-               }
-               dstIndex += scope.length();
+        try {
+            System.arraycopy( scope.getBytes( Name.OEM_ENCODING ), 0, dst, dstIndex, scope.length() );
+        } catch( UnsupportedEncodingException uee ) {
+        }
+        dstIndex += scope.length();
 
-               dst[dstIndex++] = (byte)0x00;
+        dst[dstIndex++] = (byte)0x00;
 
         // now go over scope backwards converting '.' to label length
 
-               int i = dstIndex - 2;
-               int e = i - scope.length();
-               int c = 0;
+        int i = dstIndex - 2;
+        int e = i - scope.length();
+        int c = 0;
 
-               do {
+        do {
             if( dst[i] == '.' ) {
                 dst[i] = (byte)c;
                 c = 0;
             } else {
                 c++;
             }
-               } while( i-- > e );
-               return scope.length() + 2;
+        } while( i-- > e );
+        return scope.length() + 2;
+    }
+    int readScopeWireFormat( byte[] src, int srcIndex ) {
+        int start = srcIndex;
+        int n;
+        StringBuffer sb;
+
+        if(( n = src[srcIndex++] & 0xFF ) == 0 ) {
+            scope = null;
+            return 1;
+        }
+
+        try {
+            sb = new StringBuffer( new String( src, srcIndex, n, Name.OEM_ENCODING ));
+            srcIndex += n;
+            while(( n = src[srcIndex++] & 0xFF ) != 0 ) {
+                sb.append( '.' ).append( new String( src, srcIndex, n, Name.OEM_ENCODING ));
+                srcIndex += n;
+            }
+            scope = sb.toString();
+        } catch( UnsupportedEncodingException uee ) {
+        }
+
+        return srcIndex - start;
     }
-       int readScopeWireFormat( byte[] src, int srcIndex ) {
-               int start = srcIndex;
-               int n;
-               StringBuffer sb;
-
-               if(( n = src[srcIndex++] & 0xFF ) == 0 ) {
-                       scope = null;
-                       return 1;
-               }
-
-               try {
-                       sb = new StringBuffer( new String( src, srcIndex, n, Name.encoding ));
-                       srcIndex += n;
-                       while(( n = src[srcIndex++] & 0xFF ) != 0 ) {
-                               sb.append( '.' ).append( new String( src, srcIndex, n, Name.encoding ));
-                               srcIndex += n;
-                       }
-                       scope = sb.toString();
-               } catch( UnsupportedEncodingException uee ) {
-               }
-
-               return srcIndex - start;
-       }
 
     public int hashCode() {
-               int result;
-
-               result = name.hashCode();
-               result += 65599 * hexCode;
-               result += 65599 * srcHashCode; /* hashCode is different depending
-                                                                               * on where it came from
-                                                                               */
-               if( scope != null && scope.length() != 0 ) {
-                       result += scope.hashCode();
-               }
+        int result;
+
+        result = name.hashCode();
+        result += 65599 * hexCode;
+        result += 65599 * srcHashCode; /* hashCode is different depending
+                                        * on where it came from
+                                        */
+        if( scope != null && scope.length() != 0 ) {
+            result += scope.hashCode();
+        }
         return result;
     }
     public boolean equals( Object obj ) {
-               Name n;
+        Name n;
 
         if( !( obj instanceof Name )) {
             return false;
         }
         n = (Name)obj;
-               if( scope == null && n.scope == null ) {
-                       return name.equals( n.name ) && hexCode == n.hexCode;
-               }
-               return name.equals( n.name ) && hexCode == n.hexCode && scope.equals( n.scope );
+        if( scope == null && n.scope == null ) {
+            return name.equals( n.name ) && hexCode == n.hexCode;
+        }
+        return name.equals( n.name ) && hexCode == n.hexCode && scope.equals( n.scope );
     }
     public String toString() {
-               StringBuffer sb = new StringBuffer();
-               String n = name;
+        StringBuffer sb = new StringBuffer();
+        String n = name;
 
         // fix MSBROWSE name
-               if( n == null ) {
-                       n = "null";
+        if( n == null ) {
+            n = "null";
         } else if( n.charAt( 0 ) == 0x01 ) {
             char c[] = n.toCharArray();
             c[0] = '.';
@@ -205,7 +190,7 @@ class Name {
             n = new String( c );
         }
 
-        sb.append( n ).append( "<" ).append( toHexChars( hexCode )).append( ">" );
+        sb.append( n ).append( "<" ).append( Hexdump.toHexString( hexCode, 2 )).append( ">" );
         if( scope != null ) {
             sb.append( "." ).append( scope );
         }
index 97d5b01..24906d7 100644 (file)
@@ -20,25 +20,25 @@ package jcifs.netbios;
 
 class NameQueryRequest extends NameServicePacket {
 
-       NameQueryRequest( Name name ) {
-               questionName = name;
-               questionType = NB;
-       }
+    NameQueryRequest( Name name ) {
+        questionName = name;
+        questionType = NB;
+    }
 
-       int writeBodyWireFormat( byte[] dst, int dstIndex ) {
-               return writeQuestionSectionWireFormat( dst, dstIndex );
-       }
-       int readBodyWireFormat( byte[] src, int srcIndex ) {
-               return readQuestionSectionWireFormat( src, srcIndex );
-       }
-       int writeRDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readRDataWireFormat( byte[] src, int srcIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "NameQueryRequest[" +
-                       super.toString() + "]" );
-       }
+    int writeBodyWireFormat( byte[] dst, int dstIndex ) {
+        return writeQuestionSectionWireFormat( dst, dstIndex );
+    }
+    int readBodyWireFormat( byte[] src, int srcIndex ) {
+        return readQuestionSectionWireFormat( src, srcIndex );
+    }
+    int writeRDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readRDataWireFormat( byte[] src, int srcIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "NameQueryRequest[" +
+            super.toString() + "]" );
+    }
 }
index a9a5942..5569839 100644 (file)
@@ -20,35 +20,35 @@ package jcifs.netbios;
 
 class NameQueryResponse extends NameServicePacket {
 
-       NbtAddress addrEntry;
+    NbtAddress addrEntry;
 
-       NameQueryResponse() {
-               recordName = new Name();
-       }
+    NameQueryResponse() {
+        recordName = new Name();
+    }
 
-       int writeBodyWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readBodyWireFormat( byte[] src, int srcIndex ) {
-               return readResourceRecordWireFormat( src, srcIndex );
-       }
-       int writeRDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readRDataWireFormat( byte[] src, int srcIndex ) {
-               if( resultCode != 0 || opCode != QUERY ) {
-                       return 0;
-               }
-               boolean groupName = (( src[srcIndex] & 0x80 ) == 0x80 ) ? true : false;
-               int nodeType = ( src[srcIndex] & 0x60 ) >> 5;
-               srcIndex += 2;
-               int address = readInt4( src, srcIndex );
-               addrEntry = new NbtAddress( recordName, address, groupName, nodeType );
-               return 6;
-       }
-       public String toString() {
-               return new String( "NameQueryResponse[" +
-                       super.toString() +
-                       ",addrEntry=" + addrEntry + "]" );
-       }
+    int writeBodyWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readBodyWireFormat( byte[] src, int srcIndex ) {
+        return readResourceRecordWireFormat( src, srcIndex );
+    }
+    int writeRDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readRDataWireFormat( byte[] src, int srcIndex ) {
+        if( resultCode != 0 || opCode != QUERY ) {
+            return 0;
+        }
+        boolean groupName = (( src[srcIndex] & 0x80 ) == 0x80 ) ? true : false;
+        int nodeType = ( src[srcIndex] & 0x60 ) >> 5;
+        srcIndex += 2;
+        int address = readInt4( src, srcIndex );
+        addrEntry = new NbtAddress( recordName, address, groupName, nodeType );
+        return 6;
+    }
+    public String toString() {
+        return new String( "NameQueryResponse[" +
+            super.toString() +
+            ",addrEntry=" + addrEntry + "]" );
+    }
 }
index f763ef1..78f59db 100644 (file)
@@ -24,345 +24,353 @@ import java.net.DatagramPacket;
 import java.net.UnknownHostException;
 import java.io.IOException;
 import java.io.InterruptedIOException;
-import java.util.Hashtable;
+import java.util.HashMap;
 import java.util.StringTokenizer;
 import jcifs.Config;
+import jcifs.util.Hexdump;
+import jcifs.util.LogStream;
 
 class NameServiceClient implements Runnable {
 
     static final int DEFAULT_SO_TIMEOUT = 5000;
     static final int DEFAULT_RCV_BUF_SIZE = 576;
     static final int DEFAULT_SND_BUF_SIZE = 576;
-       static final int NAME_SERVICE_UDP_PORT = 137;
-       static final int DEFAULT_RETRY_COUNT = 2;
-       static final int DEFAULT_RETRY_TIMEOUT = 3000;
-
-       static final int RESOLVER_LMHOSTS = 1;
-       static final int RESOLVER_BCAST   = 2;
-       static final int RESOLVER_WINS    = 3;
-
-    InetAddress laddr, baddr, nbns;
-    int port, soTimeout, retryCount, retryTimeout, closeTimeout;
-    int snd_buf_size, rcv_buf_size;
-    byte[] snd_buf, rcv_buf;
-    DatagramSocket socket;
-    DatagramPacket in, out;
-       Hashtable responseTable;
-    Thread thread;
-       int nextNameTrnId;
-       Object socketLock;
-       int[] resolveOrder;
-
-       NameServiceClient() {
-               this( Config.getInt( "jcifs.netbios.lport", 0 ),
-                       Config.getInetAddress( "jcifs.netbios.laddr", null ));
-       }
-    NameServiceClient( int port, InetAddress laddr ) {
-        this.port = port;
+    static final int NAME_SERVICE_UDP_PORT = 137;
+    static final int DEFAULT_RETRY_COUNT = 2;
+    static final int DEFAULT_RETRY_TIMEOUT = 3000;
+
+    static final int RESOLVER_LMHOSTS = 1;
+    static final int RESOLVER_BCAST   = 2;
+    static final int RESOLVER_WINS    = 3;
+
+    private static final int SND_BUF_SIZE = Config.getInt( "jcifs.netbios.snd_buf_size", DEFAULT_SND_BUF_SIZE );
+    private static final int RCV_BUF_SIZE = Config.getInt( "jcifs.netbios.rcv_buf_size", DEFAULT_RCV_BUF_SIZE );
+    private static final int SO_TIMEOUT = Config.getInt( "jcifs.netbios.soTimeout", DEFAULT_SO_TIMEOUT );
+    private static final int RETRY_COUNT = Config.getInt( "jcifs.netbios.retryCount", DEFAULT_RETRY_COUNT );
+    private static final int RETRY_TIMEOUT = Config.getInt( "jcifs.netbios.retryTimeout", DEFAULT_RETRY_TIMEOUT);
+    private static final int LPORT = Config.getInt( "jcifs.netbios.lport", 0 );
+    private static final InetAddress LADDR = Config.getInetAddress( "jcifs.netbios.laddr", null );
+    private static final String RO = Config.getProperty( "jcifs.resolveOrder" );
+
+    private static LogStream log = LogStream.getInstance();
+
+    private final Object LOCK = new Object();
+
+    private int lport, closeTimeout;
+    private byte[] snd_buf, rcv_buf;
+    private DatagramSocket socket;
+    private DatagramPacket in, out;
+    private HashMap responseTable = new HashMap();
+    private Thread thread;
+    private int nextNameTrnId = 0;
+    private int[] resolveOrder;
+
+    InetAddress laddr, baddr;
+
+    NameServiceClient() {
+        this( LPORT, LADDR );
+    }
+    NameServiceClient( int lport, InetAddress laddr ) {
+        this.lport = lport;
         this.laddr = laddr;
 
-               try {
-                       baddr = Config.getInetAddress( "jcifs.netbios.baddr",
-                                               InetAddress.getByName( "255.255.255.255" ));
-               } catch( UnknownHostException uhe ) {
-               }
-
-               nbns = Config.getInetAddress( "jcifs.netbios.wins", null );
-        soTimeout = Config.getInt( "jcifs.netbios.soTimeout", DEFAULT_SO_TIMEOUT );
-               retryCount = Config.getInt( "jcifs.netbios.retryCount", DEFAULT_RETRY_COUNT );
-               retryTimeout = Config.getInt( "jcifs.netbios.retryTimeout", DEFAULT_RETRY_TIMEOUT);
-        rcv_buf_size = Config.getInt( "jcifs.netbios.rcv_buf_size", DEFAULT_RCV_BUF_SIZE );
-        snd_buf_size = Config.getInt( "jcifs.netbios.snd_buf_size", DEFAULT_SND_BUF_SIZE );
-        rcv_buf = new byte[rcv_buf_size];
-        snd_buf = new byte[snd_buf_size];
-        in  = new DatagramPacket( rcv_buf, rcv_buf_size );
-        out = new DatagramPacket( snd_buf, snd_buf_size, baddr, NAME_SERVICE_UDP_PORT );
-               responseTable = new Hashtable();
-               nextNameTrnId = 0;
-               socketLock = new Object();
-
-               String ro = Config.getProperty( "jcifs.resolveOrder" );
-               if( ro == null || ro.length() == 0 ) {
-
-                       /* No resolveOrder has been specified, use the
-                        * default which is LMHOSTS,WINS,BCAST,DNS or just
-                        * LMHOSTS,BCAST,DNS if jcifs.netbios.wins has not
-                        * been specified.
-                        */
-
-                       if( nbns == null ) {
-                               resolveOrder = new int[2];
-                               resolveOrder[0] = RESOLVER_LMHOSTS;
-                               resolveOrder[1] = RESOLVER_BCAST;
-                       } else {
-                               resolveOrder = new int[3];
-                               resolveOrder[0] = RESOLVER_LMHOSTS;
-                               resolveOrder[1] = RESOLVER_WINS;
-                               resolveOrder[2] = RESOLVER_BCAST;
-                       }
-               } else {
-                       int[] tmp = new int[3];
-                       StringTokenizer st = new StringTokenizer( ro, "," );
-                       int i = 0;
-                       while( st.hasMoreTokens() ) {
-                               String s = st.nextToken().trim();
-                               if( s.equalsIgnoreCase( "LMHOSTS" )) {
-                                       tmp[i++] = RESOLVER_LMHOSTS;
-                               } else if( s.equalsIgnoreCase( "WINS" )) {
-                                       if( nbns == null ) {
-                                               Log.println( Log.WARNINGS, "netbios name service warning",
-                                                               " resolveOrder specifies WINS however the " +
-                                                               "jcifs.netbios.wins property has not been set" );
-                                               continue;
-                                       }
-                                       tmp[i++] = RESOLVER_WINS;
-                               } else if( s.equalsIgnoreCase( "BCAST" )) {
-                                       tmp[i++] = RESOLVER_BCAST;
-                               } else if( s.equalsIgnoreCase( "DNS" )) {
-                                       ; // skip
-                               } else {
-                                       Log.println( Log.WARNINGS, "netbios name service warning",
-                                                               "unknown resolver method: " + s );
-                               }
-                       }
-                       resolveOrder = new int[i];
-                       System.arraycopy( tmp, 0, resolveOrder, 0, i );
-               }
+        try {
+            baddr = Config.getInetAddress( "jcifs.netbios.baddr",
+                        InetAddress.getByName( "255.255.255.255" ));
+        } catch( UnknownHostException uhe ) {
+        }
+
+        snd_buf = new byte[SND_BUF_SIZE];
+        rcv_buf = new byte[RCV_BUF_SIZE];
+        out = new DatagramPacket( snd_buf, SND_BUF_SIZE, baddr, NAME_SERVICE_UDP_PORT );
+        in  = new DatagramPacket( rcv_buf, RCV_BUF_SIZE );
+
+        if( RO == null || RO.length() == 0 ) {
+
+            /* No resolveOrder has been specified, use the
+             * default which is LMHOSTS,WINS,BCAST,DNS or just
+             * LMHOSTS,BCAST,DNS if jcifs.netbios.wins has not
+             * been specified.
+             */
+
+            if( NbtAddress.getNBNSAddress() == null ) {
+                resolveOrder = new int[2];
+                resolveOrder[0] = RESOLVER_LMHOSTS;
+                resolveOrder[1] = RESOLVER_BCAST;
+            } else {
+                resolveOrder = new int[3];
+                resolveOrder[0] = RESOLVER_LMHOSTS;
+                resolveOrder[1] = RESOLVER_WINS;
+                resolveOrder[2] = RESOLVER_BCAST;
+            }
+        } else {
+            int[] tmp = new int[3];
+            StringTokenizer st = new StringTokenizer( RO, "," );
+            int i = 0;
+            while( st.hasMoreTokens() ) {
+                String s = st.nextToken().trim();
+                if( s.equalsIgnoreCase( "LMHOSTS" )) {
+                    tmp[i++] = RESOLVER_LMHOSTS;
+                } else if( s.equalsIgnoreCase( "WINS" )) {
+                    if( NbtAddress.getNBNSAddress() == null ) {
+                        if( log.level > 1 ) {
+                            log.println( "NetBIOS resolveOrder specifies WINS however the " +
+                                    "jcifs.netbios.wins property has not been set" );
+                        }
+                        continue;
+                    }
+                    tmp[i++] = RESOLVER_WINS;
+                } else if( s.equalsIgnoreCase( "BCAST" )) {
+                    tmp[i++] = RESOLVER_BCAST;
+                } else if( s.equalsIgnoreCase( "DNS" )) {
+                    ; // skip
+                } else if( log.level > 1 ) {
+                    log.println( "unknown resolver method: " + s );
+                }
+            }
+            resolveOrder = new int[i];
+            System.arraycopy( tmp, 0, resolveOrder, 0, i );
+        }
     }
 
-       int getNextNameTrnId() {
-               if(( ++nextNameTrnId & 0xFFFF ) == 0 ) {
-                       nextNameTrnId = 1;
-               }
-               return nextNameTrnId;
-       }
+    int getNextNameTrnId() {
+        if(( ++nextNameTrnId & 0xFFFF ) == 0 ) {
+            nextNameTrnId = 1;
+        }
+        return nextNameTrnId;
+    }
     void ensureOpen( int timeout ) throws IOException {
-               closeTimeout = 0;
-               if( soTimeout != 0 ) {
-                       closeTimeout = Math.max( soTimeout, timeout );
-               }
-               // If socket is still good, the new closeTimeout will
-               // be ignored; see tryClose comment.
+        closeTimeout = 0;
+        if( SO_TIMEOUT != 0 ) {
+            closeTimeout = Math.max( SO_TIMEOUT, timeout );
+        }
+        // If socket is still good, the new closeTimeout will
+        // be ignored; see tryClose comment.
         if( socket == null ) {
-               socket = new DatagramSocket( port, laddr );
-               thread = new Thread( this, "JCIFS-NameServiceClient" );
-                       thread.setDaemon( true );
-               thread.start();
-               }
+            socket = new DatagramSocket( lport, laddr );
+            thread = new Thread( this, "JCIFS-NameServiceClient" );
+            thread.setDaemon( true );
+            thread.start();
+        }
     }
     void tryClose() {
-               synchronized( socketLock ) {
-
-                       /* Yes, there is the potential to drop packets
-                        * because we might close the socket during a
-                        * request. However the chances are slim and the
-                        * retry code should ensure the overall request
-                        * is serviced. The alternative complicates things
-                        * more than I think is worth it.
-                        */
-
-               if( socket != null ) {
-                       socket.close();
-                       socket = null;
-               }
-               thread = null;
-                       responseTable.clear();
-               }
+        synchronized( LOCK ) {
+
+            /* Yes, there is the potential to drop packets
+             * because we might close the socket during a
+             * request. However the chances are slim and the
+             * retry code should ensure the overall request
+             * is serviced. The alternative complicates things
+             * more than I think is worth it.
+             */
+
+            if( socket != null ) {
+                socket.close();
+                socket = null;
+            }
+            thread = null;
+            responseTable.clear();
+        }
     }
     public void run() {
-               int nameTrnId;
-               NameServicePacket response;
+        int nameTrnId;
+        NameServicePacket response;
 
         while( thread == Thread.currentThread() ) {
-                       in.setLength( rcv_buf_size );
-               try {
-                       socket.setSoTimeout( closeTimeout );
-               socket.receive( in );
-               } catch( IOException ioe ) {
-                               tryClose();
-                               break;
-               }
-
-                       Log.println( Log.DEBUGGING, "nbt name service debugging",
-                                                                                               " new data read from socket" );
-
-                       nameTrnId = NameServicePacket.readNameTrnId( rcv_buf, 0 );
-                       response = (NameServicePacket)responseTable.get( new Integer( nameTrnId ));
-                       if( response == null || response.received ) {
-                               continue;
-                       }
-                       synchronized( response ) {
-                               response.readWireFormat( rcv_buf, 0 );
-                               response.received = true;
-
-                               Log.printPacketData( "nbt name service packet receviced", response );
-                               Log.printHexDump( "datagram packet received from: " +
-                                               in.getAddress().getHostAddress(), rcv_buf, 0, in.getLength() );
-
-                               response.notify();
-                       }
+            in.setLength( RCV_BUF_SIZE );
+            try {
+                socket.setSoTimeout( closeTimeout );
+                socket.receive( in );
+            } catch( IOException ioe ) {
+                tryClose();
+                break;
+            }
+
+            if( log.level > 2 )
+                log.println( "NetBIOS: new data read from socket" );
+
+            nameTrnId = NameServicePacket.readNameTrnId( rcv_buf, 0 );
+            response = (NameServicePacket)responseTable.get( new Integer( nameTrnId ));
+            if( response == null || response.received ) {
+                continue;
+            }
+            synchronized( response ) {
+                response.readWireFormat( rcv_buf, 0 );
+                response.received = true;
+
+                if( log.level > 2 ) {
+                    log.println( response );
+                    Hexdump.hexdump( log, rcv_buf, 0, in.getLength() );
+                }
+
+                response.notify();
+            }
         }
     }
     void send( NameServicePacket request, NameServicePacket response,
-                                                                                       int timeout ) throws IOException {
-               Integer nid = null;
-
-               synchronized( response ) {
-                       try {
-                               synchronized( socketLock ) {
-                                       request.nameTrnId = getNextNameTrnId();
-                                       nid = new Integer( request.nameTrnId );
-
-                               out.setAddress( request.addr );
-                               out.setLength( request.writeWireFormat( snd_buf, 0 ));
-                                       response.received = false;
-
-                                       responseTable.put( nid, response );
-                               ensureOpen( timeout + 1000 );
-                           socket.send( out );
-
-                                       Log.printPacketData( "nbt name service packet sent", request );
-                                       Log.printHexDump( "datagram packet sent to: " +
-                                                               out.getAddress().getHostAddress(), snd_buf, 0, out.getLength() );
-                               }
-
-                               response.wait( timeout );
-
-                       } catch( InterruptedException ie ) {
-                       } finally {
-                               responseTable.remove( nid );
-                       }
-               }
+                                            int timeout ) throws IOException {
+        Integer nid = null;
+
+        synchronized( response ) {
+            try {
+                synchronized( LOCK ) {
+                    request.nameTrnId = getNextNameTrnId();
+                    nid = new Integer( request.nameTrnId );
+
+                    out.setAddress( request.addr );
+                    out.setLength( request.writeWireFormat( snd_buf, 0 ));
+                    response.received = false;
+
+                    responseTable.put( nid, response );
+                    ensureOpen( timeout + 1000 );
+                    socket.send( out );
+
+                    if( log.level > 2 ) {
+                        log.println( request );
+                        Hexdump.hexdump( log, snd_buf, 0, out.getLength() );
+                    }
+                }
+
+                response.wait( timeout );
+
+            } catch( InterruptedException ie ) {
+            } finally {
+                responseTable.remove( nid );
+            }
+        }
     }
 
-       NbtAddress getByName( Name name, InetAddress addr )
-                                                                                       throws UnknownHostException {
-               int n;
-               NameQueryRequest request = new NameQueryRequest( name );
-               NameQueryResponse response = new NameQueryResponse();
-
-               if( addr != null ) { /* UniAddress calls always use this
-                                                         * because it specifies addr
-                                                         */
-                       request.addr = addr; /* if addr ends with 255 flag it bcast */
-                       request.isBroadcast = (addr.getAddress()[3] == (byte)0xFF);
-
-                       n = retryCount;
-                       do {
-                               try {
-                                       send( request, response, retryTimeout );
-                               } catch( IOException ioe ) {
-                                       Log.printStackTrace( "nbt name service send:", ioe );
-                                       throw new UnknownHostException( ioe.getMessage() );
-                               }
-
-                               if( response.received && response.resultCode == 0 ) {
-                                       response.addrEntry.hostName.srcHashCode = addr.hashCode();
-                                       return response.addrEntry;
-                               }
-                       } while( --n > 0 && request.isBroadcast );
-
-                       throw new UnknownHostException( name.toString() );
-               }
-
-               /* If a target address to query was not specified explicitly
-                * with the addr parameter we fall into this resolveOrder routine.
-                */
-
-               for( int i = 0; i < resolveOrder.length; i++ ) {
-                       try {
-                               switch( resolveOrder[i] ) {
-                                       case RESOLVER_LMHOSTS:
-                                               NbtAddress ans = Lmhosts.getByName( name );
-                                               if( ans != null ) {
-                                                       ans.hostName.srcHashCode = 0; // just has to be different
-                                                                                                                 // from other methods
-                                                       return ans;
-                                               }
-                                               break;
-                                       case RESOLVER_WINS:
-                                       case RESOLVER_BCAST:
-                                               if( resolveOrder[i] == RESOLVER_WINS &&
-                                                               name.name != NbtAddress.MASTER_BROWSER_NAME &&
-                                                               name.hexCode != 0x1d ) {
-                                                       request.addr = nbns;
-                                                       request.isBroadcast = false;
-                                               } else {
-                                                       request.addr = baddr;
-                                                       request.isBroadcast = true;
-                                               }
-
-                                               n = retryCount;
-                                               while( n-- > 0 ) {
-                                                       try {
-                                                               send( request, response, retryTimeout );
-                                                       } catch( IOException ioe ) {
-                                                               Log.printStackTrace( "nbt name service send:", ioe );
-                                                               throw new UnknownHostException( ioe.getMessage() );
-                                                       }
-                                                       if( response.received && response.resultCode == 0 ) {
+    NbtAddress getByName( Name name, InetAddress addr )
+                                            throws UnknownHostException {
+        int n;
+        NameQueryRequest request = new NameQueryRequest( name );
+        NameQueryResponse response = new NameQueryResponse();
+
+        if( addr != null ) { /* UniAddress calls always use this
+                              * because it specifies addr
+                              */
+            request.addr = addr; /* if addr ends with 255 flag it bcast */
+            request.isBroadcast = (addr.getAddress()[3] == (byte)0xFF);
+
+            n = RETRY_COUNT;
+            do {
+                try {
+                    send( request, response, RETRY_TIMEOUT );
+                } catch( IOException ioe ) {
+                    if( log.level > 1 )
+                        ioe.printStackTrace( log );
+                    throw new UnknownHostException( name.name );
+                }
+
+                if( response.received && response.resultCode == 0 ) {
+                    response.addrEntry.hostName.srcHashCode = addr.hashCode();
+                    return response.addrEntry;
+                }
+            } while( --n > 0 && request.isBroadcast );
+
+            throw new UnknownHostException( name.name );
+        }
+
+        /* If a target address to query was not specified explicitly
+         * with the addr parameter we fall into this resolveOrder routine.
+         */
+
+        for( int i = 0; i < resolveOrder.length; i++ ) {
+            try {
+                switch( resolveOrder[i] ) {
+                    case RESOLVER_LMHOSTS:
+                        NbtAddress ans = Lmhosts.getByName( name );
+                        if( ans != null ) {
+                            ans.hostName.srcHashCode = 0; // just has to be different
+                                                          // from other methods
+                            return ans;
+                        }
+                        break;
+                    case RESOLVER_WINS:
+                    case RESOLVER_BCAST:
+                        if( resolveOrder[i] == RESOLVER_WINS &&
+                                name.name != NbtAddress.MASTER_BROWSER_NAME &&
+                                name.hexCode != 0x1d ) {
+                            request.addr = NbtAddress.getNBNSAddress();
+                            request.isBroadcast = false;
+                        } else {
+                            request.addr = baddr;
+                            request.isBroadcast = true;
+                        }
+
+                        n = RETRY_COUNT;
+                        while( n-- > 0 ) {
+                            try {
+                                send( request, response, RETRY_TIMEOUT );
+                            } catch( IOException ioe ) {
+                                if( log.level > 1 )
+                                    ioe.printStackTrace( log );
+                                throw new UnknownHostException( name.name );
+                            }
+                            if( response.received && response.resultCode == 0 ) {
 
 /* Before we return, in anticipation of this address being cached we must
  * augment the addresses name's hashCode to distinguish those resolved by
  * Lmhosts, WINS, or BCAST. Otherwise a failed query from say WINS would
  * get pulled out of the cache for a BCAST on the same name.
  */
-                                                               response.addrEntry.hostName.srcHashCode =
-                                                                                                               request.addr.hashCode();
-                                                               return response.addrEntry;
-                                                       } else if( resolveOrder[i] == RESOLVER_WINS ) {
-                                                               /* If WINS reports negative, no point in retry
-                                                                */
-                                                               break;
-                                                       }
-                                               }
-                                               break;
-                               }
-                       } catch( IOException ioe ) {
-                       }
-               }
-               throw new UnknownHostException( name.name );
-       }
-       NbtAddress[] getNodeStatus( NbtAddress addr ) throws UnknownHostException {
-               int n, srcHashCode;
-               NodeStatusRequest request;
-               NodeStatusResponse response;
-
-               response = new NodeStatusResponse( addr );
-               request = new NodeStatusRequest(
-                                                       new Name( NbtAddress.ANY_HOSTS_NAME, 0x00, null));
-               request.addr = addr.getInetAddress();
-
-               n = retryCount;
-               while( n-- > 0 ) {
-                       try {
-                               send( request, response, retryTimeout );
-                       } catch( IOException ioe ) {
-                               Log.printStackTrace( "nbt name service send:", ioe );
-                               throw new UnknownHostException( ioe.getMessage() );
-                       }
-                       if( response.received && response.resultCode == 0 ) {
-
-               /* For name queries resolved by different sources (e.g. WINS,
-                * BCAST, Node Status) we need to augment the hashcode generated
-                * for the addresses hostname or failed lookups for one type will
-                * be cached and cause other types to fail even though they may
-                * not be the authority for the name. For example, if a WINS lookup
-                * for FOO fails and caches unknownAddress for FOO, a subsequent
-                * lookup for FOO using BCAST should not fail because of that
-                * name cached from WINS.
-                *
-                * So, here we apply the source addresses hashCode to each name to
-                * make them specific to who resolved the name.
-                */
-
-                               srcHashCode = request.addr.hashCode();
-                               for( int i = 0; i < response.addressArray.length; i++ ) {
-                                       response.addressArray[i].hostName.srcHashCode = srcHashCode;
-                               }
-                               return response.addressArray;
-                       }
-               }
-               throw new UnknownHostException( addr.hostName.name );
-       }
+                                response.addrEntry.hostName.srcHashCode =
+                                                        request.addr.hashCode();
+                                return response.addrEntry;
+                            } else if( resolveOrder[i] == RESOLVER_WINS ) {
+                                /* If WINS reports negative, no point in retry
+                                 */
+                                break;
+                            }
+                        }
+                        break;
+                }
+            } catch( IOException ioe ) {
+            }
+        }
+        throw new UnknownHostException( name.name );
+    }
+    NbtAddress[] getNodeStatus( NbtAddress addr ) throws UnknownHostException {
+        int n, srcHashCode;
+        NodeStatusRequest request;
+        NodeStatusResponse response;
+
+        response = new NodeStatusResponse( addr );
+        request = new NodeStatusRequest(
+                            new Name( NbtAddress.ANY_HOSTS_NAME, 0x00, null));
+        request.addr = addr.getInetAddress();
+
+        n = RETRY_COUNT;
+        while( n-- > 0 ) {
+            try {
+                send( request, response, RETRY_TIMEOUT );
+            } catch( IOException ioe ) {
+                if( log.level > 1 )
+                    ioe.printStackTrace( log );
+                throw new UnknownHostException( addr.toString() );
+            }
+            if( response.received && response.resultCode == 0 ) {
+
+        /* For name queries resolved by different sources (e.g. WINS,
+         * BCAST, Node Status) we need to augment the hashcode generated
+         * for the addresses hostname or failed lookups for one type will
+         * be cached and cause other types to fail even though they may
+         * not be the authority for the name. For example, if a WINS lookup
+         * for FOO fails and caches unknownAddress for FOO, a subsequent
+         * lookup for FOO using BCAST should not fail because of that
+         * name cached from WINS.
+         *
+         * So, here we apply the source addresses hashCode to each name to
+         * make them specific to who resolved the name.
+         */
+
+                srcHashCode = request.addr.hashCode();
+                for( int i = 0; i < response.addressArray.length; i++ ) {
+                    response.addressArray[i].hostName.srcHashCode = srcHashCode;
+                }
+                return response.addressArray;
+            }
+        }
+        throw new UnknownHostException( addr.hostName.name );
+    }
 }
index 3d4d2cf..ed407da 100644 (file)
 package jcifs.netbios;
 
 import java.net.InetAddress;
+import jcifs.util.Hexdump;
 
 abstract class NameServicePacket {
 
-       // opcode
-       static final int QUERY = 0;
-       static final int WACK = 7;
+    private static final int LOOKUP_RESP_LIMIT = jcifs.Config.getInt( "jcifs.netbios.lookupRespLimit", 5 );
 
-       // rcode
-       static final int FMT_ERR = 0x1;
-       static final int SRV_ERR = 0x2;
-       static final int IMP_ERR = 0x4;
-       static final int RFS_ERR = 0x5;
-       static final int ACT_ERR = 0x6;
-       static final int CFT_ERR = 0x7;
+    private static int addrIndex = 0;
 
-       // type/class
-       static final int NB_IN     = 0x00200001;
-       static final int NBSTAT_IN = 0x00210001;
-       static final int NB        = 0x0020;
-       static final int NBSTAT    = 0x0021;
-       static final int IN        = 0x0001;
-       static final int A         = 0x0001;
-       static final int NS        = 0x0002;
-       static final int NULL      = 0x000a;
+    // opcode
+    static final int QUERY = 0;
+    static final int WACK = 7;
 
-       static final int HEADER_LENGTH = 12;
+    // rcode
+    static final int FMT_ERR = 0x1;
+    static final int SRV_ERR = 0x2;
+    static final int IMP_ERR = 0x4;
+    static final int RFS_ERR = 0x5;
+    static final int ACT_ERR = 0x6;
+    static final int CFT_ERR = 0x7;
 
-       // header field offsets
-       static final int OPCODE_OFFSET = 2;
-       static final int QUESTION_OFFSET = 4;
-       static final int ANSWER_OFFSET = 6;
-       static final int AUTHORITY_OFFSET = 8;
-       static final int ADDITIONAL_OFFSET = 10;
+    // type/class
+    static final int NB_IN     = 0x00200001;
+    static final int NBSTAT_IN = 0x00210001;
+    static final int NB        = 0x0020;
+    static final int NBSTAT    = 0x0021;
+    static final int IN        = 0x0001;
+    static final int A         = 0x0001;
+    static final int NS        = 0x0002;
+    static final int NULL      = 0x000a;
 
-       static final int LOOKUP_RESP_LIMIT = jcifs.Config.getInt( "jcifs.netbios.lookupRespLimit", 5 );
+    static final int HEADER_LENGTH = 12;
 
-       static int addrIndex = 0;
+    // header field offsets
+    static final int OPCODE_OFFSET = 2;
+    static final int QUESTION_OFFSET = 4;
+    static final int ANSWER_OFFSET = 6;
+    static final int AUTHORITY_OFFSET = 8;
+    static final int ADDITIONAL_OFFSET = 10;
 
-       static void writeInt2( int val, byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = (byte)(( val >> 8 ) & 0xFF );
-               dst[dstIndex] = (byte)( val & 0xFF );
-       }
-       static void writeInt4( int val, byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = (byte)(( val >> 24 ) & 0xFF );
-               dst[dstIndex++] = (byte)(( val >> 16 ) & 0xFF );
-               dst[dstIndex++] = (byte)(( val >> 8 ) & 0xFF );
-               dst[dstIndex] = (byte)( val & 0xFF );
-       }
-       static int readInt2( byte[] src, int srcIndex ) {
-               return (( src[srcIndex] & 0xFF ) << 8 ) +
-                               ( src[srcIndex + 1] & 0xFF );
-       }
-       static int readInt4( byte[] src, int srcIndex ) {
-               return (( src[srcIndex] & 0xFF ) << 24 ) +
-                               (( src[srcIndex + 1] & 0xFF ) << 16 ) +
-                               (( src[srcIndex + 2] & 0xFF ) << 8 ) +
-                               ( src[srcIndex + 3] & 0xFF );
-       }
+    static void writeInt2( int val, byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = (byte)(( val >> 8 ) & 0xFF );
+        dst[dstIndex] = (byte)( val & 0xFF );
+    }
+    static void writeInt4( int val, byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = (byte)(( val >> 24 ) & 0xFF );
+        dst[dstIndex++] = (byte)(( val >> 16 ) & 0xFF );
+        dst[dstIndex++] = (byte)(( val >> 8 ) & 0xFF );
+        dst[dstIndex] = (byte)( val & 0xFF );
+    }
+    static int readInt2( byte[] src, int srcIndex ) {
+        return (( src[srcIndex] & 0xFF ) << 8 ) +
+                ( src[srcIndex + 1] & 0xFF );
+    }
+    static int readInt4( byte[] src, int srcIndex ) {
+        return (( src[srcIndex] & 0xFF ) << 24 ) +
+                (( src[srcIndex + 1] & 0xFF ) << 16 ) +
+                (( src[srcIndex + 2] & 0xFF ) << 8 ) +
+                ( src[srcIndex + 3] & 0xFF );
+    }
 
-       static int readNameTrnId( byte[] src, int srcIndex ) {
-               return readInt2( src, srcIndex );
-       }
+    static int readNameTrnId( byte[] src, int srcIndex ) {
+        return readInt2( src, srcIndex );
+    }
 
-       int nameTrnId;
+    int nameTrnId;
 
-       int opCode,
-                       resultCode,
-                       questionCount,
-                       answerCount,
-                       authorityCount,
-                       additionalCount;
-       boolean received,
-                       isResponse,
-                       isAuthAnswer,
-                       isTruncated,
-                       isRecurDesired,
-                       isRecurAvailable,
-                       isBroadcast;
+    int opCode,
+            resultCode,
+            questionCount,
+            answerCount,
+            authorityCount,
+            additionalCount;
+    boolean received,
+            isResponse,
+            isAuthAnswer,
+            isTruncated,
+            isRecurDesired,
+            isRecurAvailable,
+            isBroadcast;
 
-       Name questionName;
-       Name recordName;
+    Name questionName;
+    Name recordName;
 
-       int questionType,
-                       questionClass,
-                       recordType,
-                       recordClass,
-                       ttl,
-                       rDataLength;
+    int questionType,
+            questionClass,
+            recordType,
+            recordClass,
+            ttl,
+            rDataLength;
 
-       InetAddress addr;
+    InetAddress addr;
 
-       NameServicePacket() {
-               isRecurDesired = true;
-               isBroadcast = true;
-               questionCount = 1;
-               questionClass = IN;
-       }
+    NameServicePacket() {
+        isRecurDesired = true;
+        isBroadcast = true;
+        questionCount = 1;
+        questionClass = IN;
+    }
 
-       int writeWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-               dstIndex += writeHeaderWireFormat( dst, dstIndex );
-               dstIndex += writeBodyWireFormat( dst, dstIndex );
-               return dstIndex - start;
-       }
-       int readWireFormat( byte[] src, int srcIndex ) {
-               int start = srcIndex;
-               srcIndex += readHeaderWireFormat( src, srcIndex );
-               srcIndex += readBodyWireFormat( src, srcIndex );
-               return srcIndex - start;
-       }
+    int writeWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+        dstIndex += writeHeaderWireFormat( dst, dstIndex );
+        dstIndex += writeBodyWireFormat( dst, dstIndex );
+        return dstIndex - start;
+    }
+    int readWireFormat( byte[] src, int srcIndex ) {
+        int start = srcIndex;
+        srcIndex += readHeaderWireFormat( src, srcIndex );
+        srcIndex += readBodyWireFormat( src, srcIndex );
+        return srcIndex - start;
+    }
 
-       int writeHeaderWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-               writeInt2( nameTrnId, dst, dstIndex );
-               dst[dstIndex + OPCODE_OFFSET] = (byte)(( isResponse ? 0x80 : 0x00 ) +
-                                               (( opCode << 3 ) & 0x78 ) +
-                                               ( isAuthAnswer ? 0x04 : 0x00 ) +
-                                               ( isTruncated ? 0x02 : 0x00 ) +
-                                               ( isRecurDesired ? 0x01 : 0x00 ));
-               dst[dstIndex + OPCODE_OFFSET + 1] = (byte)(( isRecurAvailable ? 0x80 : 0x00 ) +
-                                               ( isBroadcast ? 0x10 : 0x00 ) +
-                                               ( resultCode & 0x0F ));
-               writeInt2( questionCount, dst, start + QUESTION_OFFSET );
-               writeInt2( answerCount, dst, start + ANSWER_OFFSET );
-               writeInt2( authorityCount, dst, start + AUTHORITY_OFFSET );
-               writeInt2( additionalCount, dst, start + ADDITIONAL_OFFSET );
-               return HEADER_LENGTH;
-       }
-       int readHeaderWireFormat( byte[] src, int srcIndex ) {
-               nameTrnId       = readInt2( src, srcIndex );
+    int writeHeaderWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+        writeInt2( nameTrnId, dst, dstIndex );
+        dst[dstIndex + OPCODE_OFFSET] = (byte)(( isResponse ? 0x80 : 0x00 ) +
+                        (( opCode << 3 ) & 0x78 ) +
+                        ( isAuthAnswer ? 0x04 : 0x00 ) +
+                        ( isTruncated ? 0x02 : 0x00 ) +
+                        ( isRecurDesired ? 0x01 : 0x00 ));
+        dst[dstIndex + OPCODE_OFFSET + 1] = (byte)(( isRecurAvailable ? 0x80 : 0x00 ) +
+                        ( isBroadcast ? 0x10 : 0x00 ) +
+                        ( resultCode & 0x0F ));
+        writeInt2( questionCount, dst, start + QUESTION_OFFSET );
+        writeInt2( answerCount, dst, start + ANSWER_OFFSET );
+        writeInt2( authorityCount, dst, start + AUTHORITY_OFFSET );
+        writeInt2( additionalCount, dst, start + ADDITIONAL_OFFSET );
+        return HEADER_LENGTH;
+    }
+    int readHeaderWireFormat( byte[] src, int srcIndex ) {
+        nameTrnId       = readInt2( src, srcIndex );
         isResponse      = (( src[srcIndex + OPCODE_OFFSET] & 0x80 ) == 0 ) ? false : true;
-               opCode          = ( src[srcIndex + OPCODE_OFFSET] & 0x78 ) >> 3;
-               isAuthAnswer    = (( src[srcIndex + OPCODE_OFFSET] & 0x04 ) == 0 ) ? false : true;
-               isTruncated     = (( src[srcIndex + OPCODE_OFFSET] & 0x02 ) == 0 ) ? false : true;
+        opCode          = ( src[srcIndex + OPCODE_OFFSET] & 0x78 ) >> 3;
+        isAuthAnswer    = (( src[srcIndex + OPCODE_OFFSET] & 0x04 ) == 0 ) ? false : true;
+        isTruncated     = (( src[srcIndex + OPCODE_OFFSET] & 0x02 ) == 0 ) ? false : true;
         isRecurDesired  = (( src[srcIndex + OPCODE_OFFSET] & 0x01 ) == 0 ) ? false : true;
         isRecurAvailable =
-                                               (( src[srcIndex + OPCODE_OFFSET + 1] & 0x80 ) == 0 ) ? false : true;
+                        (( src[srcIndex + OPCODE_OFFSET + 1] & 0x80 ) == 0 ) ? false : true;
         isBroadcast     = (( src[srcIndex + OPCODE_OFFSET + 1] & 0x10 ) == 0 ) ? false : true;
         resultCode      = src[srcIndex + OPCODE_OFFSET + 1] & 0x0F;
-               questionCount   = readInt2( src, srcIndex + QUESTION_OFFSET );
-               answerCount     = readInt2( src, srcIndex + ANSWER_OFFSET );
-               authorityCount  = readInt2( src, srcIndex + AUTHORITY_OFFSET );
-               additionalCount = readInt2( src, srcIndex + ADDITIONAL_OFFSET );
-               return HEADER_LENGTH;
-       }
-       int writeQuestionSectionWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-               dstIndex += questionName.writeWireFormat( dst, dstIndex );
-               writeInt2( questionType, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( questionClass, dst, dstIndex );
-               dstIndex += 2;
-               return dstIndex - start;
-       }
-       int readQuestionSectionWireFormat( byte[] src, int srcIndex ) {
-               int start = srcIndex;
-               srcIndex += questionName.readWireFormat( src, srcIndex );
-               questionType = readInt2( src, srcIndex );
-               srcIndex += 2;
-               questionClass = readInt2( src, srcIndex );
-               srcIndex += 2;
-               return srcIndex - start;
-       }
-       int writeResourceRecordWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-               if( recordName == questionName ) {
-                       dst[dstIndex++] = (byte)0xC0; // label string pointer to
-                       dst[dstIndex++] = (byte)0x0C; // questionName (offset 12)
-               } else {
-                       dstIndex += recordName.writeWireFormat( dst, dstIndex );
-               }
-               writeInt2( recordType, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( recordClass, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( ttl, dst, dstIndex );
-               dstIndex += 4;
-               rDataLength = writeRDataWireFormat( dst, dstIndex + 2 );
-               writeInt2( rDataLength, dst, dstIndex );
-               dstIndex += 2 + rDataLength;
-               return dstIndex - start;
-       }
-       int readResourceRecordWireFormat( byte[] src, int srcIndex ) {
-               int start = srcIndex;
-               int end;
+        questionCount   = readInt2( src, srcIndex + QUESTION_OFFSET );
+        answerCount     = readInt2( src, srcIndex + ANSWER_OFFSET );
+        authorityCount  = readInt2( src, srcIndex + AUTHORITY_OFFSET );
+        additionalCount = readInt2( src, srcIndex + ADDITIONAL_OFFSET );
+        return HEADER_LENGTH;
+    }
+    int writeQuestionSectionWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+        dstIndex += questionName.writeWireFormat( dst, dstIndex );
+        writeInt2( questionType, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( questionClass, dst, dstIndex );
+        dstIndex += 2;
+        return dstIndex - start;
+    }
+    int readQuestionSectionWireFormat( byte[] src, int srcIndex ) {
+        int start = srcIndex;
+        srcIndex += questionName.readWireFormat( src, srcIndex );
+        questionType = readInt2( src, srcIndex );
+        srcIndex += 2;
+        questionClass = readInt2( src, srcIndex );
+        srcIndex += 2;
+        return srcIndex - start;
+    }
+    int writeResourceRecordWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+        if( recordName == questionName ) {
+            dst[dstIndex++] = (byte)0xC0; // label string pointer to
+            dst[dstIndex++] = (byte)0x0C; // questionName (offset 12)
+        } else {
+            dstIndex += recordName.writeWireFormat( dst, dstIndex );
+        }
+        writeInt2( recordType, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( recordClass, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( ttl, dst, dstIndex );
+        dstIndex += 4;
+        rDataLength = writeRDataWireFormat( dst, dstIndex + 2 );
+        writeInt2( rDataLength, dst, dstIndex );
+        dstIndex += 2 + rDataLength;
+        return dstIndex - start;
+    }
+    int readResourceRecordWireFormat( byte[] src, int srcIndex ) {
+        int start = srcIndex;
+        int end;
 
-               if(( src[srcIndex] & 0xC0 ) == 0xC0 ) {
-                       recordName = questionName; // label string pointer to questionName
-                       srcIndex += 2;
-               } else {
-                       srcIndex += recordName.readWireFormat( src, srcIndex );
-               }
-               recordType = readInt2( src, srcIndex );
-               srcIndex += 2;
-               recordClass = readInt2( src, srcIndex );
-               srcIndex += 2;
-               ttl = readInt4( src, srcIndex );
-               srcIndex += 4;
-               rDataLength = readInt2( src, srcIndex );
-               srcIndex += 2;
+        if(( src[srcIndex] & 0xC0 ) == 0xC0 ) {
+            recordName = questionName; // label string pointer to questionName
+            srcIndex += 2;
+        } else {
+            srcIndex += recordName.readWireFormat( src, srcIndex );
+        }
+        recordType = readInt2( src, srcIndex );
+        srcIndex += 2;
+        recordClass = readInt2( src, srcIndex );
+        srcIndex += 2;
+        ttl = readInt4( src, srcIndex );
+        srcIndex += 4;
+        rDataLength = readInt2( src, srcIndex );
+        srcIndex += 2;
 
-               end = srcIndex + rDataLength;
-               for( int i = 0; srcIndex < end; i++ ) {
-                       srcIndex += readRDataWireFormat( src, srcIndex );
-                       if( i == addrIndex ) {
-                               addrIndex++;
-                               if( addrIndex == LOOKUP_RESP_LIMIT ) {
-                                       addrIndex = 0;
-                               }
-                               return end - start;
-                       }
-               }
-               addrIndex = 0;
+        end = srcIndex + rDataLength;
+        for( int i = 0; srcIndex < end; i++ ) {
+            srcIndex += readRDataWireFormat( src, srcIndex );
+            if( i == addrIndex ) {
+                addrIndex++;
+                if( addrIndex == LOOKUP_RESP_LIMIT ) {
+                    addrIndex = 0;
+                }
+                return end - start;
+            }
+        }
+        addrIndex = 0;
 
-               return srcIndex - start;
-       }
+        return srcIndex - start;
+    }
 
-       abstract int writeBodyWireFormat( byte[] dst, int dstIndex );
-       abstract int readBodyWireFormat( byte[] src, int srcIndex );
-       abstract int writeRDataWireFormat( byte[] dst, int dstIndex );
-       abstract int readRDataWireFormat( byte[] src, int srcIndex );
+    abstract int writeBodyWireFormat( byte[] dst, int dstIndex );
+    abstract int readBodyWireFormat( byte[] src, int srcIndex );
+    abstract int writeRDataWireFormat( byte[] dst, int dstIndex );
+    abstract int readRDataWireFormat( byte[] src, int srcIndex );
 
-       public String toString() {
-               String opCodeString,
-                               resultCodeString,
-                               questionTypeString,
-                               questionClassString,
-                               recordTypeString,
-                               recordClassString;
+    public String toString() {
+        String opCodeString,
+                resultCodeString,
+                questionTypeString,
+                questionClassString,
+                recordTypeString,
+                recordClassString;
 
-               switch( opCode ) {
-                       case QUERY:
-                               opCodeString = "QUERY";
-                               break;
-                       case WACK:
-                               opCodeString = "WACK";
-                               break;
-                       default:
-                               opCodeString = Integer.toString( opCode );
-               }
-               switch( resultCode ) {
-                       case FMT_ERR:
-                               resultCodeString = "FMT_ERR";
-                               break;
-                       case SRV_ERR:
-                               resultCodeString = "SRV_ERR";
-                               break;
-                       case IMP_ERR:
-                               resultCodeString = "IMP_ERR";
-                               break;
-                       case RFS_ERR:
-                               resultCodeString = "RFS_ERR";
-                               break;
-                       case ACT_ERR:
-                               resultCodeString = "ACT_ERR";
-                               break;
-                       case CFT_ERR:
-                               resultCodeString = "CFT_ERR";
-                               break;
-                       default:
-                               resultCodeString = "0x" + Log.getHexString( resultCode, 1 );
-               }
-               switch( questionType ) {
-                       case NB:
-                               questionTypeString = "NB";
-                       case NBSTAT:
-                               questionTypeString = "NBSTAT";
-                       default:
-                               questionTypeString = "0x" + Log.getHexString( questionType, 4 );
-               }
-               switch( recordType ) {
-                       case A:
-                               recordTypeString = "A";
-                               break;
-                       case NS:
-                               recordTypeString = "NS";
-                               break;
-                       case NULL:
-                               recordTypeString = "NULL";
-                               break;
-                       case NB:
-                               recordTypeString = "NB";
-                       case NBSTAT:
-                               recordTypeString = "NBSTAT";
-                       default:
-                               recordTypeString = "0x" + Log.getHexString( recordType, 4 );
-               }
+        switch( opCode ) {
+            case QUERY:
+                opCodeString = "QUERY";
+                break;
+            case WACK:
+                opCodeString = "WACK";
+                break;
+            default:
+                opCodeString = Integer.toString( opCode );
+        }
+        switch( resultCode ) {
+            case FMT_ERR:
+                resultCodeString = "FMT_ERR";
+                break;
+            case SRV_ERR:
+                resultCodeString = "SRV_ERR";
+                break;
+            case IMP_ERR:
+                resultCodeString = "IMP_ERR";
+                break;
+            case RFS_ERR:
+                resultCodeString = "RFS_ERR";
+                break;
+            case ACT_ERR:
+                resultCodeString = "ACT_ERR";
+                break;
+            case CFT_ERR:
+                resultCodeString = "CFT_ERR";
+                break;
+            default:
+                resultCodeString = "0x" + Hexdump.toHexString( resultCode, 1 );
+        }
+        switch( questionType ) {
+            case NB:
+                questionTypeString = "NB";
+            case NBSTAT:
+                questionTypeString = "NBSTAT";
+            default:
+                questionTypeString = "0x" + Hexdump.toHexString( questionType, 4 );
+        }
+        switch( recordType ) {
+            case A:
+                recordTypeString = "A";
+                break;
+            case NS:
+                recordTypeString = "NS";
+                break;
+            case NULL:
+                recordTypeString = "NULL";
+                break;
+            case NB:
+                recordTypeString = "NB";
+            case NBSTAT:
+                recordTypeString = "NBSTAT";
+            default:
+                recordTypeString = "0x" + Hexdump.toHexString( recordType, 4 );
+        }
 
-               return new String(
-                               "nameTrnId=" + nameTrnId +
-                               ",isResponse=" + isResponse +
-                               ",opCode=" + opCodeString +
-                               ",isAuthAnswer=" + isAuthAnswer +
-                               ",isTruncated=" + isTruncated +
-                               ",isRecurAvailable=" + isRecurAvailable +
-                               ",isRecurDesired=" + isRecurDesired +
-                               ",isBroadcast=" + isBroadcast +
-                               ",resultCode=" + resultCode +
-                               ",questionCount=" + questionCount +
-                               ",answerCount=" + answerCount +
-                               ",authorityCount=" + authorityCount +
-                               ",additionalCount=" + additionalCount +
-                               ",questionName=" + questionName +
-                               ",questionType=" + questionTypeString +
-                               ",questionClass=" + ( questionClass == IN ? "IN" :
-                                                       "0x" + Log.getHexString( questionClass, 4 )) +
-                               ",recordName=" + recordName +
-                               ",recordType=" + recordTypeString +
-                               ",recordClass=" + ( recordClass == IN ? "IN" :
-                                                       "0x" + Log.getHexString( recordClass, 4 )) +
-                               ",ttl=" + ttl +
-                               ",rDataLength=" + rDataLength );
-       }
+        return new String(
+                "nameTrnId=" + nameTrnId +
+                ",isResponse=" + isResponse +
+                ",opCode=" + opCodeString +
+                ",isAuthAnswer=" + isAuthAnswer +
+                ",isTruncated=" + isTruncated +
+                ",isRecurAvailable=" + isRecurAvailable +
+                ",isRecurDesired=" + isRecurDesired +
+                ",isBroadcast=" + isBroadcast +
+                ",resultCode=" + resultCode +
+                ",questionCount=" + questionCount +
+                ",answerCount=" + answerCount +
+                ",authorityCount=" + authorityCount +
+                ",additionalCount=" + additionalCount +
+                ",questionName=" + questionName +
+                ",questionType=" + questionTypeString +
+                ",questionClass=" + ( questionClass == IN ? "IN" :
+                            "0x" + Hexdump.toHexString( questionClass, 4 )) +
+                ",recordName=" + recordName +
+                ",recordType=" + recordTypeString +
+                ",recordClass=" + ( recordClass == IN ? "IN" :
+                            "0x" + Hexdump.toHexString( recordClass, 4 )) +
+                ",ttl=" + ttl +
+                ",rDataLength=" + rDataLength );
+    }
 }
 
index fdbc005..ffee207 100644 (file)
@@ -23,8 +23,9 @@ import java.net.UnknownHostException;
 import java.net.SocketException;
 import java.io.IOException;
 import java.io.UnsupportedEncodingException;
-import java.util.Hashtable;
+import java.util.HashMap;
 import jcifs.Config;
+import jcifs.util.Hexdump;
 
 /**
  * This class represents a NetBIOS over TCP/IP address. Under normal
@@ -83,14 +84,14 @@ public final class NbtAddress {
  * on a network querying a workgroup group name is the preferred method.
  */ 
 
-       static final String ANY_HOSTS_NAME = "*\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";
+    static final String ANY_HOSTS_NAME = "*\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";
 
 /** 
  * This is a special name for querying the master browser that serves the
  * list of hosts found in "Network Neighborhood".
  */ 
 
-       public static final String MASTER_BROWSER_NAME = "\u0001\u0002__MSBROWSE__\u0002";
+    public static final String MASTER_BROWSER_NAME = "\u0001\u0002__MSBROWSE__\u0002";
 
 /**
  * A special generic name specified when connecting to a host for which
@@ -129,154 +130,148 @@ public final class NbtAddress {
 
     public static final int H_NODE = 3;
 
-       static final int DEFAULT_CACHE_POLICY = 30;
-    static final int FOREVER = -1;
+    private static final InetAddress[] NBNS = Config.getInetAddressArray( "jcifs.netbios.wins", ",", new InetAddress[0] );
 
-    static int cachePolicy;
-    static Hashtable addressCache;
-    static Hashtable lookupTable;
-       static Name unknownName;
-    static NbtAddress unknownAddress;
-       static byte[] unknownMacAddress = new byte[] {
-                                               (byte)0x00, (byte)0x00, (byte)0x00,
-                                               (byte)0x00, (byte)0x00, (byte)0x00
-                                       };
+    /* Construct the shared static client object that will
+     * conduct all encoding and decoding of NetBIOS name service
+     * messages as well as socket IO in a synchronized fashon.
+     */
+
+    private static final NameServiceClient CLIENT = new NameServiceClient();
+
+    private static final int DEFAULT_CACHE_POLICY = 30;
+    private static final int CACHE_POLICY = Config.getInt( "jcifs.netbios.cachePolicy", DEFAULT_CACHE_POLICY );
+    private static final int FOREVER = -1;
+    private static int nbnsIndex = 0;
+
+    private static final HashMap ADDRESS_CACHE = new HashMap();
+    private static final HashMap LOOKUP_TABLE = new HashMap();
+
+    static final Name UNKNOWN_NAME = new Name( "0.0.0.0", 0x00, null );
+    static final NbtAddress UNKNOWN_ADDRESS = new NbtAddress( UNKNOWN_NAME, 0, false, B_NODE );
+    static final byte[] UNKNOWN_MAC_ADDRESS = new byte[] {
+        (byte)0x00, (byte)0x00, (byte)0x00,
+        (byte)0x00, (byte)0x00, (byte)0x00
+    };
 
     static final class CacheEntry {
-               Name hostName;
+        Name hostName;
         NbtAddress address;
         long expiration;
 
         CacheEntry( Name hostName, NbtAddress address, long expiration ) {
-                       this.hostName = hostName;
+            this.hostName = hostName;
             this.address = address;
             this.expiration = expiration;
         }
     }
 
-    static NameServiceClient client;
-       static NbtAddress localhost;
+    static NbtAddress localhost;
 
     static {
-               InetAddress localInetAddress;
-               String localHostname;
-               Name localName;
-
-       addressCache = new Hashtable();
-       lookupTable = new Hashtable();
-       cachePolicy = Config.getInt( "jcifs.netbios.cachePolicy", DEFAULT_CACHE_POLICY );
-
-               /* Construct the shared static client object that will
-                * conduct all encoding and decoding of NetBIOS name service
-                * messages as well as socket IO in a synchronized fashon.
-                */
-
-               client = new NameServiceClient();
-
-               /* Create an address to represent failed lookups and cache forever.
-                */
-
-        unknownName = new Name( "0.0.0.0", 0x00, null );
-        unknownAddress = new NbtAddress( unknownName, 0, false, B_NODE );
-        addressCache.put( unknownName,
-                                               new CacheEntry( unknownName, unknownAddress, FOREVER ));
-
-               /* Determine the InetAddress of the local interface
-                * if one was not specified.
-                */
-               localInetAddress = client.laddr;
-               if( localInetAddress == null ) {
-                       try {
-                               localInetAddress = InetAddress.getLocalHost();
-                       } catch( UnknownHostException uhe ) {
-                       }
-               }
-
-               /* If a local hostname was not provided a name like
-                * JCIFS34_172_A6 will be dynamically generated for the
-                * client. This is primarily (exclusively?) used as a
-                * CallingName during session establishment.
-                */
-               localHostname = Config.getProperty( "jcifs.netbios.hostname", null );
-               if( localHostname == null || localHostname.length() == 0 ) {
-                       byte[] addr = localInetAddress.getAddress();
-                       localHostname = "JCIFS" +
-                                       ( addr[2] & 0xFF ) + "_" +
-                                       ( addr[3] & 0xFF ) + "_" +
-                                       Name.toHexChars( (int)( Math.random() * (double)0xFF ));
-               }
-
-               /* Create an NbtAddress for the local interface with
-                * the name deduced above possibly with scope applied and
-                * cache it forever.
-                */
-               localName = new Name( localHostname, 0x00,
-                                                       Config.getProperty( "jcifs.netbios.scope", null ));
-               localhost = new NbtAddress( localName,
-                                                                       localInetAddress.hashCode(),
-                                                                       false,
-                                                                       B_NODE,
-                                                                       false, false, true, false,
-                                                                       unknownMacAddress );
-               cacheAddress( localName, localhost, FOREVER );
+        InetAddress localInetAddress;
+        String localHostname;
+        Name localName;
+
+        /* Create an address to represent failed lookups and cache forever.
+         */
+
+        ADDRESS_CACHE.put( UNKNOWN_NAME, new CacheEntry( UNKNOWN_NAME, UNKNOWN_ADDRESS, FOREVER ));
+
+        /* Determine the InetAddress of the local interface
+         * if one was not specified.
+         */
+        localInetAddress = CLIENT.laddr;
+        if( localInetAddress == null ) {
+            try {
+                localInetAddress = InetAddress.getLocalHost();
+            } catch( UnknownHostException uhe ) {
+            }
+        }
+
+        /* If a local hostname was not provided a name like
+         * JCIFS34_172_A6 will be dynamically generated for the
+         * client. This is primarily (exclusively?) used as a
+         * CallingName during session establishment.
+         */
+        localHostname = Config.getProperty( "jcifs.netbios.hostname", null );
+        if( localHostname == null || localHostname.length() == 0 ) {
+            byte[] addr = localInetAddress.getAddress();
+            localHostname = "JCIFS" +
+                    ( addr[2] & 0xFF ) + "_" +
+                    ( addr[3] & 0xFF ) + "_" +
+                    Hexdump.toHexString( (int)( Math.random() * (double)0xFF ), 2 );
+        }
+
+        /* Create an NbtAddress for the local interface with
+         * the name deduced above possibly with scope applied and
+         * cache it forever.
+         */
+        localName = new Name( localHostname, 0x00,
+                            Config.getProperty( "jcifs.netbios.scope", null ));
+        localhost = new NbtAddress( localName,
+                                    localInetAddress.hashCode(),
+                                    false,
+                                    B_NODE,
+                                    false, false, true, false,
+                                    UNKNOWN_MAC_ADDRESS );
+        cacheAddress( localName, localhost, FOREVER );
     }
 
     static void cacheAddress( Name hostName, NbtAddress addr ) {
-        if( cachePolicy == 0 ) {
+        if( CACHE_POLICY == 0 ) {
             return;
         }
         long expiration = -1;
-        if( cachePolicy != FOREVER ) {
-            expiration = System.currentTimeMillis() + cachePolicy * 1000;
+        if( CACHE_POLICY != FOREVER ) {
+            expiration = System.currentTimeMillis() + CACHE_POLICY * 1000;
         }
         cacheAddress( hostName, addr, expiration );
     }
     static void cacheAddress( Name hostName, NbtAddress addr, long expiration ) {
-        if( cachePolicy == 0 ) {
+        if( CACHE_POLICY == 0 ) {
             return;
         }
-        synchronized( addressCache ) {
-            CacheEntry entry = (CacheEntry)addressCache.get( hostName );
+        synchronized( ADDRESS_CACHE ) {
+            CacheEntry entry = (CacheEntry)ADDRESS_CACHE.get( hostName );
             if( entry == null ) {
                 entry = new CacheEntry( hostName, addr, expiration );
-                addressCache.put( hostName, entry );
+                ADDRESS_CACHE.put( hostName, entry );
             } else {
                 entry.address = addr;
                 entry.expiration = expiration;
             }
-            Log.printAddressCache( "name service address cache", addressCache );
         }
     }
     static void cacheAddressArray( NbtAddress[] addrs ) {
-        if( cachePolicy == 0 ) {
+        if( CACHE_POLICY == 0 ) {
             return;
         }
         long expiration = -1;
-        if( cachePolicy != FOREVER ) {
-            expiration = System.currentTimeMillis() + cachePolicy * 1000;
+        if( CACHE_POLICY != FOREVER ) {
+            expiration = System.currentTimeMillis() + CACHE_POLICY * 1000;
         }
-        synchronized( addressCache ) {
+        synchronized( ADDRESS_CACHE ) {
             for( int i = 0; i < addrs.length; i++ ) {
-                CacheEntry entry = (CacheEntry)addressCache.get( addrs[i].hostName );
+                CacheEntry entry = (CacheEntry)ADDRESS_CACHE.get( addrs[i].hostName );
                 if( entry == null ) {
                     entry = new CacheEntry( addrs[i].hostName, addrs[i], expiration );
-                    addressCache.put( addrs[i].hostName, entry );
+                    ADDRESS_CACHE.put( addrs[i].hostName, entry );
                 } else {
                     entry.address = addrs[i];
                     entry.expiration = expiration;
                 }
             }
-            Log.printAddressCache( "name service address cache", addressCache );
         }
     }
     static NbtAddress getCachedAddress( Name hostName ) {
-        if( cachePolicy == 0 ) {
+        if( CACHE_POLICY == 0 ) {
             return null;
         }
-        synchronized( addressCache ) {
-            CacheEntry entry = (CacheEntry)addressCache.get( hostName );
+        synchronized( ADDRESS_CACHE ) {
+            CacheEntry entry = (CacheEntry)ADDRESS_CACHE.get( hostName );
             if( entry != null && entry.expiration < System.currentTimeMillis() &&
-                                                                                               entry.expiration >= 0 ) {
+                                                entry.expiration >= 0 ) {
                 entry = null;
             }
             return entry != null ? entry.address : null;
@@ -284,67 +279,67 @@ public final class NbtAddress {
     }
 
     static NbtAddress doNameQuery( Name name, InetAddress svr )
-                                                                                                       throws UnknownHostException {
+                                                    throws UnknownHostException {
         NbtAddress addr;
 
-               if( name.hexCode == 0x1d && svr == null ) {
-                       svr = client.baddr; // bit of a hack but saves a lookup
-               }
-               name.srcHashCode = svr != null ? svr.hashCode() : 0;
-               addr = getCachedAddress( name );
+        if( name.hexCode == 0x1d && svr == null ) {
+            svr = CLIENT.baddr; // bit of a hack but saves a lookup
+        }
+        name.srcHashCode = svr != null ? svr.hashCode() : 0;
+        addr = getCachedAddress( name );
 
         if( addr == null ) {
-                       /* This was copied amost verbatim from InetAddress.java. See the
-                        * comments there for a description of how the lookupTable prevents
-                        * redundant queries from going out on the wire.
-                        */
-                       if(( addr = (NbtAddress)checkLookupTable( name )) == null ) {
-                   try {
-                       addr = client.getByName( name, svr );
-                   } catch( UnknownHostException uhe ) {
-                                       addr = unknownAddress;
-                   } finally {
-                       cacheAddress( name, addr );
-                                       updateLookupTable( name );
-                               }
-                       }
+            /* This was copied amost verbatim from InetAddress.java. See the
+             * comments there for a description of how the LOOKUP_TABLE prevents
+             * redundant queries from going out on the wire.
+             */
+            if(( addr = (NbtAddress)checkLookupTable( name )) == null ) {
+                try {
+                    addr = CLIENT.getByName( name, svr );
+                } catch( UnknownHostException uhe ) {
+                    addr = UNKNOWN_ADDRESS;
+                } finally {
+                    cacheAddress( name, addr );
+                    updateLookupTable( name );
+                }
+            }
         }
-        if( addr == unknownAddress ) {
+        if( addr == UNKNOWN_ADDRESS ) {
             throw new UnknownHostException( name.toString() );
         }
         return addr;
     }
 
-       private static Object checkLookupTable( Name name ) {
-               Object obj;
-
-               synchronized( lookupTable ) {
-                       if( lookupTable.containsKey( name ) == false ) {
-                               lookupTable.put( name, name );
-                               return null;
-                       }
-                       while( lookupTable.containsKey( name )) {
-                               try {
-                                       lookupTable.wait();
-                               } catch( InterruptedException e ) {
-                               }
-                       }
-               }
-               obj = getCachedAddress( name );
-               if( obj == null ) {
-                       synchronized( lookupTable ) {
-                               lookupTable.put( name, name );
-                       }
-               }
-
-               return obj;
-       }
-       private static void updateLookupTable( Name name ) {
-               synchronized( lookupTable ) {
-                       lookupTable.remove( name );
-                       lookupTable.notifyAll();
-               }
-       }
+    private static Object checkLookupTable( Name name ) {
+        Object obj;
+
+        synchronized( LOOKUP_TABLE ) {
+            if( LOOKUP_TABLE.containsKey( name ) == false ) {
+                LOOKUP_TABLE.put( name, name );
+                return null;
+            }
+            while( LOOKUP_TABLE.containsKey( name )) {
+                try {
+                    LOOKUP_TABLE.wait();
+                } catch( InterruptedException e ) {
+                }
+            }
+        }
+        obj = getCachedAddress( name );
+        if( obj == null ) {
+            synchronized( LOOKUP_TABLE ) {
+                LOOKUP_TABLE.put( name, name );
+            }
+        }
+
+        return obj;
+    }
+    private static void updateLookupTable( Name name ) {
+        synchronized( LOOKUP_TABLE ) {
+            LOOKUP_TABLE.remove( name );
+            LOOKUP_TABLE.notifyAll();
+        }
+    }
 
 /** 
  * Retrieves the local host address.
@@ -393,8 +388,8 @@ public final class NbtAddress {
                                         String scope )
                                         throws UnknownHostException {
 
-               return getByName( host, type, scope, null );
-       }
+        return getByName( host, type, scope, null );
+    }
 
 /* 
  * The additional <code>svr</code> parameter specifies the address to
@@ -405,7 +400,7 @@ public final class NbtAddress {
     public static NbtAddress getByName( String host,
                                         int type,
                                         String scope,
-                                                                               InetAddress svr )
+                                        InetAddress svr )
                                         throws UnknownHostException {
 
         if( host == null || host.length() == 0 ) {
@@ -444,7 +439,7 @@ public final class NbtAddress {
             if( hitDots != 4 || host.endsWith( "." )) {
                 return (NbtAddress)doNameQuery( new Name( host, type, scope ), svr );
             }
-            return new NbtAddress( unknownName, IP, false, B_NODE );
+            return new NbtAddress( UNKNOWN_NAME, IP, false, B_NODE );
         }
     }
 
@@ -460,7 +455,7 @@ public final class NbtAddress {
 
 
     public static NbtAddress[] getAllByAddress( String host )
-                                                                                               throws UnknownHostException {
+                                                throws UnknownHostException {
         return getAllByAddress( getByName( host, 0x00, null ));
     }
 
@@ -499,38 +494,51 @@ public final class NbtAddress {
  */
 
     public static NbtAddress[] getAllByAddress( NbtAddress addr )
-                                                                                               throws UnknownHostException {
+                                                throws UnknownHostException {
         try {
-            NbtAddress[] addrs = client.getNodeStatus( addr );
+            NbtAddress[] addrs = CLIENT.getNodeStatus( addr );
             cacheAddressArray( addrs );
             return addrs;
         } catch( UnknownHostException uhe ) {
             throw new UnknownHostException( "no name with type 0x" +
-                                                       Name.toHexChars( addr.hostName.hexCode ) +
-                                                       ((( addr.hostName.scope == null ) ||
-                                                       ( addr.hostName.scope.length() == 0 )) ?
-                                                       " with no scope" : " with scope " + addr.hostName.scope ) +
-                                                       " for host " + addr.getHostAddress() );
+                            Hexdump.toHexString( addr.hostName.hexCode, 2 ) +
+                            ((( addr.hostName.scope == null ) ||
+                            ( addr.hostName.scope.length() == 0 )) ?
+                            " with no scope" : " with scope " + addr.hostName.scope ) +
+                            " for host " + addr.getHostAddress() );
         }
     }
 
+    public static InetAddress getNBNSAddress() {
+        return NBNS.length == 0 ? null : NBNS[nbnsIndex];
+    }
+
+    public static boolean isNBNS( InetAddress svr ) {
+        for( int i = 0; svr != null && i < NBNS.length; i++ ) {
+            if( svr.hashCode() == NBNS[i].hashCode() ) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     Name hostName;
     int address, nodeType;
     boolean groupName,
-               isBeingDeleted,
-       isInConflict,
-       isActive,
-       isPermanent,
-       isDataFromNodeStatus;
+        isBeingDeleted,
+        isInConflict,
+        isActive,
+        isPermanent,
+        isDataFromNodeStatus;
     byte[] macAddress;
-       String calledName;
+    String calledName;
 
     NbtAddress( Name hostName, int address, boolean groupName, int nodeType ) {
         this.hostName = hostName;
         this.address = address;
         this.groupName = groupName;
         this.nodeType = nodeType;
-       }
+    }
 
     NbtAddress( Name hostName,
                 int address,
@@ -562,66 +570,66 @@ public final class NbtAddress {
  * methods are used by the smb package.
  */
 
-       public String firstCalledName() {
-
-               calledName = hostName.name;
-
-               if( Character.isDigit( calledName.charAt( 0 ))) {
-                       int i, len, dots;
-                       char[] data;
-
-                       i = dots = 0;                    /* quick IP address validation */
-                       len = calledName.length();
-                       data = calledName.toCharArray();
-                       while( i < len && Character.isDigit( data[i++] )) {
-                               if( i == len && dots == 3 ) {
-                                       // probably an IP address
-                                       calledName = SMBSERVER_NAME;
-                                       break;
-                               }
-                               if( i < len && data[i] == '.' ) {
-                                       dots++;
-                                       i++;
-                               }
-                       }
-               } else if( hostName.hexCode == 0x1D ) {
-                       calledName = SMBSERVER_NAME;
-               }
-
-               return calledName;
-    }
-       public String nextCalledName() {
-
-               if( calledName == hostName.name ) {
-                       calledName = SMBSERVER_NAME;
-               } else if( calledName == SMBSERVER_NAME ) {
-                       NbtAddress[] addrs;
-
-                       try {
-                               addrs = client.getNodeStatus( this );
-                               if( hostName.hexCode == 0x1D ) {
-                                       for( int i = 0; i < addrs.length; i++ ) {
-                                               if( addrs[i].hostName.hexCode == 0x20 ) {
-                                                       return addrs[i].hostName.name;
-                                               }
-                                       }
-                                       return null;
-                               } else if( isDataFromNodeStatus ) {
-                                       /* 'this' has been updated and should now
-                                        * have a real NetBIOS name
-                                        */
-                                       calledName = null;
-                                       return hostName.name;
-                               }
-                       } catch( UnknownHostException uhe ) {
-                               calledName = null;
-                       }
-               } else {
-                       calledName = null;
-               }
-
-               return calledName;
-       }
+    public String firstCalledName() {
+
+        calledName = hostName.name;
+
+        if( Character.isDigit( calledName.charAt( 0 ))) {
+            int i, len, dots;
+            char[] data;
+
+            i = dots = 0;                    /* quick IP address validation */
+            len = calledName.length();
+            data = calledName.toCharArray();
+            while( i < len && Character.isDigit( data[i++] )) {
+                if( i == len && dots == 3 ) {
+                    // probably an IP address
+                    calledName = SMBSERVER_NAME;
+                    break;
+                }
+                if( i < len && data[i] == '.' ) {
+                    dots++;
+                    i++;
+                }
+            }
+        } else if( hostName.hexCode == 0x1D ) {
+            calledName = SMBSERVER_NAME;
+        }
+
+        return calledName;
+    }
+    public String nextCalledName() {
+
+        if( calledName == hostName.name ) {
+            calledName = SMBSERVER_NAME;
+        } else if( calledName == SMBSERVER_NAME ) {
+            NbtAddress[] addrs;
+
+            try {
+                addrs = CLIENT.getNodeStatus( this );
+                if( hostName.hexCode == 0x1D ) {
+                    for( int i = 0; i < addrs.length; i++ ) {
+                        if( addrs[i].hostName.hexCode == 0x20 ) {
+                            return addrs[i].hostName.name;
+                        }
+                    }
+                    return null;
+                } else if( isDataFromNodeStatus ) {
+                    /* 'this' has been updated and should now
+                     * have a real NetBIOS name
+                     */
+                    calledName = null;
+                    return hostName.name;
+                }
+            } catch( UnknownHostException uhe ) {
+                calledName = null;
+            }
+        } else {
+            calledName = null;
+        }
+
+        return calledName;
+    }
 
 /* 
  * There are three degrees of state that any NbtAddress can have.
@@ -651,13 +659,13 @@ public final class NbtAddress {
  */ 
 
     void checkData() throws UnknownHostException {
-        if( hostName == unknownName ) {
-               getAllByAddress( this );
+        if( hostName == UNKNOWN_NAME ) {
+            getAllByAddress( this );
         }
     }
     void checkNodeStatusData() throws UnknownHostException {
         if( isDataFromNodeStatus == false ) {
-               getAllByAddress( this );
+            getAllByAddress( this );
         }
     }
 
@@ -753,7 +761,7 @@ public final class NbtAddress {
 
     public String getHostName() {
         try {
-                       checkData();
+            checkData();
         } catch( UnknownHostException uhe ) {
             return getHostAddress();
         }
@@ -803,9 +811,9 @@ public final class NbtAddress {
  * Returned the hex code associated with this name(e.g. 0x20 is for the file service)
  */
 
-       public int getNameType() {
-               return hostName.hexCode;
-       }
+    public int getNameType() {
+        return hostName.hexCode;
+    }
 
 /** 
  * Returns a hashcode for this IP address. The hashcode comes from the IP address
@@ -826,7 +834,7 @@ public final class NbtAddress {
 
     public boolean equals( Object obj ) {
         return ( obj != null ) && ( obj instanceof NbtAddress ) &&
-                                                                               ( ((NbtAddress)obj).address == address );
+                                        ( ((NbtAddress)obj).address == address );
     }
 
 /** 
index 2934568..b4f7f75 100644 (file)
@@ -22,82 +22,82 @@ import java.io.IOException;
 
 public class NbtException extends IOException {
 
-       // error classes
-       public static final int SUCCESS = 0;
-       public static final int ERR_NAM_SRVC = 0x01;
-       public static final int ERR_SSN_SRVC = 0x02;
+    // error classes
+    public static final int SUCCESS = 0;
+    public static final int ERR_NAM_SRVC = 0x01;
+    public static final int ERR_SSN_SRVC = 0x02;
 
-       // name service error codes
-       public static final int FMT_ERR = 0x1;
-       public static final int SRV_ERR = 0x2;
-       public static final int IMP_ERR = 0x4;
-       public static final int RFS_ERR = 0x5;
-       public static final int ACT_ERR = 0x6;
-       public static final int CFT_ERR = 0x7;
+    // name service error codes
+    public static final int FMT_ERR = 0x1;
+    public static final int SRV_ERR = 0x2;
+    public static final int IMP_ERR = 0x4;
+    public static final int RFS_ERR = 0x5;
+    public static final int ACT_ERR = 0x6;
+    public static final int CFT_ERR = 0x7;
 
-       // session service error codes
-       public static final int CONNECTION_REFUSED    = -1; 
-       public static final int NOT_LISTENING_CALLED  = 0x80;
-       public static final int NOT_LISTENING_CALLING = 0x81;
-       public static final int CALLED_NOT_PRESENT    = 0x82;
-       public static final int NO_RESOURCES          = 0x83;
-       public static final int UNSPECIFIED           = 0x8F;
+    // session service error codes
+    public static final int CONNECTION_REFUSED    = -1; 
+    public static final int NOT_LISTENING_CALLED  = 0x80;
+    public static final int NOT_LISTENING_CALLING = 0x81;
+    public static final int CALLED_NOT_PRESENT    = 0x82;
+    public static final int NO_RESOURCES          = 0x83;
+    public static final int UNSPECIFIED           = 0x8F;
 
-       public int errorClass;
-       public int errorCode;
+    public int errorClass;
+    public int errorCode;
 
-       public static String getErrorString( int errorClass, int errorCode ) {
-               String result = "";
-               switch( errorClass ) {
-                       case SUCCESS:
-                               result += "SUCCESS";
-                               break;
-                       case ERR_NAM_SRVC:
-                               result += "ERR_NAM_SRVC/";
-                               switch( errorCode ) {
-                                       case FMT_ERR:
-                                               result += "FMT_ERR: Format Error";
-                                       default:
-                                               result += "Unknown error code: " + errorCode;
-                               }
-                               break;
-                       case ERR_SSN_SRVC:
-                               result += "ERR_SSN_SRVC/";
-                               switch( errorCode ) {
-                                       case CONNECTION_REFUSED:
-                                               result += "Connection refused";
-                                               break;
-                                       case NOT_LISTENING_CALLED:
-                                               result += "Not listening on called name";
-                                               break;
-                                       case NOT_LISTENING_CALLING:
-                                               result += "Not listening for calling name";
-                                               break;
-                                       case CALLED_NOT_PRESENT:
-                                               result += "Called name not present";
-                                               break;
-                                       case NO_RESOURCES:
-                                               result += "Called name present, but insufficient resources";
-                                               break;
-                                       case UNSPECIFIED:
-                                               result += "Unspecified error";
-                                               break;
-                                       default:
-                                               result += "Unknown error code: " + errorCode;
-                               }
-                               break;
-                       default:
-                               result += "unknown error class: " + errorClass;
-               }
-               return result;
-       }
+    public static String getErrorString( int errorClass, int errorCode ) {
+        String result = "";
+        switch( errorClass ) {
+            case SUCCESS:
+                result += "SUCCESS";
+                break;
+            case ERR_NAM_SRVC:
+                result += "ERR_NAM_SRVC/";
+                switch( errorCode ) {
+                    case FMT_ERR:
+                        result += "FMT_ERR: Format Error";
+                    default:
+                        result += "Unknown error code: " + errorCode;
+                }
+                break;
+            case ERR_SSN_SRVC:
+                result += "ERR_SSN_SRVC/";
+                switch( errorCode ) {
+                    case CONNECTION_REFUSED:
+                        result += "Connection refused";
+                        break;
+                    case NOT_LISTENING_CALLED:
+                        result += "Not listening on called name";
+                        break;
+                    case NOT_LISTENING_CALLING:
+                        result += "Not listening for calling name";
+                        break;
+                    case CALLED_NOT_PRESENT:
+                        result += "Called name not present";
+                        break;
+                    case NO_RESOURCES:
+                        result += "Called name present, but insufficient resources";
+                        break;
+                    case UNSPECIFIED:
+                        result += "Unspecified error";
+                        break;
+                    default:
+                        result += "Unknown error code: " + errorCode;
+                }
+                break;
+            default:
+                result += "unknown error class: " + errorClass;
+        }
+        return result;
+    }
 
-       public NbtException( int errorClass, int errorCode ) {
-               super( getErrorString( errorClass, errorCode ));
-               this.errorClass = errorClass;
-               this.errorCode = errorCode;
-       }
-       public String toString() {
-               return new String( "errorClass=" + errorClass + ",errorCode=" + errorCode + ",errorString=" + getErrorString( errorClass, errorCode ));
-       }
+    public NbtException( int errorClass, int errorCode ) {
+        super( getErrorString( errorClass, errorCode ));
+        this.errorClass = errorClass;
+        this.errorCode = errorCode;
+    }
+    public String toString() {
+        return new String( "errorClass=" + errorClass + ",errorCode=" + errorCode + ",errorString=" + getErrorString( errorClass, errorCode ));
+    }
 }
index f9c4714..0f7fd05 100644 (file)
@@ -24,102 +24,111 @@ import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.IOException;
 import jcifs.Config;
+import jcifs.util.LogStream;
 
 /**
- * This class represents a netbios TCP/IP socket. Under no
- * conditions will users of jcifs need not be concerned with this class as
- * netbios services are handled internally to the smb package. It is
- * only public so the smb package can access it.
+Do not use this class. Writing to the OutputStream of this type of socket
+requires leaving a 4 byte prefix for the NBT header. IOW you must call
+write( buf, 4, len ). Calling write( buf, 0, len ) will generate an error.
  */
 
 public class NbtSocket extends Socket {
 
-       private static final int SSN_SRVC_PORT = 139;
-       private static final int BUFFER_SIZE = 512;
+    private static final int SSN_SRVC_PORT = 139;
+    private static final int BUFFER_SIZE = 512;
     private static final int DEFAULT_SO_TIMEOUT = 5000;
 
-       NbtAddress address;
-       Name calledName;
-       int soTimeout;
+    private static LogStream log = LogStream.getInstance();
 
-       public NbtSocket() {
-               super();
-       }
-       public NbtSocket( NbtAddress address, int port ) throws IOException {
-               this( address, port, null, 0 );
-       }
-       public NbtSocket( NbtAddress address, int port,
-                                                               InetAddress localAddr, int localPort ) throws IOException {
-               this( address, null, port, localAddr, localPort );
-       }
-       public NbtSocket( NbtAddress address, String calledName, int port,
-                                                               InetAddress localAddr, int localPort ) throws IOException {
-               super( address.getInetAddress(), ( port == 0 ? SSN_SRVC_PORT : port ),
-                                                               localAddr, localPort );
-               this.address = address;
-               if( calledName == null ) {
-                       this.calledName = address.hostName;
-               } else {
-                       this.calledName = new Name( calledName, 0x20, null );
-               }
+    private NbtAddress address;
+    private Name calledName;
+    private int soTimeout;
+
+    public NbtSocket() {
+        super();
+    }
+    public NbtSocket( NbtAddress address, int port ) throws IOException {
+        this( address, port, null, 0 );
+    }
+    public NbtSocket( NbtAddress address, int port,
+                                InetAddress localAddr, int localPort ) throws IOException {
+        this( address, null, port, localAddr, localPort );
+    }
+    public NbtSocket( NbtAddress address, String calledName, int port,
+                                InetAddress localAddr, int localPort ) throws IOException {
+        super( address.getInetAddress(), ( port == 0 ? SSN_SRVC_PORT : port ),
+                                localAddr, localPort );
+        this.address = address;
+        if( calledName == null ) {
+            this.calledName = address.hostName;
+        } else {
+            this.calledName = new Name( calledName, 0x20, null );
+        }
         soTimeout = Config.getInt( "jcifs.netbios.soTimeout", DEFAULT_SO_TIMEOUT );
-               connect();
-       }
+        connect();
+    }
+
+    public NbtAddress getNbtAddress() {
+        return address;
+    }
+    public InputStream getInputStream() throws IOException {
+        return new SocketInputStream( super.getInputStream() );
+    }
+    public OutputStream getOutputStream() throws IOException {
+        return new SocketOutputStream( super.getOutputStream() );
+    }
+    public int getPort() {
+        return super.getPort();
+    }
+    public InetAddress getLocalAddress() {
+        return super.getLocalAddress();
+    }
+    public int getLocalPort() {
+        return super.getLocalPort();
+    }
+    public String toString() {
+        return "NbtSocket[addr=" + address +
+                ",port=" + super.getPort() +
+                ",localport=" + super.getLocalPort() + "]";
+    }
+    private void connect() throws IOException {
+        byte[] buffer = new byte[BUFFER_SIZE];
+        int type;
+        InputStream in;
 
-       public NbtAddress getNbtAddress() {
-               return address;
-       }
-       InputStream getRawInputStream() throws IOException {
-               return super.getInputStream();
-       }
-       OutputStream getRawOutputStream() throws IOException {
-               return super.getOutputStream();
-       }
-       public InputStream getInputStream() throws IOException {
-               return new SocketInputStream( super.getInputStream() );
-       }
-       public OutputStream getOutputStream() throws IOException {
-               return new SocketOutputStream( super.getOutputStream() );
-       }
-       public int getPort() {
-               return super.getPort();
-       }
-       public InetAddress getLocalAddress() {
-               return super.getLocalAddress();
-       }
-       public int getLocalPort() {
-               return super.getLocalPort();
-       }
-       public String toString() {
-               return "NbtSocket[addr=" + address +
-                               ",port=" + super.getPort() +
-                               ",localport=" + super.getLocalPort() + "]";
-       }
-       private void connect() throws IOException {
-               byte[] buffer = new byte[BUFFER_SIZE];
+        try {
+            in = super.getInputStream();
+            OutputStream out = super.getOutputStream();
 
-               InputStream in = super.getInputStream();
-               OutputStream out = super.getOutputStream();
+            SessionServicePacket ssp0 = new SessionRequestPacket( calledName, NbtAddress.localhost.hostName );
+            out.write( buffer, 0, ssp0.writeWireFormat( buffer, 0 ));
 
-               SessionServicePacket ssp0 = new SessionRequestPacket( calledName, NbtAddress.localhost.hostName );
-               out.write( buffer, 0, ssp0.writeWireFormat( buffer, 0 ));
+            setSoTimeout( soTimeout );
+            type = ssp0.readPacketType( in, buffer, 0 );
+        } catch( IOException ioe ) {
+            close();
+            throw ioe;
+        }
 
-               setSoTimeout( soTimeout );
-               switch( ssp0.readPacketType( in, buffer, 0 )) {
-                       case SessionServicePacket.POSITIVE_SESSION_RESPONSE:
-                               Log.println( Log.WARNINGS, "session service warning", " session established ok with " + address );
-                               return;
-                       case SessionServicePacket.NEGATIVE_SESSION_RESPONSE:
-                               int errorCode = (int)( in.read() & 0xFF );
-                               throw new NbtException( NbtException.ERR_SSN_SRVC, errorCode );
-                       case -1:
-                               throw new NbtException( NbtException.ERR_SSN_SRVC, NbtException.CONNECTION_REFUSED );
-                       default:
-                               throw new NbtException( NbtException.ERR_SSN_SRVC, 0 );
-               }
-       }
-       public void close() throws IOException {
-               Log.println( Log.WARNINGS, "netbios socket closed", this );
-               super.close();
-       }
+        switch( type ) {
+            case SessionServicePacket.POSITIVE_SESSION_RESPONSE:
+                if( log.level > 2 )
+                    log.println( "session established ok with " + address );
+                return;
+            case SessionServicePacket.NEGATIVE_SESSION_RESPONSE:
+                int errorCode = (int)( in.read() & 0xFF );
+                close();
+                throw new NbtException( NbtException.ERR_SSN_SRVC, errorCode );
+            case -1:
+                throw new NbtException( NbtException.ERR_SSN_SRVC, NbtException.CONNECTION_REFUSED );
+            default:
+                close();
+                throw new NbtException( NbtException.ERR_SSN_SRVC, 0 );
+        }
+    }
+    public void close() throws IOException {
+        if( log.level > 2 )
+            log.println( "close: " + this );
+        super.close();
+    }
 }
index c4a6749..283c9c6 100644 (file)
@@ -20,31 +20,31 @@ package jcifs.netbios;
 
 class NodeStatusRequest extends NameServicePacket {
 
-       NodeStatusRequest( Name name ) {
-               questionName = name;
-               questionType = NBSTAT;
-               isRecurDesired = false;
-               isBroadcast = false;
-       }
+    NodeStatusRequest( Name name ) {
+        questionName = name;
+        questionType = NBSTAT;
+        isRecurDesired = false;
+        isBroadcast = false;
+    }
 
-       int writeBodyWireFormat( byte[] dst, int dstIndex ) {
-               int tmp = questionName.hexCode;
-               questionName.hexCode = 0x00; // type has to be 0x00 for node status
-               int result = writeQuestionSectionWireFormat( dst, dstIndex );
-               questionName.hexCode = tmp;
-               return result;
-       }
-       int readBodyWireFormat( byte[] src, int srcIndex ) {
-               return 0;
-       }
-       int writeRDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readRDataWireFormat( byte[] src, int srcIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "NodeStatusRequest[" +
-                       super.toString() + "]" );
-       }
+    int writeBodyWireFormat( byte[] dst, int dstIndex ) {
+        int tmp = questionName.hexCode;
+        questionName.hexCode = 0x00; // type has to be 0x00 for node status
+        int result = writeQuestionSectionWireFormat( dst, dstIndex );
+        questionName.hexCode = tmp;
+        return result;
+    }
+    int readBodyWireFormat( byte[] src, int srcIndex ) {
+        return 0;
+    }
+    int writeRDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readRDataWireFormat( byte[] src, int srcIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "NodeStatusRequest[" +
+            super.toString() + "]" );
+    }
 }
index dc6787c..8687988 100644 (file)
@@ -22,54 +22,55 @@ import java.io.UnsupportedEncodingException;
 
 class NodeStatusResponse extends NameServicePacket {
 
-       NbtAddress queryAddress;
+    private NbtAddress queryAddress;
 
-       int numberOfNames;
-       NbtAddress[] addressArray;
-       byte[] macAddress;
-       byte[] stats;
+    private int numberOfNames;
+    private byte[] macAddress;
+    private byte[] stats;
 
-       /* It is a little awkward but prudent to pass the quering address
-        * so that it may be included in the list of results. IOW we do
-        * not want to create a new NbtAddress object for this particular
-        * address from which the query is constructed, we want to populate
+    NbtAddress[] addressArray;
+
+    /* It is a little awkward but prudent to pass the quering address
+     * so that it may be included in the list of results. IOW we do
+     * not want to create a new NbtAddress object for this particular
+     * address from which the query is constructed, we want to populate
      * the data of the existing address that should be one of several
-        * returned by the node status.
-        */
+     * returned by the node status.
+     */
 
-       NodeStatusResponse( NbtAddress queryAddress ) {
-               this.queryAddress = queryAddress;
-               recordName = new Name();
+    NodeStatusResponse( NbtAddress queryAddress ) {
+        this.queryAddress = queryAddress;
+        recordName = new Name();
         macAddress = new byte[6];
-       }
+    }
 
-       int writeBodyWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readBodyWireFormat( byte[] src, int srcIndex ) {
-               return readResourceRecordWireFormat( src, srcIndex );
-       }
-       int writeRDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readRDataWireFormat( byte[] src, int srcIndex ) {
-               int start = srcIndex;
-               numberOfNames = src[srcIndex] & 0xFF;
-               int namesLength = numberOfNames * 18;
-               int statsLength = rDataLength - namesLength - 1;
-               numberOfNames = src[srcIndex++] & 0xFF;
-               // gotta read the mac first so we can populate addressArray with it
+    int writeBodyWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readBodyWireFormat( byte[] src, int srcIndex ) {
+        return readResourceRecordWireFormat( src, srcIndex );
+    }
+    int writeRDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readRDataWireFormat( byte[] src, int srcIndex ) {
+        int start = srcIndex;
+        numberOfNames = src[srcIndex] & 0xFF;
+        int namesLength = numberOfNames * 18;
+        int statsLength = rDataLength - namesLength - 1;
+        numberOfNames = src[srcIndex++] & 0xFF;
+        // gotta read the mac first so we can populate addressArray with it
         System.arraycopy( src, srcIndex + namesLength, macAddress, 0, 6 );
-               srcIndex += readNodeNameArray( src, srcIndex );
-               stats = new byte[statsLength];
-               System.arraycopy( src, srcIndex, stats, 0, statsLength );
-               srcIndex += statsLength;
-               return srcIndex - start;
-       }
+        srcIndex += readNodeNameArray( src, srcIndex );
+        stats = new byte[statsLength];
+        System.arraycopy( src, srcIndex, stats, 0, statsLength );
+        srcIndex += statsLength;
+        return srcIndex - start;
+    }
     private int readNodeNameArray( byte[] src, int srcIndex ) {
-               int start = srcIndex;
+        int start = srcIndex;
 
-               addressArray = new NbtAddress[numberOfNames];
+        addressArray = new NbtAddress[numberOfNames];
 
         String n;
         int hexCode;
@@ -83,61 +84,61 @@ class NodeStatusResponse extends NameServicePacket {
         int j;
         boolean addrFound = false;
 
-               try {
-               for( int i = 0; i < numberOfNames; srcIndex += 18, i++ ) {
-                   for( j = srcIndex + 14; src[j] == 0x20; j-- )
-                       ;
-                       n = new String( src, srcIndex, j - srcIndex + 1, Name.encoding );
-                   hexCode          =    src[srcIndex + 15] & 0xFF;
-                   groupName        = (( src[srcIndex + 16] & 0x80 ) == 0x80 ) ? true : false;
-                   ownerNodeType    =  ( src[srcIndex + 16] & 0x60 ) >> 5;
-                   isBeingDeleted   = (( src[srcIndex + 16] & 0x10 ) == 0x10 ) ? true : false;
-                   isInConflict     = (( src[srcIndex + 16] & 0x08 ) == 0x08 ) ? true : false;
-                   isActive         = (( src[srcIndex + 16] & 0x04 ) == 0x04 ) ? true : false;
-                   isPermanent      = (( src[srcIndex + 16] & 0x02 ) == 0x02 ) ? true : false;
-       
-       /* The NbtAddress object used to query this node will be in the list
-        * returned by the Node Status. A new NbtAddress object should not be
-        * created for it because the original is potentially being actively
-        * referenced by other objects. We must populate the existing object's
-        * data explicitly (and carefully).
-        */
-                   if( !addrFound && queryAddress.hostName.hexCode == hexCode &&
-                                               ( queryAddress.hostName == NbtAddress.unknownName ||
-                                               queryAddress.hostName.name.equals( n ))) {
-       
-                                       if( queryAddress.hostName == NbtAddress.unknownName ) {
-                               queryAddress.hostName = new Name( n, hexCode, scope );
-                                       }
-                       queryAddress.groupName = groupName;
-                       queryAddress.nodeType = ownerNodeType;
-                       queryAddress.isBeingDeleted = isBeingDeleted;
-                       queryAddress.isInConflict = isInConflict;
-                       queryAddress.isActive = isActive;
-                       queryAddress.isPermanent = isPermanent;
-                       queryAddress.macAddress = macAddress;
-                       queryAddress.isDataFromNodeStatus = true;
-                       addrFound = true;
-                       addressArray[i] = queryAddress;
-                   } else {
-                       addressArray[i] = new NbtAddress( new Name( n, hexCode, scope ),
-                                               queryAddress.address,
-                                               groupName,
-                                               ownerNodeType,
-                                               isBeingDeleted,
-                                               isInConflict,
-                                               isActive,
-                                               isPermanent,
-                                               macAddress );
-                   }
-               }
-               } catch( UnsupportedEncodingException uee ) {
-               }
+        try {
+            for( int i = 0; i < numberOfNames; srcIndex += 18, i++ ) {
+                for( j = srcIndex + 14; src[j] == 0x20; j-- )
+                    ;
+                n = new String( src, srcIndex, j - srcIndex + 1, Name.OEM_ENCODING );
+                hexCode          =    src[srcIndex + 15] & 0xFF;
+                groupName        = (( src[srcIndex + 16] & 0x80 ) == 0x80 ) ? true : false;
+                ownerNodeType    =  ( src[srcIndex + 16] & 0x60 ) >> 5;
+                isBeingDeleted   = (( src[srcIndex + 16] & 0x10 ) == 0x10 ) ? true : false;
+                isInConflict     = (( src[srcIndex + 16] & 0x08 ) == 0x08 ) ? true : false;
+                isActive         = (( src[srcIndex + 16] & 0x04 ) == 0x04 ) ? true : false;
+                isPermanent      = (( src[srcIndex + 16] & 0x02 ) == 0x02 ) ? true : false;
+    
+    /* The NbtAddress object used to query this node will be in the list
+     * returned by the Node Status. A new NbtAddress object should not be
+     * created for it because the original is potentially being actively
+     * referenced by other objects. We must populate the existing object's
+     * data explicitly (and carefully).
+     */
+                if( !addrFound && queryAddress.hostName.hexCode == hexCode &&
+                        ( queryAddress.hostName == NbtAddress.UNKNOWN_NAME ||
+                        queryAddress.hostName.name.equals( n ))) {
+    
+                    if( queryAddress.hostName == NbtAddress.UNKNOWN_NAME ) {
+                        queryAddress.hostName = new Name( n, hexCode, scope );
+                    }
+                    queryAddress.groupName = groupName;
+                    queryAddress.nodeType = ownerNodeType;
+                    queryAddress.isBeingDeleted = isBeingDeleted;
+                    queryAddress.isInConflict = isInConflict;
+                    queryAddress.isActive = isActive;
+                    queryAddress.isPermanent = isPermanent;
+                    queryAddress.macAddress = macAddress;
+                    queryAddress.isDataFromNodeStatus = true;
+                    addrFound = true;
+                    addressArray[i] = queryAddress;
+                } else {
+                    addressArray[i] = new NbtAddress( new Name( n, hexCode, scope ),
+                                            queryAddress.address,
+                                            groupName,
+                                            ownerNodeType,
+                                            isBeingDeleted,
+                                            isInConflict,
+                                            isActive,
+                                            isPermanent,
+                                            macAddress );
+                }
+            }
+        } catch( UnsupportedEncodingException uee ) {
+        }
         return srcIndex - start;
     }
-       public String toString() {
-               return new String( "NodeStatusResponse[" +
-                       super.toString() + "]" );
-       }
+    public String toString() {
+        return new String( "NodeStatusResponse[" +
+            super.toString() + "]" );
+    }
 }
 
index 26618d2..b5a7ee9 100644 (file)
@@ -23,33 +23,33 @@ import java.io.InputStream;
 
 class SessionRequestPacket extends SessionServicePacket {
 
-       Name calledName, callingName;
+    private Name calledName, callingName;
 
-       SessionRequestPacket() {
-               calledName = new Name();
-               callingName = new Name();
-       }
-       SessionRequestPacket( Name calledName, Name callingName ) {
-               type = SESSION_REQUEST;
-               this.calledName = calledName;
-               this.callingName = callingName;
-       }
-       int writeTrailerWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-               dstIndex += calledName.writeWireFormat( dst, dstIndex );
-               dstIndex += callingName.writeWireFormat( dst, dstIndex );
-               return dstIndex - start;
-       }
-       int readTrailerWireFormat( InputStream in,
-                                                       byte[] buffer,
-                                                       int bufferIndex )
-                                                       throws IOException {
-               int start = bufferIndex;
-               if( in.read( buffer, bufferIndex, length ) != length ) {
-                       throw new IOException( "invalid session request wire format" );
-               }
-               bufferIndex += calledName.readWireFormat( buffer, bufferIndex );
-               bufferIndex += callingName.readWireFormat( buffer, bufferIndex );
-               return bufferIndex - start;
-       }
+    SessionRequestPacket() {
+        calledName = new Name();
+        callingName = new Name();
+    }
+    SessionRequestPacket( Name calledName, Name callingName ) {
+        type = SESSION_REQUEST;
+        this.calledName = calledName;
+        this.callingName = callingName;
+    }
+    int writeTrailerWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+        dstIndex += calledName.writeWireFormat( dst, dstIndex );
+        dstIndex += callingName.writeWireFormat( dst, dstIndex );
+        return dstIndex - start;
+    }
+    int readTrailerWireFormat( InputStream in,
+                            byte[] buffer,
+                            int bufferIndex )
+                            throws IOException {
+        int start = bufferIndex;
+        if( in.read( buffer, bufferIndex, length ) != length ) {
+            throw new IOException( "invalid session request wire format" );
+        }
+        bufferIndex += calledName.readWireFormat( buffer, bufferIndex );
+        bufferIndex += callingName.readWireFormat( buffer, bufferIndex );
+        return bufferIndex - start;
+    }
 }
index cf02b87..dafd1d4 100644 (file)
@@ -23,28 +23,28 @@ import java.io.InputStream;
 
 class SessionRetargetResponsePacket extends SessionServicePacket {
 
-       NbtAddress retargetAddress;
-       int retargetPort;
+    private NbtAddress retargetAddress;
+    private int retargetPort;
 
-       SessionRetargetResponsePacket() {
-               type = SESSION_RETARGET_RESPONSE;
-               length = 6;
-       }
+    SessionRetargetResponsePacket() {
+        type = SESSION_RETARGET_RESPONSE;
+        length = 6;
+    }
 
-       int writeTrailerWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readTrailerWireFormat( InputStream in,
-                                                       byte[] buffer,
-                                                       int bufferIndex )
-                                                       throws IOException {
-               if( in.read( buffer, bufferIndex, length ) != length ) {
-                       throw new IOException( "unexpected EOF reading netbios retarget session response" );
-               }
-               int addr = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-               retargetAddress = new NbtAddress( null, addr, false, NbtAddress.B_NODE );
-               retargetPort = readInt2( buffer, bufferIndex );
-               return length;
-       }
+    int writeTrailerWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readTrailerWireFormat( InputStream in,
+                            byte[] buffer,
+                            int bufferIndex )
+                            throws IOException {
+        if( in.read( buffer, bufferIndex, length ) != length ) {
+            throw new IOException( "unexpected EOF reading netbios retarget session response" );
+        }
+        int addr = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+        retargetAddress = new NbtAddress( null, addr, false, NbtAddress.B_NODE );
+        retargetPort = readInt2( buffer, bufferIndex );
+        return length;
+    }
 }
index f90cdb2..8d7fb43 100644 (file)
@@ -23,90 +23,90 @@ import java.io.InputStream;
 
 abstract class SessionServicePacket { 
 
-       // session service packet types 
-       static final int SESSION_MESSAGE = 0x00; 
-       static final int SESSION_REQUEST = 0x81; 
-       static final int POSITIVE_SESSION_RESPONSE = 0x82; 
-       static final int NEGATIVE_SESSION_RESPONSE = 0x83; 
-       static final int SESSION_RETARGET_RESPONSE = 0x84; 
-       static final int SESSION_KEEP_ALIVE = 0x85; 
+    // session service packet types 
+    static final int SESSION_MESSAGE = 0x00; 
+    static final int SESSION_REQUEST = 0x81; 
+    static final int POSITIVE_SESSION_RESPONSE = 0x82; 
+    static final int NEGATIVE_SESSION_RESPONSE = 0x83; 
+    static final int SESSION_RETARGET_RESPONSE = 0x84; 
+    static final int SESSION_KEEP_ALIVE = 0x85; 
 
-       static final int MAX_MESSAGE_SIZE = 0x0001FFFF;
-       static final int HEADER_LENGTH = 4;
+    static final int MAX_MESSAGE_SIZE = 0x0001FFFF;
+    static final int HEADER_LENGTH = 4;
 
-       static void writeInt2( int val, byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = (byte)(( val >> 8 ) & 0xFF );
-               dst[dstIndex] = (byte)( val & 0xFF );
-       }
-       static void writeInt4( int val, byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = (byte)(( val >> 24 ) & 0xFF );
-               dst[dstIndex++] = (byte)(( val >> 16 ) & 0xFF );
-               dst[dstIndex++] = (byte)(( val >> 8 ) & 0xFF );
-               dst[dstIndex] = (byte)( val & 0xFF );
-       }
-       static int readInt2( byte[] src, int srcIndex ) {
-               return (( src[srcIndex] & 0xFF ) << 8 ) +
-                               ( src[srcIndex + 1] & 0xFF );
-       }
-       static int readInt4( byte[] src, int srcIndex ) {
-               return (( src[srcIndex] & 0xFF ) << 24 ) +
-                               (( src[srcIndex + 1] & 0xFF ) << 16 ) +
-                               (( src[srcIndex + 2] & 0xFF ) << 8 ) +
-                               ( src[srcIndex + 3] & 0xFF );
-       }
-       static int readLength( byte[] src, int srcIndex ) {
-               srcIndex++;
-               return (( src[srcIndex++] & 0x01 ) << 16 ) +
-                               (( src[srcIndex++] & 0xFF ) << 8 ) +
-                               ( src[srcIndex++] & 0xFF );
-       }
-       static int readPacketType( InputStream in,
-                                                                       byte[] buffer,
-                                                                       int bufferIndex )
-                                                                       throws IOException {
-               int n;
-               if(( n = in.read( buffer, bufferIndex, HEADER_LENGTH )) != HEADER_LENGTH ) {
-                       if( n == -1 ) {
-                               return -1;
-                       }
-                       throw new IOException( "unexpected EOF reading netbios session header" );
-               }
-               int t = buffer[bufferIndex] & 0xFF;
-               return t;
-       }
+    static void writeInt2( int val, byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = (byte)(( val >> 8 ) & 0xFF );
+        dst[dstIndex] = (byte)( val & 0xFF );
+    }
+    static void writeInt4( int val, byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = (byte)(( val >> 24 ) & 0xFF );
+        dst[dstIndex++] = (byte)(( val >> 16 ) & 0xFF );
+        dst[dstIndex++] = (byte)(( val >> 8 ) & 0xFF );
+        dst[dstIndex] = (byte)( val & 0xFF );
+    }
+    static int readInt2( byte[] src, int srcIndex ) {
+        return (( src[srcIndex] & 0xFF ) << 8 ) +
+                ( src[srcIndex + 1] & 0xFF );
+    }
+    static int readInt4( byte[] src, int srcIndex ) {
+        return (( src[srcIndex] & 0xFF ) << 24 ) +
+                (( src[srcIndex + 1] & 0xFF ) << 16 ) +
+                (( src[srcIndex + 2] & 0xFF ) << 8 ) +
+                ( src[srcIndex + 3] & 0xFF );
+    }
+    static int readLength( byte[] src, int srcIndex ) {
+        srcIndex++;
+        return (( src[srcIndex++] & 0x01 ) << 16 ) +
+                (( src[srcIndex++] & 0xFF ) << 8 ) +
+                ( src[srcIndex++] & 0xFF );
+    }
+    static int readPacketType( InputStream in,
+                                    byte[] buffer,
+                                    int bufferIndex )
+                                    throws IOException {
+        int n;
+        if(( n = in.read( buffer, bufferIndex, HEADER_LENGTH )) != HEADER_LENGTH ) {
+            if( n == -1 ) {
+                return -1;
+            }
+            throw new IOException( "unexpected EOF reading netbios session header" );
+        }
+        int t = buffer[bufferIndex] & 0xFF;
+        return t;
+    }
 
-       int type, length;
+    int type, length;
 
-       int writeWireFormat( byte[] dst, int dstIndex ) {
-               length = writeTrailerWireFormat( dst, dstIndex + HEADER_LENGTH );
-               writeHeaderWireFormat( dst, dstIndex );
-               return HEADER_LENGTH + length;
-       }
-       int readWireFormat( InputStream in, byte[] buffer, int bufferIndex ) throws IOException {
-               readHeaderWireFormat( in, buffer, bufferIndex );
-               return HEADER_LENGTH + readTrailerWireFormat( in, buffer, bufferIndex );
-       }
-       int writeHeaderWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = (byte)type;
-               if( length > 0x0000FFFF ) {
-                       dst[dstIndex] = (byte)0x01;
-               }
-               dstIndex++;
-               writeInt2( length, dst, dstIndex );
-               return HEADER_LENGTH;
-       }
-       int readHeaderWireFormat( InputStream in,
-                                                               byte[] buffer,
-                                                               int bufferIndex )
-                                                               throws IOException {
-               type = buffer[bufferIndex++] & 0xFF;
-               length = (( buffer[bufferIndex] & 0x01 ) << 16 ) + readInt2( buffer, bufferIndex + 1 );
-               return HEADER_LENGTH;
-       }
+    int writeWireFormat( byte[] dst, int dstIndex ) {
+        length = writeTrailerWireFormat( dst, dstIndex + HEADER_LENGTH );
+        writeHeaderWireFormat( dst, dstIndex );
+        return HEADER_LENGTH + length;
+    }
+    int readWireFormat( InputStream in, byte[] buffer, int bufferIndex ) throws IOException {
+        readHeaderWireFormat( in, buffer, bufferIndex );
+        return HEADER_LENGTH + readTrailerWireFormat( in, buffer, bufferIndex );
+    }
+    int writeHeaderWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = (byte)type;
+        if( length > 0x0000FFFF ) {
+            dst[dstIndex] = (byte)0x01;
+        }
+        dstIndex++;
+        writeInt2( length, dst, dstIndex );
+        return HEADER_LENGTH;
+    }
+    int readHeaderWireFormat( InputStream in,
+                                byte[] buffer,
+                                int bufferIndex )
+                                throws IOException {
+        type = buffer[bufferIndex++] & 0xFF;
+        length = (( buffer[bufferIndex] & 0x01 ) << 16 ) + readInt2( buffer, bufferIndex + 1 );
+        return HEADER_LENGTH;
+    }
 
-       abstract int writeTrailerWireFormat( byte[] dst, int dstIndex );
-       abstract int readTrailerWireFormat( InputStream in,
-                                                               byte[] buffer,
-                                                               int bufferIndex )
-                                                               throws IOException;
+    abstract int writeTrailerWireFormat( byte[] dst, int dstIndex );
+    abstract int readTrailerWireFormat( InputStream in,
+                                byte[] buffer,
+                                int bufferIndex )
+                                throws IOException;
 } 
index 25e5493..2bd4b9d 100644 (file)
@@ -23,89 +23,90 @@ import java.io.IOException;
 
 class SocketInputStream extends InputStream {
 
-       private static final int TMP_BUFFER_SIZE = 256;
-       private InputStream in;
-       private SessionServicePacket ssp;
-       private int tot, bip, n;
-       private byte[] header, tmp;
+    private static final int TMP_BUFFER_SIZE = 256;
 
-       SocketInputStream( InputStream in ) {
-               this.in = in;
-               header = new byte[4];
-               tmp = new byte[TMP_BUFFER_SIZE];
-       }
+    private InputStream in;
+    private SessionServicePacket ssp;
+    private int tot, bip, n;
+    private byte[] header, tmp;
 
-       public synchronized int read() throws IOException {
-               if( read( tmp, 0, 1 ) < 0 ) {
-                       return -1;
-               }
-               return tmp[0] & 0xFF;
-       }
-       public synchronized int read( byte[] b ) throws IOException {
-               return read( b, 0, b.length );
-       }
+    SocketInputStream( InputStream in ) {
+        this.in = in;
+        header = new byte[4];
+        tmp = new byte[TMP_BUFFER_SIZE];
+    }
 
-       /* This method will not return until len bytes have been read
-        * or the stream has been closed.
-        */
+    public synchronized int read() throws IOException {
+        if( read( tmp, 0, 1 ) < 0 ) {
+            return -1;
+        }
+        return tmp[0] & 0xFF;
+    }
+    public synchronized int read( byte[] b ) throws IOException {
+        return read( b, 0, b.length );
+    }
 
-       public synchronized int read( byte[] b, int off, int len ) throws IOException {
-               if( len == 0 ) {
-                       return 0;
-               }
-               tot = 0;
+    /* This method will not return until len bytes have been read
+     * or the stream has been closed.
+     */
 
-               while( true ) {
-                       while( bip > 0 ) {
-                               n = in.read( b, off, Math.min( len, bip ));
-                               if( n == -1 ) {
-                                       return tot > 0 ? tot : -1;
-                               }
-                               tot += n;
-                               off += n;
-                               len -= n;
-                               bip -= n;
-                               if( len == 0 ) {
-                                       return tot;
-                               }
-                       }
+    public synchronized int read( byte[] b, int off, int len ) throws IOException {
+        if( len == 0 ) {
+            return 0;
+        }
+        tot = 0;
 
-                       switch( SessionServicePacket.readPacketType( in, header, 0 )) {
-                               case SessionServicePacket.SESSION_KEEP_ALIVE:
-                                       break;
-                               case SessionServicePacket.SESSION_MESSAGE:
-                                       bip = SessionServicePacket.readLength( header, 0 );
-                                       break;
-                               case -1:
-                                       if( tot > 0 ) {
-                                               return tot;
-                                       }
-                                       return -1;
-                       }
-               }
-       }
-       public synchronized long skip( long numbytes ) throws IOException {
-               if( numbytes <= 0 ) {
-                       return 0;
-               }
-               long n = numbytes;
-               while( n > 0 ) {
-                       int r = read( tmp, 0, (int)Math.min( (long)TMP_BUFFER_SIZE, n ));
-                       if (r < 0) {
-                               break;
-                       }
-                       n -= r;
-               }
-               return numbytes - n;
-       }
-       public int available() throws IOException {
-               if( bip > 0 ) {
-                       return bip;
-               }
-               return in.available();
-       }
-       public void close() throws IOException {
-               in.close();
-       }
+        while( true ) {
+            while( bip > 0 ) {
+                n = in.read( b, off, Math.min( len, bip ));
+                if( n == -1 ) {
+                    return tot > 0 ? tot : -1;
+                }
+                tot += n;
+                off += n;
+                len -= n;
+                bip -= n;
+                if( len == 0 ) {
+                    return tot;
+                }
+            }
+
+            switch( SessionServicePacket.readPacketType( in, header, 0 )) {
+                case SessionServicePacket.SESSION_KEEP_ALIVE:
+                    break;
+                case SessionServicePacket.SESSION_MESSAGE:
+                    bip = SessionServicePacket.readLength( header, 0 );
+                    break;
+                case -1:
+                    if( tot > 0 ) {
+                        return tot;
+                    }
+                    return -1;
+            }
+        }
+    }
+    public synchronized long skip( long numbytes ) throws IOException {
+        if( numbytes <= 0 ) {
+            return 0;
+        }
+        long n = numbytes;
+        while( n > 0 ) {
+            int r = read( tmp, 0, (int)Math.min( (long)TMP_BUFFER_SIZE, n ));
+            if (r < 0) {
+                break;
+            }
+            n -= r;
+        }
+        return numbytes - n;
+    }
+    public int available() throws IOException {
+        if( bip > 0 ) {
+            return bip;
+        }
+        return in.available();
+    }
+    public void close() throws IOException {
+        in.close();
+    }
 }
 
index 37c1e69..93d10e3 100644 (file)
@@ -21,68 +21,27 @@ package jcifs.netbios;
 import java.io.FilterOutputStream;
 import java.io.OutputStream;
 import java.io.IOException;
-import jcifs.util.Log;
 
 class SocketOutputStream extends FilterOutputStream {
 
-       private static int DEFAULT_BUFR_SIZE = 4400;
+    SocketOutputStream( OutputStream out ) {
+        super( out );
+    }
 
-       private byte[] bufr;
-       private int count, writeSize;
+    public synchronized void write( byte[] b, int off, int len ) throws IOException {
+        if( len > 0xFFFF ) {
+            throw new IOException( "write too large: " + len );
+        } else if( off < 4 ) {
+            throw new IOException( "NetBIOS socket output buffer requires 4 bytes available before off" );
+        }
 
-       SocketOutputStream( OutputStream out ) {
-               this( out, DEFAULT_BUFR_SIZE );
-       }
-       SocketOutputStream( OutputStream out, int size ) {
-               super( out );
-               writeSize = jcifs.Config.getInt( "jcifs.netbios.client.writeSize", size );
-               if( writeSize <= 0 ) {
-                       throw new IllegalArgumentException( "buffer size <= 0" );
-               } else if( writeSize > SessionServicePacket.MAX_MESSAGE_SIZE ) {
-                       throw new IllegalArgumentException( "buffer exceeds max netbios message size" );
-               }
-               writeSize += 4;
-               bufr = new byte[writeSize];
-               bufr[0] = (byte)SessionServicePacket.SESSION_MESSAGE;
-               count = 4;
-       }
+        off -= 4;
 
-       public synchronized void write( int b ) throws IOException {
-               if( count >= bufr.length ) {
-                       flush();
-               }
-               bufr[count++] = (byte)b;
-       }
-       public synchronized void write( byte[] b, int off, int len ) throws IOException {
-               if(( len + 4 ) > bufr.length ) {
-                       Log.println( Log.WARNINGS, "session service warning",
-                                                       "write len exceeds pre-allocated buffer size; performance " +
-                                                       "will suffer: len=" + len + ",writeSize=" + writeSize );
-                       flush();
-                       byte[] tmp = bufr;
-                       bufr = new byte[len + 4]; /* at least mantain a permainent fixed size buffer */
-                       System.arraycopy( b, off, bufr, count, len ); /* doah! */
-                       count += len;
-                       flush();
-                       bufr = tmp;
-                       return;
-               }
-               if( len > bufr.length - count ) {
-                       flush();
-               }
-               System.arraycopy( b, off, bufr, count, len );
-               count += len;
-       }
-       public synchronized void flush() throws IOException {
-               if( count == 4 ) {
-                       return;
-               }
-               int n = count - 4;
-               bufr[1] = (byte)(( n & 0x010000 ) == 0x00 ? 0x00 : 0x01 ); 
-               bufr[2] = (byte)(( n >> 8 ) & 0xFF ); 
-               bufr[3] = (byte)( n & 0xFF ); 
-               out.write( bufr, 0, count );
-               out.flush();
-               count = 4;
-       }
+        b[off + 0] = (byte)SessionServicePacket.SESSION_MESSAGE;
+        b[off + 1] = (byte)0x00; 
+        b[off + 2] = (byte)(( len >> 8 ) & 0xFF ); 
+        b[off + 3] = (byte)( len & 0xFF ); 
+
+        out.write( b, off, 4 + len );
+    }
 }
index 5689a71..2a5fd50 100644 (file)
@@ -1,6 +1,6 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                      "Eric Glass" <jcifs at samba dot org>
+ *                   "Eric Glass" <jcifs at samba dot org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -26,113 +26,113 @@ import jcifs.Config;
  */
 public abstract class NtlmMessage implements NtlmFlags {
 
-       /**
-        * The NTLMSSP "preamble".
-        */
-       protected static final byte[] NTLMSSP_SIGNATURE = new byte[] {
-               (byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M',
-               (byte) 'S', (byte) 'S', (byte) 'P', (byte) 0
-       };
-
-       private static final String OEM_ENCODING =
-                       Config.getProperty("jcifs.smb.client.codepage",
-                                       Config.getProperty("jcifs.encoding",
-                                                       System.getProperty("file.encoding")));
-
-       private int flags;
-
-       /**
-        * Returns the flags currently in use for this message.
-        *
-        * @return An <code>int</code> containing the flags in use for this
-        * message.
-        */
-       public int getFlags() {
-               return flags;
-       }
-
-       /**
-        * Sets the flags for this message.
-        *
-        * @param flags The flags for this message.
-        */
-       public void setFlags(int flags) {
-               this.flags = flags;
-       }
-
-       /**
-        * Returns the status of the specified flag.
-        *
-        * @param flag The flag to test (i.e., <code>NTLMSSP_NEGOTIATE_OEM</code>).
-        * @return A <code>boolean</code> indicating whether the flag is set.
-        */
-       public boolean getFlag(int flag) {
-               return (getFlags() & flag) != 0;
-       }
-
-       /**
-        * Sets or clears the specified flag.
-        
-        * @param flag The flag to set/clear (i.e.,
-        * <code>NTLMSSP_NEGOTIATE_OEM</code>).
-        * @param value Indicates whether to set (<code>true</code>) or
-        * clear (<code>false</code>) the specified flag.
-        */
-       public void setFlag(int flag, boolean value) {
-               setFlags(value ? (getFlags() | flag) :
-                               (getFlags() & (0xffffffff ^ flag)));
-       }
-
-       static int readULong(byte[] src, int index) {
-               return (src[index] & 0xff) |
-                               ((src[index + 1] & 0xff) << 8) |
-                               ((src[index + 2] & 0xff) << 16) |
-                               ((src[index + 3] & 0xff) << 24);
-       }
-
-       static int readUShort(byte[] src, int index) {
-               return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8);
-       }
-
-       static byte[] readSecurityBuffer(byte[] src, int index) {
-               int length = readUShort(src, index);
-               int offset = readULong(src, index + 4);
-               byte[] buffer = new byte[length];
-               System.arraycopy(src, offset, buffer, 0, length);
-               return buffer;
-       }
-
-       static void writeULong(byte[] dest, int offset, int ulong) {
-               dest[offset] = (byte) (ulong & 0xff);
-               dest[offset + 1] = (byte) (ulong >> 8 & 0xff);
-               dest[offset + 2] = (byte) (ulong >> 16 & 0xff);
-               dest[offset + 3] = (byte) (ulong >> 24 & 0xff);
-       }
-
-       static void writeUShort(byte[] dest, int offset, int ushort) {
-               dest[offset] = (byte) (ushort & 0xff);
-               dest[offset + 1] = (byte) (ushort >> 8 & 0xff);
-       }
-
-       static void writeSecurityBuffer(byte[] dest, int offset, int bodyOffset,
-                       byte[] src) {
-               int length = (src != null) ? src.length : 0;
-               if (length == 0) return;
-               writeUShort(dest, offset, length);
-               writeUShort(dest, offset + 2, length);
-               writeULong(dest, offset + 4, bodyOffset);
-               System.arraycopy(src, 0, dest, bodyOffset, length);
-       }
-
-       static String getOEMEncoding() {
-               return OEM_ENCODING;
-       }
-
-       /**
-        * Returns the raw byte representation of this message.
-        *
-        * @return A <code>byte[]</code> containing the raw message material.
-        */
-       public abstract byte[] toByteArray();
+    /**
+     * The NTLMSSP "preamble".
+     */
+    protected static final byte[] NTLMSSP_SIGNATURE = new byte[] {
+        (byte) 'N', (byte) 'T', (byte) 'L', (byte) 'M',
+        (byte) 'S', (byte) 'S', (byte) 'P', (byte) 0
+    };
+
+    private static final String OEM_ENCODING =
+            Config.getProperty("jcifs.smb.client.codepage",
+                    Config.getProperty("jcifs.encoding",
+                            System.getProperty("file.encoding")));
+
+    private int flags;
+
+    /**
+     * Returns the flags currently in use for this message.
+     *
+     * @return An <code>int</code> containing the flags in use for this
+     * message.
+     */
+    public int getFlags() {
+        return flags;
+    }
+
+    /**
+     * Sets the flags for this message.
+     *
+     * @param flags The flags for this message.
+     */
+    public void setFlags(int flags) {
+        this.flags = flags;
+    }
+
+    /**
+     * Returns the status of the specified flag.
+     *
+     * @param flag The flag to test (i.e., <code>NTLMSSP_NEGOTIATE_OEM</code>).
+     * @return A <code>boolean</code> indicating whether the flag is set.
+     */
+    public boolean getFlag(int flag) {
+        return (getFlags() & flag) != 0;
+    }
+
+    /**
+     * Sets or clears the specified flag.
+     * 
+     * @param flag The flag to set/clear (i.e.,
+     * <code>NTLMSSP_NEGOTIATE_OEM</code>).
+     * @param value Indicates whether to set (<code>true</code>) or
+     * clear (<code>false</code>) the specified flag.
+     */
+    public void setFlag(int flag, boolean value) {
+        setFlags(value ? (getFlags() | flag) :
+                (getFlags() & (0xffffffff ^ flag)));
+    }
+
+    static int readULong(byte[] src, int index) {
+        return (src[index] & 0xff) |
+                ((src[index + 1] & 0xff) << 8) |
+                ((src[index + 2] & 0xff) << 16) |
+                ((src[index + 3] & 0xff) << 24);
+    }
+
+    static int readUShort(byte[] src, int index) {
+        return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8);
+    }
+
+    static byte[] readSecurityBuffer(byte[] src, int index) {
+        int length = readUShort(src, index);
+        int offset = readULong(src, index + 4);
+        byte[] buffer = new byte[length];
+        System.arraycopy(src, offset, buffer, 0, length);
+        return buffer;
+    }
+
+    static void writeULong(byte[] dest, int offset, int ulong) {
+        dest[offset] = (byte) (ulong & 0xff);
+        dest[offset + 1] = (byte) (ulong >> 8 & 0xff);
+        dest[offset + 2] = (byte) (ulong >> 16 & 0xff);
+        dest[offset + 3] = (byte) (ulong >> 24 & 0xff);
+    }
+
+    static void writeUShort(byte[] dest, int offset, int ushort) {
+        dest[offset] = (byte) (ushort & 0xff);
+        dest[offset + 1] = (byte) (ushort >> 8 & 0xff);
+    }
+
+    static void writeSecurityBuffer(byte[] dest, int offset, int bodyOffset,
+            byte[] src) {
+        int length = (src != null) ? src.length : 0;
+        if (length == 0) return;
+        writeUShort(dest, offset, length);
+        writeUShort(dest, offset + 2, length);
+        writeULong(dest, offset + 4, bodyOffset);
+        System.arraycopy(src, 0, dest, bodyOffset, length);
+    }
+
+    static String getOEMEncoding() {
+        return OEM_ENCODING;
+    }
+
+    /**
+     * Returns the raw byte representation of this message.
+     *
+     * @return A <code>byte[]</code> containing the raw message material.
+     */
+    public abstract byte[] toByteArray();
 
 }
index 42d3610..2c5c829 100644 (file)
@@ -1,6 +1,6 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                      "Eric Glass" <jcifs at samba dot org>
+ *                   "Eric Glass" <jcifs at samba dot org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -32,217 +32,217 @@ import jcifs.Config;
  */
 public class Type1Message extends NtlmMessage {
 
-       private static final int DEFAULT_FLAGS;
-
-       private static final String DEFAULT_DOMAIN;
-
-       private static final String DEFAULT_WORKSTATION;
-
-       private String suppliedDomain;
-
-       private String suppliedWorkstation;
-
-       static {
-               DEFAULT_FLAGS = NTLMSSP_NEGOTIATE_NTLM |
-                               (Config.getBoolean("jcifs.smb.client.useUnicode", true) ?
-                                               NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM);
-               DEFAULT_DOMAIN = Config.getProperty("jcifs.smb.client.domain", null);
-               String defaultWorkstation = null;
-               try {
-                       defaultWorkstation = NbtAddress.getLocalHost().getHostName();
-               } catch (UnknownHostException ex) { }
-               DEFAULT_WORKSTATION = defaultWorkstation;
-       }
-
-       /**
-        * Creates a Type-1 message using default values from the current
-        * environment.
-        */
-       public Type1Message() {
-               this(getDefaultFlags(), getDefaultDomain(), getDefaultWorkstation());
-       }
-
-       /**
-        * Creates a Type-1 message with the specified parameters.
-        *
-        * @param flags The flags to apply to this message.
-        * @param suppliedDomain The supplied authentication domain.
-        * @param suppliedWorkstation The supplied workstation name.
-        */
-       public Type1Message(int flags, String suppliedDomain,
-                       String suppliedWorkstation) {
-               setFlags(flags);
-               setSuppliedDomain(suppliedDomain);
-               setSuppliedWorkstation(suppliedWorkstation);
-       }
-
-       /**
-        * Creates a Type-1 message using the given raw Type-1 material.
-        *
-        * @param material The raw Type-1 material used to construct this message.
-        * @throws IOException If an error occurs while parsing the material.
-        */
-       public Type1Message(byte[] material) throws IOException {
-               parse(material);
-       }
-
-       /**
-        * Returns the supplied authentication domain.
-        *
-        * @return A <code>String</code> containing the supplied domain.
-        */
-       public String getSuppliedDomain() {
-               return suppliedDomain;
-       }
-
-       /**
-        * Sets the supplied authentication domain for this message.
-        *
-        * @param suppliedDomain The supplied domain for this message.
-        */
-       public void setSuppliedDomain(String suppliedDomain) {
-               this.suppliedDomain = suppliedDomain;
-       }
-
-       /**
-        * Returns the supplied workstation name.
-        
-        * @return A <code>String</code> containing the supplied workstation name.
-        */
-       public String getSuppliedWorkstation() {
-               return suppliedWorkstation;
-       }
-
-       /**
-        * Sets the supplied workstation name for this message.
-        
-        * @param suppliedWorkstation The supplied workstation for this message.
-        */
-       public void setSuppliedWorkstation(String suppliedWorkstation) {
-               this.suppliedWorkstation = suppliedWorkstation;
-       }
-
-       public byte[] toByteArray() {
-               try {
-                       String suppliedDomain = getSuppliedDomain();
-                       String suppliedWorkstation = getSuppliedWorkstation();
-                       int flags = getFlags();
-                       boolean hostInfo = false;
-                       byte[] domain = new byte[0];
-                       if (suppliedDomain != null && suppliedDomain.length() != 0) {
-                               hostInfo = true;
-                               flags |= NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED;
-                               domain = suppliedDomain.toUpperCase().getBytes(
-                                               getOEMEncoding());
-                       } else {
-                               flags &= (NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED ^ 0xffffffff);
-                       }
-                       byte[] workstation = new byte[0];
-                       if (suppliedWorkstation != null &&
-                                       suppliedWorkstation.length() != 0) {
-                               hostInfo = true;
-                               flags |= NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED;
-                               workstation =
-                                               suppliedWorkstation.toUpperCase().getBytes(
-                                                               getOEMEncoding());
-                       } else {
-                               flags &= (NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED ^
-                                               0xffffffff);
-                       }
-                       byte[] type1 = new byte[hostInfo ?
-                                       (32 + domain.length + workstation.length) : 16];
-                       System.arraycopy(NTLMSSP_SIGNATURE, 0, type1, 0, 8);
-                       writeULong(type1, 8, 1);
-                       writeULong(type1, 12, flags);
-                       if (hostInfo) {
-                               writeSecurityBuffer(type1, 16, 32, domain);
-                               writeSecurityBuffer(type1, 24, 32 + domain.length, workstation);
-                       }
-                       return type1;
-               } catch (IOException ex) {
-                       throw new IllegalStateException(ex.getMessage());
-               }
-       }
-
-       public String toString() {
-               String suppliedDomain = getSuppliedDomain();
-               String suppliedWorkstation = getSuppliedWorkstation();
-               int flags = getFlags();
-               StringBuffer buffer = new StringBuffer();
-               if (suppliedDomain != null) {
-                       buffer.append("suppliedDomain: ").append(suppliedDomain);
-               }
-               if (suppliedWorkstation != null) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("suppliedWorkstation: ").append(suppliedWorkstation);
-               }
-               if (flags != 0) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("flags: ");
-                       buffer.append("0x");
-                       buffer.append(Integer.toHexString((flags >> 28) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 24) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 20) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 16) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 12) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 8) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 4) & 0x0f));
-                       buffer.append(Integer.toHexString(flags & 0x0f));
-               }
-               return buffer.toString();
-       }
-
-       /**
-        * Returns the default flags for a generic Type-1 message in the
-        * current environment.
-        
-        * @return An <code>int</code> containing the default flags.
-        */
-       public static int getDefaultFlags() {
-               return DEFAULT_FLAGS;
-       }
-
-       /**
-        * Returns the default domain from the current environment.
-        *
-        * @return A <code>String</code> containing the default domain.
-        */
-       public static String getDefaultDomain() {
-               return DEFAULT_DOMAIN;
-       }
-
-       /**
-        * Returns the default workstation from the current environment.
-        *
-        * @return A <code>String</code> containing the default workstation.
-        */
-       public static String getDefaultWorkstation() {
-               return DEFAULT_WORKSTATION;
-       }
-
-       private void parse(byte[] material) throws IOException {
-               for (int i = 0; i < 8; i++) {
-                       if (material[i] != NTLMSSP_SIGNATURE[i]) {
-                               throw new IOException("Not an NTLMSSP message.");
-                       }
-               }
-               if (readULong(material, 8) != 1) {
-                       throw new IOException("Not a Type 1 message.");
-               }
-               int flags = readULong(material, 12);
-               String suppliedDomain = null;
-               if ((flags & NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED) != 0) {
-                       byte[] domain = readSecurityBuffer(material, 16);
-                       suppliedDomain = new String(domain, getOEMEncoding());
-               }
-               String suppliedWorkstation = null;
-               if ((flags & NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED) != 0) {
-                       byte[] workstation = readSecurityBuffer(material, 24);
-                       suppliedWorkstation = new String(workstation, getOEMEncoding());
-               }
-               setFlags(flags);
-               setSuppliedDomain(suppliedDomain);
-               setSuppliedWorkstation(suppliedWorkstation);
-       }
+    private static final int DEFAULT_FLAGS;
+
+    private static final String DEFAULT_DOMAIN;
+
+    private static final String DEFAULT_WORKSTATION;
+
+    private String suppliedDomain;
+
+    private String suppliedWorkstation;
+
+    static {
+        DEFAULT_FLAGS = NTLMSSP_NEGOTIATE_NTLM |
+                (Config.getBoolean("jcifs.smb.client.useUnicode", true) ?
+                        NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM);
+        DEFAULT_DOMAIN = Config.getProperty("jcifs.smb.client.domain", null);
+        String defaultWorkstation = null;
+        try {
+            defaultWorkstation = NbtAddress.getLocalHost().getHostName();
+        } catch (UnknownHostException ex) { }
+        DEFAULT_WORKSTATION = defaultWorkstation;
+    }
+
+    /**
+     * Creates a Type-1 message using default values from the current
+     * environment.
+     */
+    public Type1Message() {
+        this(getDefaultFlags(), getDefaultDomain(), getDefaultWorkstation());
+    }
+
+    /**
+     * Creates a Type-1 message with the specified parameters.
+     *
+     * @param flags The flags to apply to this message.
+     * @param suppliedDomain The supplied authentication domain.
+     * @param suppliedWorkstation The supplied workstation name.
+     */
+    public Type1Message(int flags, String suppliedDomain,
+            String suppliedWorkstation) {
+        setFlags(flags);
+        setSuppliedDomain(suppliedDomain);
+        setSuppliedWorkstation(suppliedWorkstation);
+    }
+
+    /**
+     * Creates a Type-1 message using the given raw Type-1 material.
+     *
+     * @param material The raw Type-1 material used to construct this message.
+     * @throws IOException If an error occurs while parsing the material.
+     */
+    public Type1Message(byte[] material) throws IOException {
+        parse(material);
+    }
+
+    /**
+     * Returns the supplied authentication domain.
+     *
+     * @return A <code>String</code> containing the supplied domain.
+     */
+    public String getSuppliedDomain() {
+        return suppliedDomain;
+    }
+
+    /**
+     * Sets the supplied authentication domain for this message.
+     *
+     * @param suppliedDomain The supplied domain for this message.
+     */
+    public void setSuppliedDomain(String suppliedDomain) {
+        this.suppliedDomain = suppliedDomain;
+    }
+
+    /**
+     * Returns the supplied workstation name.
+     * 
+     * @return A <code>String</code> containing the supplied workstation name.
+     */
+    public String getSuppliedWorkstation() {
+        return suppliedWorkstation;
+    }
+
+    /**
+     * Sets the supplied workstation name for this message.
+     * 
+     * @param suppliedWorkstation The supplied workstation for this message.
+     */
+    public void setSuppliedWorkstation(String suppliedWorkstation) {
+        this.suppliedWorkstation = suppliedWorkstation;
+    }
+
+    public byte[] toByteArray() {
+        try {
+            String suppliedDomain = getSuppliedDomain();
+            String suppliedWorkstation = getSuppliedWorkstation();
+            int flags = getFlags();
+            boolean hostInfo = false;
+            byte[] domain = new byte[0];
+            if (suppliedDomain != null && suppliedDomain.length() != 0) {
+                hostInfo = true;
+                flags |= NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED;
+                domain = suppliedDomain.toUpperCase().getBytes(
+                        getOEMEncoding());
+            } else {
+                flags &= (NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED ^ 0xffffffff);
+            }
+            byte[] workstation = new byte[0];
+            if (suppliedWorkstation != null &&
+                    suppliedWorkstation.length() != 0) {
+                hostInfo = true;
+                flags |= NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED;
+                workstation =
+                        suppliedWorkstation.toUpperCase().getBytes(
+                                getOEMEncoding());
+            } else {
+                flags &= (NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED ^
+                        0xffffffff);
+            }
+            byte[] type1 = new byte[hostInfo ?
+                    (32 + domain.length + workstation.length) : 16];
+            System.arraycopy(NTLMSSP_SIGNATURE, 0, type1, 0, 8);
+            writeULong(type1, 8, 1);
+            writeULong(type1, 12, flags);
+            if (hostInfo) {
+                writeSecurityBuffer(type1, 16, 32, domain);
+                writeSecurityBuffer(type1, 24, 32 + domain.length, workstation);
+            }
+            return type1;
+        } catch (IOException ex) {
+            throw new IllegalStateException(ex.getMessage());
+        }
+    }
+
+    public String toString() {
+        String suppliedDomain = getSuppliedDomain();
+        String suppliedWorkstation = getSuppliedWorkstation();
+        int flags = getFlags();
+        StringBuffer buffer = new StringBuffer();
+        if (suppliedDomain != null) {
+            buffer.append("suppliedDomain: ").append(suppliedDomain);
+        }
+        if (suppliedWorkstation != null) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("suppliedWorkstation: ").append(suppliedWorkstation);
+        }
+        if (flags != 0) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("flags: ");
+            buffer.append("0x");
+            buffer.append(Integer.toHexString((flags >> 28) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 24) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 20) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 16) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 12) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 8) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 4) & 0x0f));
+            buffer.append(Integer.toHexString(flags & 0x0f));
+        }
+        return buffer.toString();
+    }
+
+    /**
+     * Returns the default flags for a generic Type-1 message in the
+     * current environment.
+     * 
+     * @return An <code>int</code> containing the default flags.
+     */
+    public static int getDefaultFlags() {
+        return DEFAULT_FLAGS;
+    }
+
+    /**
+     * Returns the default domain from the current environment.
+     *
+     * @return A <code>String</code> containing the default domain.
+     */
+    public static String getDefaultDomain() {
+        return DEFAULT_DOMAIN;
+    }
+
+    /**
+     * Returns the default workstation from the current environment.
+     *
+     * @return A <code>String</code> containing the default workstation.
+     */
+    public static String getDefaultWorkstation() {
+        return DEFAULT_WORKSTATION;
+    }
+
+    private void parse(byte[] material) throws IOException {
+        for (int i = 0; i < 8; i++) {
+            if (material[i] != NTLMSSP_SIGNATURE[i]) {
+                throw new IOException("Not an NTLMSSP message.");
+            }
+        }
+        if (readULong(material, 8) != 1) {
+            throw new IOException("Not a Type 1 message.");
+        }
+        int flags = readULong(material, 12);
+        String suppliedDomain = null;
+        if ((flags & NTLMSSP_NEGOTIATE_OEM_DOMAIN_SUPPLIED) != 0) {
+            byte[] domain = readSecurityBuffer(material, 16);
+            suppliedDomain = new String(domain, getOEMEncoding());
+        }
+        String suppliedWorkstation = null;
+        if ((flags & NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED) != 0) {
+            byte[] workstation = readSecurityBuffer(material, 24);
+            suppliedWorkstation = new String(workstation, getOEMEncoding());
+        }
+        setFlags(flags);
+        setSuppliedDomain(suppliedDomain);
+        setSuppliedWorkstation(suppliedWorkstation);
+    }
 
 }
index bb1de85..1d92957 100644 (file)
@@ -1,6 +1,6 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                "Eric Glass" <jcifs at samba dot org>
+ *                 "Eric Glass" <jcifs at samba dot org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -32,383 +32,383 @@ import jcifs.netbios.NbtAddress;
  */
 public class Type2Message extends NtlmMessage {
 
-       private static final int DEFAULT_FLAGS;
-
-       private static final String DEFAULT_DOMAIN;
-
-       private static final byte[] DEFAULT_TARGET_INFORMATION;
-
-       private byte[] challenge;
-
-       private String target;
-
-       private byte[] context;
-
-       private byte[] targetInformation;
-
-       static {
-               DEFAULT_FLAGS = NTLMSSP_NEGOTIATE_NTLM |
-                               (Config.getBoolean("jcifs.smb.client.useUnicode", true) ?
-                                               NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM);
-               DEFAULT_DOMAIN = Config.getProperty("jcifs.smb.client.domain", null);
-               byte[] domain = new byte[0];
-               if (DEFAULT_DOMAIN != null) {
-                       try {
-                               domain = DEFAULT_DOMAIN.getBytes("UnicodeLittleUnmarked");
-                       } catch (IOException ex) { }
-               }
-               int domainLength = domain.length;
-               byte[] server = new byte[0];
-               try {
-                       String host = NbtAddress.getLocalHost().getHostName();
-                       if (host != null) {
-                               try {
-                                       server = host.getBytes("UnicodeLittleUnmarked");
-                               } catch (IOException ex) { }
-                       }
-               } catch (UnknownHostException ex) { }
-               int serverLength = server.length;
-               byte[] targetInfo = new byte[(domainLength > 0 ? domainLength + 4 : 0) +
-                               (serverLength > 0 ? serverLength + 4 : 0) + 4];
-               int offset = 0;
-               if (domainLength > 0) {
-                       writeUShort(targetInfo, offset, 2);
-                       offset += 2;
-                       writeUShort(targetInfo, offset, domainLength);
-                       offset += 2;
-                       System.arraycopy(domain, 0, targetInfo, offset, domainLength);
-                       offset += domainLength;
-               }
-               if (serverLength > 0) {
-                       writeUShort(targetInfo, offset, 1);
-                       offset += 2;
-                       writeUShort(targetInfo, offset, serverLength);
-                       offset += 2;
-                       System.arraycopy(server, 0, targetInfo, offset, serverLength);
-               }
-               DEFAULT_TARGET_INFORMATION = targetInfo;
-       }
-
-       /**
-        * Creates a Type-2 message using default values from the current
-        * environment.
-        */
-       public Type2Message() {
-               this(getDefaultFlags(), null, null);
-       }
-
-       /**
-        * Creates a Type-2 message in response to the given Type-1 message
-        * using default values from the current environment.
-        *
-        * @param type1 The Type-1 message which this represents a response to.
-        */
-       public Type2Message(Type1Message type1) {
-               this(type1, null, null);
-       }
-
-       /**
-        * Creates a Type-2 message in response to the given Type-1 message.
-        *
-        * @param type1 The Type-1 message which this represents a response to.
-        * @param challenge The challenge from the domain controller/server.
-        * @param target The authentication target.
-        */
-       public Type2Message(Type1Message type1, byte[] challenge, String target) {
-               this(getDefaultFlags(type1), challenge, (type1 != null &&
-                               target == null && type1.getFlag(NTLMSSP_REQUEST_TARGET)) ?
-                                               getDefaultDomain() : target);
-       }
-
-       /**
-        * Creates a Type-2 message with the specified parameters.
-        *
-        * @param flags The flags to apply to this message.
-        * @param challenge The challenge from the domain controller/server.
-        * @param target The authentication target.
-        */
-       public Type2Message(int flags, byte[] challenge, String target) {
-               setFlags(flags);
-               setChallenge(challenge);
-               setTarget(target);
-               if (target != null) setTargetInformation(getDefaultTargetInformation());
-       }
-
-       /**
-        * Creates a Type-2 message using the given raw Type-2 material.
-        *
-        * @param material The raw Type-2 material used to construct this message.
-        * @throws IOException If an error occurs while parsing the material.
-        */
-       public Type2Message(byte[] material) throws IOException {
-               parse(material);
-       }
-
-       /**
-        * Returns the challenge for this message.
-        *
-        * @return A <code>byte[]</code> containing the challenge.
-        */
-       public byte[] getChallenge() {
-               return challenge;
-       }
-
-       /**
-        * Sets the challenge for this message.
-        *
-        * @param challenge The challenge from the domain controller/server.
-        */
-       public void setChallenge(byte[] challenge) {
-               this.challenge = challenge;
-       }
-
-       /**
-        * Returns the authentication target.
-        *
-        * @return A <code>String</code> containing the authentication target.
-        */
-       public String getTarget() {
-               return target;
-       }
-
-       /**
-        * Sets the authentication target.
-        *
-        * @param target The authentication target.
-        */
-       public void setTarget(String target) {
-               this.target = target;
-       }
-
-       /**
-        * Returns the target information block.
-        *
-        * @return A <code>byte[]</code> containing the target information block.
-        * The target information block is used by the client to create an
-        * NTLMv2 response.
-        */ 
-       public byte[] getTargetInformation() {
-               return targetInformation;
-       }
-
-       /**
-        * Sets the target information block.
-        * The target information block is used by the client to create
-        * an NTLMv2 response.
-        
-        * @param targetInformation The target information block.
-        */
-       public void setTargetInformation(byte[] targetInformation) {
-               this.targetInformation = targetInformation;
-       }
-
-       /**
-        * Returns the local security context.
-        *
-        * @return A <code>byte[]</code> containing the local security
-        * context.  This is used by the client to negotiate local
-        * authentication.
-        */
-       public byte[] getContext() {
-               return context;
-       }
-
-       /**
-        * Sets the local security context.  This is used by the client
-        * to negotiate local authentication.
-        *
-        * @param context The local security context.
-        */
-       public void setContext(byte[] context) {
-               this.context = context;
-       }
-
-       public byte[] toByteArray() {
-               try {
-                       String targetName = getTarget();
-                       byte[] challenge = getChallenge();
-                       byte[] context = getContext();
-                       byte[] targetInformation = getTargetInformation();
-                       int flags = getFlags();
-                       byte[] target = new byte[0];
-                       if ((flags & (NTLMSSP_TARGET_TYPE_DOMAIN |
-                                       NTLMSSP_TARGET_TYPE_SERVER |
-                                                       NTLMSSP_TARGET_TYPE_SHARE)) != 0) {
-                               if (targetName != null && targetName.length() != 0) {
-                                       target = (flags & NTLMSSP_NEGOTIATE_UNICODE) != 0 ?
-                                                       targetName.getBytes("UnicodeLittleUnmarked") :
-                                                       targetName.toUpperCase().getBytes(getOEMEncoding());
-                               } else {
-                                       flags &= (0xffffffff ^ (NTLMSSP_TARGET_TYPE_DOMAIN |
-                                                       NTLMSSP_TARGET_TYPE_SERVER |
-                                                                       NTLMSSP_TARGET_TYPE_SHARE));
-                               }
-                       }
-                       if (targetInformation != null) {
-                               flags ^= NTLMSSP_NEGOTIATE_TARGET_INFO;
-                               // empty context is needed for padding when t.i. is supplied.
-                               if (context == null) context = new byte[8];
-                       }
-                       int data = 32;
-                       if (context != null) data += 8;
-                       if (targetInformation != null) data += 8;
-                       byte[] type2 = new byte[data + target.length +
-                                       (targetInformation != null ? targetInformation.length : 0)];
-                       System.arraycopy(NTLMSSP_SIGNATURE, 0, type2, 0, 8);
-                       writeULong(type2, 8, 2);
-                       writeSecurityBuffer(type2, 12, data, target);
-                       writeULong(type2, 20, flags);
-                       System.arraycopy(challenge != null ? challenge : new byte[8], 0,
-                                       type2, 24, 8);
-                       if (context != null) System.arraycopy(context, 0, type2, 32, 8);
-                       if (targetInformation != null) {
-                               writeSecurityBuffer(type2, 40, data + target.length,
-                                               targetInformation);
-                       }
-                       return type2;
-               } catch (IOException ex) {
-                       throw new IllegalStateException(ex.getMessage());
-               }
-       }
-
-       public String toString() {
-               String target = getTarget();
-               byte[] challenge = getChallenge();
-               byte[] context = getContext();
-               byte[] targetInformation = getTargetInformation();
-               int flags = getFlags();
-               StringBuffer buffer = new StringBuffer();
-               if (target != null) {
-                       buffer.append("target: ").append(target);
-               }
-               if (challenge != null) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("challenge: ");
-                       buffer.append("0x");
-                       for (int i = 0; i < challenge.length; i++) {
-                               buffer.append(Integer.toHexString((challenge[i] >> 4) & 0x0f));
-                               buffer.append(Integer.toHexString(challenge[i] & 0x0f));
-                       }
-               }
-               if (context != null) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("context: ");
-                       buffer.append("0x");
-                       for (int i = 0; i < context.length; i++) {
-                               buffer.append(Integer.toHexString((context[i] >> 4) & 0x0f));
-                               buffer.append(Integer.toHexString(context[i] & 0x0f));
-                       }
-               }
-               if (targetInformation != null) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("targetInformation: ");
-                       buffer.append("0x");
-                       for (int i = 0; i < targetInformation.length; i++) {
-                               buffer.append(Integer.toHexString((targetInformation[i] >> 4) &
-                                               0x0f));
-                               buffer.append(Integer.toHexString(targetInformation[i] & 0x0f));
-                       }
-               }
-               if (flags != 0) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("flags: ");
-                       buffer.append("0x");
-                       buffer.append(Integer.toHexString((flags >> 28) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 24) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 20) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 16) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 12) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 8) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 4) & 0x0f));
-                       buffer.append(Integer.toHexString(flags & 0x0f));
-               }
-               return buffer.toString();
-       }
-
-       /**
-        * Returns the default flags for a generic Type-2 message in the
-        * current environment.
-        *
-        * @return An <code>int</code> containing the default flags.
-        */
-       public static int getDefaultFlags() {
-               return DEFAULT_FLAGS;
-       }
-
-       /**
-        * Returns the default flags for a Type-2 message created in response
-        * to the given Type-1 message in the current environment.
-        *
-        * @return An <code>int</code> containing the default flags.
-        */
-       public static int getDefaultFlags(Type1Message type1) {
-               if (type1 == null) return DEFAULT_FLAGS;
-               int flags = NTLMSSP_NEGOTIATE_NTLM;
-               int type1Flags = type1.getFlags();
-               flags |= ((type1Flags & NTLMSSP_NEGOTIATE_UNICODE) != 0) ?
-                               NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM;
-               if ((type1Flags & NTLMSSP_REQUEST_TARGET) != 0) {
-                       String domain = getDefaultDomain();
-                       if (domain != null) {
-                               flags |= NTLMSSP_REQUEST_TARGET | NTLMSSP_TARGET_TYPE_DOMAIN;
-                       }
-               }
-               return flags;
-       }
-
-       /**
-        * Returns the default domain from the current environment.
-        *
-        * @return A <code>String</code> containing the domain.
-        */
-       public static String getDefaultDomain() {
-               return DEFAULT_DOMAIN;
-       }
-
-       public static byte[] getDefaultTargetInformation() {
-               return DEFAULT_TARGET_INFORMATION;
-       }
-
-       private void parse(byte[] material) throws IOException {
-               for (int i = 0; i < 8; i++) {
-                       if (material[i] != NTLMSSP_SIGNATURE[i]) {
-                               throw new IOException("Not an NTLMSSP message.");
-                       }
-               }
-               if (readULong(material, 8) != 2) {
-                       throw new IOException("Not a Type 2 message.");
-               }
-               int flags = readULong(material, 20);
-               setFlags(flags);
-               String target = null;
-               byte[] bytes = readSecurityBuffer(material, 12);
-               if (bytes.length != 0) {
-                       target = new String(bytes,
-                                       ((flags & NTLMSSP_NEGOTIATE_UNICODE) != 0) ?
-                                                       "UnicodeLittleUnmarked" : getOEMEncoding());
-               }
-               setTarget(target);
-               for (int i = 24; i < 32; i++) {
-                       if (material[i] != 0) {
-                               byte[] challenge = new byte[8];
-                               System.arraycopy(material, 24, challenge, 0, 8);
-                               setChallenge(challenge);
-                               break;
-                       }
-               }
-               int offset = readULong(material, 16); // offset of targetname start
-               if (offset == 32 || material.length == 32) return;
-               for (int i = 32; i < 40; i++) {
-                       if (material[i] != 0) {
-                               byte[] context = new byte[8];
-                               System.arraycopy(material, 32, context, 0, 8);
-                               setContext(context);
-                               break;
-                       }
-               }
-               if (offset == 40 || material.length == 40) return;
-               bytes = readSecurityBuffer(material, 40);
-               if (bytes.length != 0) setTargetInformation(bytes);
-       }
+    private static final int DEFAULT_FLAGS;
+
+    private static final String DEFAULT_DOMAIN;
+
+    private static final byte[] DEFAULT_TARGET_INFORMATION;
+
+    private byte[] challenge;
+
+    private String target;
+
+    private byte[] context;
+
+    private byte[] targetInformation;
+
+    static {
+        DEFAULT_FLAGS = NTLMSSP_NEGOTIATE_NTLM |
+                (Config.getBoolean("jcifs.smb.client.useUnicode", true) ?
+                        NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM);
+        DEFAULT_DOMAIN = Config.getProperty("jcifs.smb.client.domain", null);
+        byte[] domain = new byte[0];
+        if (DEFAULT_DOMAIN != null) {
+            try {
+                domain = DEFAULT_DOMAIN.getBytes("UnicodeLittleUnmarked");
+            } catch (IOException ex) { }
+        }
+        int domainLength = domain.length;
+        byte[] server = new byte[0];
+        try {
+            String host = NbtAddress.getLocalHost().getHostName();
+            if (host != null) {
+                try {
+                    server = host.getBytes("UnicodeLittleUnmarked");
+                } catch (IOException ex) { }
+            }
+        } catch (UnknownHostException ex) { }
+        int serverLength = server.length;
+        byte[] targetInfo = new byte[(domainLength > 0 ? domainLength + 4 : 0) +
+                (serverLength > 0 ? serverLength + 4 : 0) + 4];
+        int offset = 0;
+        if (domainLength > 0) {
+            writeUShort(targetInfo, offset, 2);
+            offset += 2;
+            writeUShort(targetInfo, offset, domainLength);
+            offset += 2;
+            System.arraycopy(domain, 0, targetInfo, offset, domainLength);
+            offset += domainLength;
+        }
+        if (serverLength > 0) {
+            writeUShort(targetInfo, offset, 1);
+            offset += 2;
+            writeUShort(targetInfo, offset, serverLength);
+            offset += 2;
+            System.arraycopy(server, 0, targetInfo, offset, serverLength);
+        }
+        DEFAULT_TARGET_INFORMATION = targetInfo;
+    }
+
+    /**
+     * Creates a Type-2 message using default values from the current
+     * environment.
+     */
+    public Type2Message() {
+        this(getDefaultFlags(), null, null);
+    }
+
+    /**
+     * Creates a Type-2 message in response to the given Type-1 message
+     * using default values from the current environment.
+     *
+     * @param type1 The Type-1 message which this represents a response to.
+     */
+    public Type2Message(Type1Message type1) {
+        this(type1, null, null);
+    }
+
+    /**
+     * Creates a Type-2 message in response to the given Type-1 message.
+     *
+     * @param type1 The Type-1 message which this represents a response to.
+     * @param challenge The challenge from the domain controller/server.
+     * @param target The authentication target.
+     */
+    public Type2Message(Type1Message type1, byte[] challenge, String target) {
+        this(getDefaultFlags(type1), challenge, (type1 != null &&
+                target == null && type1.getFlag(NTLMSSP_REQUEST_TARGET)) ?
+                        getDefaultDomain() : target);
+    }
+
+    /**
+     * Creates a Type-2 message with the specified parameters.
+     *
+     * @param flags The flags to apply to this message.
+     * @param challenge The challenge from the domain controller/server.
+     * @param target The authentication target.
+     */
+    public Type2Message(int flags, byte[] challenge, String target) {
+        setFlags(flags);
+        setChallenge(challenge);
+        setTarget(target);
+        if (target != null) setTargetInformation(getDefaultTargetInformation());
+    }
+
+    /**
+     * Creates a Type-2 message using the given raw Type-2 material.
+     *
+     * @param material The raw Type-2 material used to construct this message.
+     * @throws IOException If an error occurs while parsing the material.
+     */
+    public Type2Message(byte[] material) throws IOException {
+        parse(material);
+    }
+
+    /**
+     * Returns the challenge for this message.
+     *
+     * @return A <code>byte[]</code> containing the challenge.
+     */
+    public byte[] getChallenge() {
+        return challenge;
+    }
+
+    /**
+     * Sets the challenge for this message.
+     *
+     * @param challenge The challenge from the domain controller/server.
+     */
+    public void setChallenge(byte[] challenge) {
+        this.challenge = challenge;
+    }
+
+    /**
+     * Returns the authentication target.
+     *
+     * @return A <code>String</code> containing the authentication target.
+     */
+    public String getTarget() {
+        return target;
+    }
+
+    /**
+     * Sets the authentication target.
+     *
+     * @param target The authentication target.
+     */
+    public void setTarget(String target) {
+        this.target = target;
+    }
+
+    /**
+     * Returns the target information block.
+     *
+     * @return A <code>byte[]</code> containing the target information block.
+     * The target information block is used by the client to create an
+     * NTLMv2 response.
+     */ 
+    public byte[] getTargetInformation() {
+        return targetInformation;
+    }
+
+    /**
+     * Sets the target information block.
+     * The target information block is used by the client to create
+     * an NTLMv2 response.
+     * 
+     * @param targetInformation The target information block.
+     */
+    public void setTargetInformation(byte[] targetInformation) {
+        this.targetInformation = targetInformation;
+    }
+
+    /**
+     * Returns the local security context.
+     *
+     * @return A <code>byte[]</code> containing the local security
+     * context.  This is used by the client to negotiate local
+     * authentication.
+     */
+    public byte[] getContext() {
+        return context;
+    }
+
+    /**
+     * Sets the local security context.  This is used by the client
+     * to negotiate local authentication.
+     *
+     * @param context The local security context.
+     */
+    public void setContext(byte[] context) {
+        this.context = context;
+    }
+
+    public byte[] toByteArray() {
+        try {
+            String targetName = getTarget();
+            byte[] challenge = getChallenge();
+            byte[] context = getContext();
+            byte[] targetInformation = getTargetInformation();
+            int flags = getFlags();
+            byte[] target = new byte[0];
+            if ((flags & (NTLMSSP_TARGET_TYPE_DOMAIN |
+                    NTLMSSP_TARGET_TYPE_SERVER |
+                            NTLMSSP_TARGET_TYPE_SHARE)) != 0) {
+                if (targetName != null && targetName.length() != 0) {
+                    target = (flags & NTLMSSP_NEGOTIATE_UNICODE) != 0 ?
+                            targetName.getBytes("UnicodeLittleUnmarked") :
+                            targetName.toUpperCase().getBytes(getOEMEncoding());
+                } else {
+                    flags &= (0xffffffff ^ (NTLMSSP_TARGET_TYPE_DOMAIN |
+                            NTLMSSP_TARGET_TYPE_SERVER |
+                                    NTLMSSP_TARGET_TYPE_SHARE));
+                }
+            }
+            if (targetInformation != null) {
+                flags ^= NTLMSSP_NEGOTIATE_TARGET_INFO;
+                // empty context is needed for padding when t.i. is supplied.
+                if (context == null) context = new byte[8];
+            }
+            int data = 32;
+            if (context != null) data += 8;
+            if (targetInformation != null) data += 8;
+            byte[] type2 = new byte[data + target.length +
+                    (targetInformation != null ? targetInformation.length : 0)];
+            System.arraycopy(NTLMSSP_SIGNATURE, 0, type2, 0, 8);
+            writeULong(type2, 8, 2);
+            writeSecurityBuffer(type2, 12, data, target);
+            writeULong(type2, 20, flags);
+            System.arraycopy(challenge != null ? challenge : new byte[8], 0,
+                    type2, 24, 8);
+            if (context != null) System.arraycopy(context, 0, type2, 32, 8);
+            if (targetInformation != null) {
+                writeSecurityBuffer(type2, 40, data + target.length,
+                        targetInformation);
+            }
+            return type2;
+        } catch (IOException ex) {
+            throw new IllegalStateException(ex.getMessage());
+        }
+    }
+
+    public String toString() {
+        String target = getTarget();
+        byte[] challenge = getChallenge();
+        byte[] context = getContext();
+        byte[] targetInformation = getTargetInformation();
+        int flags = getFlags();
+        StringBuffer buffer = new StringBuffer();
+        if (target != null) {
+            buffer.append("target: ").append(target);
+        }
+        if (challenge != null) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("challenge: ");
+            buffer.append("0x");
+            for (int i = 0; i < challenge.length; i++) {
+                buffer.append(Integer.toHexString((challenge[i] >> 4) & 0x0f));
+                buffer.append(Integer.toHexString(challenge[i] & 0x0f));
+            }
+        }
+        if (context != null) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("context: ");
+            buffer.append("0x");
+            for (int i = 0; i < context.length; i++) {
+                buffer.append(Integer.toHexString((context[i] >> 4) & 0x0f));
+                buffer.append(Integer.toHexString(context[i] & 0x0f));
+            }
+        }
+        if (targetInformation != null) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("targetInformation: ");
+            buffer.append("0x");
+            for (int i = 0; i < targetInformation.length; i++) {
+                buffer.append(Integer.toHexString((targetInformation[i] >> 4) &
+                        0x0f));
+                buffer.append(Integer.toHexString(targetInformation[i] & 0x0f));
+            }
+        }
+        if (flags != 0) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("flags: ");
+            buffer.append("0x");
+            buffer.append(Integer.toHexString((flags >> 28) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 24) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 20) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 16) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 12) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 8) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 4) & 0x0f));
+            buffer.append(Integer.toHexString(flags & 0x0f));
+        }
+        return buffer.toString();
+    }
+
+    /**
+     * Returns the default flags for a generic Type-2 message in the
+     * current environment.
+     *
+     * @return An <code>int</code> containing the default flags.
+     */
+    public static int getDefaultFlags() {
+        return DEFAULT_FLAGS;
+    }
+
+    /**
+     * Returns the default flags for a Type-2 message created in response
+     * to the given Type-1 message in the current environment.
+     *
+     * @return An <code>int</code> containing the default flags.
+     */
+    public static int getDefaultFlags(Type1Message type1) {
+        if (type1 == null) return DEFAULT_FLAGS;
+        int flags = NTLMSSP_NEGOTIATE_NTLM;
+        int type1Flags = type1.getFlags();
+        flags |= ((type1Flags & NTLMSSP_NEGOTIATE_UNICODE) != 0) ?
+                NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM;
+        if ((type1Flags & NTLMSSP_REQUEST_TARGET) != 0) {
+            String domain = getDefaultDomain();
+            if (domain != null) {
+                flags |= NTLMSSP_REQUEST_TARGET | NTLMSSP_TARGET_TYPE_DOMAIN;
+            }
+        }
+        return flags;
+    }
+
+    /**
+     * Returns the default domain from the current environment.
+     *
+     * @return A <code>String</code> containing the domain.
+     */
+    public static String getDefaultDomain() {
+        return DEFAULT_DOMAIN;
+    }
+
+    public static byte[] getDefaultTargetInformation() {
+        return DEFAULT_TARGET_INFORMATION;
+    }
+
+    private void parse(byte[] material) throws IOException {
+        for (int i = 0; i < 8; i++) {
+            if (material[i] != NTLMSSP_SIGNATURE[i]) {
+                throw new IOException("Not an NTLMSSP message.");
+            }
+        }
+        if (readULong(material, 8) != 2) {
+            throw new IOException("Not a Type 2 message.");
+        }
+        int flags = readULong(material, 20);
+        setFlags(flags);
+        String target = null;
+        byte[] bytes = readSecurityBuffer(material, 12);
+        if (bytes.length != 0) {
+            target = new String(bytes,
+                    ((flags & NTLMSSP_NEGOTIATE_UNICODE) != 0) ?
+                            "UnicodeLittleUnmarked" : getOEMEncoding());
+        }
+        setTarget(target);
+        for (int i = 24; i < 32; i++) {
+            if (material[i] != 0) {
+                byte[] challenge = new byte[8];
+                System.arraycopy(material, 24, challenge, 0, 8);
+                setChallenge(challenge);
+                break;
+            }
+        }
+        int offset = readULong(material, 16); // offset of targetname start
+        if (offset == 32 || material.length == 32) return;
+        for (int i = 32; i < 40; i++) {
+            if (material[i] != 0) {
+                byte[] context = new byte[8];
+                System.arraycopy(material, 32, context, 0, 8);
+                setContext(context);
+                break;
+            }
+        }
+        if (offset == 40 || material.length == 40) return;
+        bytes = readSecurityBuffer(material, 40);
+        if (bytes.length != 0) setTargetInformation(bytes);
+    }
 
 }
index c11f1fc..bcac159 100644 (file)
@@ -1,6 +1,6 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                "Eric Glass" <jcifs at samba dot org>
+ *                 "Eric Glass" <jcifs at samba dot org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -36,545 +36,545 @@ import jcifs.smb.NtlmPasswordAuthentication;
  */
 public class Type3Message extends NtlmMessage {
 
-       private static final int DEFAULT_FLAGS;
-
-       private static final String DEFAULT_DOMAIN;
-
-       private static final String DEFAULT_USER;
-
-       private static final String DEFAULT_PASSWORD;
-
-       private static final String DEFAULT_WORKSTATION;
-
-       private static final int LM_COMPATIBILITY;
-
-       private static final SecureRandom RANDOM = new SecureRandom();
-
-       private byte[] lmResponse;
-
-       private byte[] ntResponse;
-
-       private String domain;
-
-       private String user;
-
-       private String workstation;
-
-       private byte[] sessionKey;
-
-       static {
-               DEFAULT_FLAGS = NTLMSSP_NEGOTIATE_NTLM |
-                               (Config.getBoolean("jcifs.smb.client.useUnicode", true) ?
-                                               NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM);
-               DEFAULT_DOMAIN = Config.getProperty("jcifs.smb.client.domain", null);
-               DEFAULT_USER = Config.getProperty("jcifs.smb.client.username", null);
-               DEFAULT_PASSWORD = Config.getProperty("jcifs.smb.client.password",
-                               null);
-               String defaultWorkstation = null;
-               try {
-                       defaultWorkstation = NbtAddress.getLocalHost().getHostName();
-               } catch (UnknownHostException ex) { }
-               DEFAULT_WORKSTATION = defaultWorkstation;
-               LM_COMPATIBILITY = Config.getInt("jcifs.smb.lmCompatibility", 0);
-       }
-
-       /**
-        * Creates a Type-3 message using default values from the current
-        * environment.
-        */
-       public Type3Message() {
-               setFlags(getDefaultFlags());
-               setDomain(getDefaultDomain());
-               setUser(getDefaultUser());
-               setWorkstation(getDefaultWorkstation());
-       }
-
-       /**
-        * Creates a Type-3 message in response to the given Type-2 message
-        * using default values from the current environment.
-        *
-        * @param type2 The Type-2 message which this represents a response to.
-        */
-       public Type3Message(Type2Message type2) {
-               setFlags(getDefaultFlags(type2));
-               setWorkstation(getDefaultWorkstation());
-               String domain = getDefaultDomain();
-               setDomain(domain);
-               String user = getDefaultUser();
-               setUser(user);
-               String password = getDefaultPassword();
-               switch (LM_COMPATIBILITY) {
-               case 0:
-               case 1:
-                       setLMResponse(getLMResponse(type2, password));
-                       setNTResponse(getNTResponse(type2, password));
-                       break;
-               case 2:
-                       byte[] nt = getNTResponse(type2, password);
-                       setLMResponse(nt);
-                       setNTResponse(nt);
-                       break;
-               case 3:
-               case 4:
-               case 5:
-                       byte[] clientChallenge = new byte[8];
-                       RANDOM.nextBytes(clientChallenge);
-                       setLMResponse(getLMv2Response(type2, domain, user, password,
-                                       clientChallenge));
-                       /*
-                       setNTResponse(getNTLMv2Response(type2, domain, user, password,
-                                       clientChallenge));
-                       */
-                       break;
-               default:
-                       setLMResponse(getLMResponse(type2, password));
-                       setNTResponse(getNTResponse(type2, password));
-               }
-       }
-
-       /**
-        * Creates a Type-3 message in response to the given Type-2 message.
-        *
-        * @param type2 The Type-2 message which this represents a response to.
-        * @param password The password to use when constructing the response.
-        * @param domain The domain in which the user has an account.
-        * @param user The username for the authenticating user.
-        * @param workstation The workstation from which authentication is
-        * taking place.
-        */
-       public Type3Message(Type2Message type2, String password, String domain,
-                       String user, String workstation) {
-               setFlags(getDefaultFlags(type2));
-               setDomain(domain);
-               setUser(user);
-               setWorkstation(workstation);
-               switch (LM_COMPATIBILITY) {
-               case 0:
-               case 1:
-                       setLMResponse(getLMResponse(type2, password));
-                       setNTResponse(getNTResponse(type2, password));
-                       break;
-               case 2:
-                       byte[] nt = getNTResponse(type2, password);
-                       setLMResponse(nt);
-                       setNTResponse(nt);
-                       break;
-               case 3:
-               case 4:
-               case 5:
-                       byte[] clientChallenge = new byte[8];
-                       RANDOM.nextBytes(clientChallenge);
-                       setLMResponse(getLMv2Response(type2, domain, user, password,
-                                       clientChallenge));
-                       /*
-                       setNTResponse(getNTLMv2Response(type2, domain, user, password,
-                                       clientChallenge));
-                       */
-                       break;
-               default:
-                       setLMResponse(getLMResponse(type2, password));
-                       setNTResponse(getNTResponse(type2, password));
-               }
-       }
-
-       /**
-        * Creates a Type-3 message with the specified parameters.
-        *
-        * @param flags The flags to apply to this message.
-        * @param lmResponse The LanManager/LMv2 response.
-        * @param domain The NT/NTLMv2 response.
-        * @param domain The domain in which the user has an account.
-        * @param user The username for the authenticating user.
-        * @param workstation The workstation from which authentication is
-        * taking place.
-        */
-       public Type3Message(int flags, byte[] lmResponse, byte[] ntResponse,
-                       String domain, String user, String workstation) {
-               setFlags(flags);
-               setLMResponse(lmResponse);
-               setNTResponse(ntResponse);
-               setDomain(domain);
-               setUser(user);
-               setWorkstation(workstation);
-       }
-
-       /**
-        * Creates a Type-3 message using the given raw Type-3 material.
-        *
-        * @param material The raw Type-3 material used to construct this message.
-        * @throws IOException If an error occurs while parsing the material.
-        */
-       public Type3Message(byte[] material) throws IOException {
-               parse(material);
-       }
-
-       /**
-        * Returns the LanManager/LMv2 response.
-        *
-        * @return A <code>byte[]</code> containing the LanManager response.
-        */
-       public byte[] getLMResponse() {
-               return lmResponse;
-       }
-
-       /**
-        * Sets the LanManager/LMv2 response for this message.
-        *
-        * @param lmResponse The LanManager response.
-        */
-       public void setLMResponse(byte[] lmResponse) {
-               this.lmResponse = lmResponse;
-       }
-
-       /**
-        * Returns the NT/NTLMv2 response.
-        *
-        * @return A <code>byte[]</code> containing the NT/NTLMv2 response.
-        */
-       public byte[] getNTResponse() {
-               return ntResponse;
-       }
-
-       /**
-        * Sets the NT/NTLMv2 response for this message.
-        *
-        * @param lmResponse The NT/NTLMv2 response.
-        */
-       public void setNTResponse(byte[] ntResponse) {
-               this.ntResponse = ntResponse;
-       }
-
-       /**
-        * Returns the domain in which the user has an account.
-        *
-        * @return A <code>String</code> containing the domain for the user.
-        */
-       public String getDomain() {
-               return domain;
-       }
-
-       /**
-        * Sets the domain for this message.
-        *
-        * @param domain The domain.
-        */
-       public void setDomain(String domain) {
-               this.domain = domain;
-       }
-
-       /**
-        * Returns the username for the authenticating user.
-        *
-        * @return A <code>String</code> containing the user for this message.
-        */
-       public String getUser() {
-               return user;
-       }
-
-       /**
-        * Sets the user for this message.
-        *
-        * @param user The user.
-        */
-       public void setUser(String user) {
-               this.user = user;
-       }
-
-       /**
-        * Returns the workstation from which authentication is being performed.
-        *
-        * @return A <code>String</code> containing the workstation.
-        */
-       public String getWorkstation() {
-               return workstation;
-       }
-
-       /**
-        * Sets the workstation for this message.
-        *
-        * @param workstation The workstation.
-        */
-       public void setWorkstation(String workstation) {
-               this.workstation = workstation;
-       }
-
-       /**
-        * Returns the session key.
-        *
-        * @return A <code>byte[]</code> containing the session key.
-        */
-       public byte[] getSessionKey() {
-               return sessionKey;
-       }
-
-       /**
-        * Sets the session key.
-        *
-        * @param sessionKey The session key.
-        */
-       public void setSessionKey(byte[] sessionKey) {
-               this.sessionKey = sessionKey;
-       }
-
-       public byte[] toByteArray() {
-               try {
-                       int flags = getFlags();
-                       boolean unicode = (flags & NTLMSSP_NEGOTIATE_UNICODE) != 0;
-                       String oem = unicode ? null : getOEMEncoding();
-                       String domainName = getDomain();
-                       byte[] domain = null;
-                       if (domainName != null && domainName.length() != 0) {
-                               domain = unicode ?
-                                               domainName.getBytes("UnicodeLittleUnmarked") :
-                                                               domainName.toUpperCase().getBytes(oem);
-                       }
-                       int domainLength = (domain != null) ? domain.length : 0;
-                       String userName = getUser();
-                       byte[] user = null;
-                       if (userName != null && userName.length() != 0) {
-                               user = unicode ? userName.getBytes("UnicodeLittleUnmarked") :
-                                               userName.toUpperCase().getBytes(oem);
-                       }
-                       int userLength = (user != null) ? user.length : 0;
-                       String workstationName = getWorkstation();
-                       byte[] workstation = null;
-                       if (workstationName != null && workstationName.length() != 0) {
-                               workstation = unicode ?
-                                               workstationName.getBytes("UnicodeLittleUnmarked") :
-                                                               workstationName.toUpperCase().getBytes(oem);
-                       }
-                       int workstationLength = (workstation != null) ?
-                                       workstation.length : 0;
-                       byte[] lmResponse = getLMResponse();
-                       int lmLength = (lmResponse != null) ? lmResponse.length : 0;
-                       byte[] ntResponse = getNTResponse();
-                       int ntLength = (ntResponse != null) ? ntResponse.length : 0;
-                       byte[] sessionKey = getSessionKey();
-                       int keyLength = (sessionKey != null) ? sessionKey.length : 0;
-                       byte[] type3 = new byte[64 + domainLength + userLength +
-                                       workstationLength + lmLength + ntLength + keyLength];
-                       System.arraycopy(NTLMSSP_SIGNATURE, 0, type3, 0, 8);
-                       writeULong(type3, 8, 3);
-                       int offset = 64;
-                       writeSecurityBuffer(type3, 12, offset, lmResponse);
-                       offset += lmLength;
-                       writeSecurityBuffer(type3, 20, offset, ntResponse);
-                       offset += ntLength;
-                       writeSecurityBuffer(type3, 28, offset, domain);
-                       offset += domainLength;
-                       writeSecurityBuffer(type3, 36, offset, user);
-                       offset += userLength;
-                       writeSecurityBuffer(type3, 44, offset, workstation);
-                       offset += workstationLength;
-                       writeSecurityBuffer(type3, 52, offset, sessionKey);
-                       writeULong(type3, 60, flags);
-                       return type3;
-               } catch (IOException ex) {
-                       throw new IllegalStateException(ex.getMessage());
-               }
-       }
-
-       public String toString() {
-               String user = getUser();
-               String domain = getDomain();
-               String workstation = getWorkstation();
-               byte[] lmResponse = getLMResponse();
-               byte[] ntResponse = getNTResponse();
-               byte[] sessionKey = getSessionKey();
-               int flags = getFlags();
-               StringBuffer buffer = new StringBuffer();
-               if (domain != null) {
-                       buffer.append("domain: ").append(domain);
-               }
-               if (user != null) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("user: ").append(user);
-               }
-               if (workstation != null) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("workstation: ").append(workstation);
-               }
-               if (lmResponse != null) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("lmResponse: ");
-                       buffer.append("0x");
-                       for (int i = 0; i < lmResponse.length; i++) {
-                               buffer.append(Integer.toHexString((lmResponse[i] >> 4) & 0x0f));
-                               buffer.append(Integer.toHexString(lmResponse[i] & 0x0f));
-                       }
-               }
-               if (ntResponse != null) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("ntResponse: ");
-                       buffer.append("0x");
-                       for (int i = 0; i < ntResponse.length; i++) {
-                               buffer.append(Integer.toHexString((ntResponse[i] >> 4) & 0x0f));
-                               buffer.append(Integer.toHexString(ntResponse[i] & 0x0f));
-                       }
-               }
-               if (sessionKey != null) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("sessionKey: ");
-                       buffer.append("0x");
-                       for (int i = 0; i < sessionKey.length; i++) {
-                               buffer.append(Integer.toHexString((sessionKey[i] >> 4) & 0x0f));
-                               buffer.append(Integer.toHexString(sessionKey[i] & 0x0f));
-                       }
-               }
-               if (flags != 0) {
-                       if (buffer.length() > 0) buffer.append("; ");
-                       buffer.append("flags: ");
-                       buffer.append("0x");
-                       buffer.append(Integer.toHexString((flags >> 28) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 24) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 20) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 16) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 12) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 8) & 0x0f));
-                       buffer.append(Integer.toHexString((flags >> 4) & 0x0f));
-                       buffer.append(Integer.toHexString(flags & 0x0f));
-               }
-               return buffer.toString();
-       }
-
-       /**
-        * Returns the default flags for a generic Type-3 message in the
-        * current environment.
-        *
-        * @return An <code>int</code> containing the default flags.
-        */
-       public static int getDefaultFlags() {
-               return DEFAULT_FLAGS;
-       }
-
-       /**
-        * Returns the default flags for a Type-3 message created in response
-        * to the given Type-2 message in the current environment.
-        *
-        * @return An <code>int</code> containing the default flags.
-        */
-       public static int getDefaultFlags(Type2Message type2) {
-               if (type2 == null) return DEFAULT_FLAGS;
-               int flags = NTLMSSP_NEGOTIATE_NTLM;
-               flags |= ((type2.getFlags() & NTLMSSP_NEGOTIATE_UNICODE) != 0) ?
-                               NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM;
-               return flags;
-       }
-
-       /**
-        * Constructs the LanManager response to the given Type-2 message using
-        * the supplied password.
-        *
-        * @param type2 The Type-2 message.
-        * @param password The password.
-        * @return A <code>byte[]</code> containing the LanManager response.
-        */
-       public static byte[] getLMResponse(Type2Message type2, String password) {
-               if (type2 == null || password == null) return null;
-               return NtlmPasswordAuthentication.getPreNTLMResponse(password,
-                               type2.getChallenge());
-       }
-
-       public static byte[] getLMv2Response(Type2Message type2,
-                       String domain, String user, String password,
-                                       byte[] clientChallenge) {
-               if (type2 == null || domain == null || user == null ||
-                               password == null || clientChallenge == null) {
-                       return null;
-               }
-               return NtlmPasswordAuthentication.getLMv2Response(domain, user,
-                               password, type2.getChallenge(), clientChallenge);
-       }
-
-       /**
-        * Constructs the NT response to the given Type-2 message using
-        * the supplied password.
-        *
-        * @param type2 The Type-2 message.
-        * @param password The password.
-        * @return A <code>byte[]</code> containing the NT response.
-        */
-       public static byte[] getNTResponse(Type2Message type2, String password) {
-               if (type2 == null || password == null) return null;
-               return NtlmPasswordAuthentication.getNTLMResponse(password,
-                               type2.getChallenge());
-       }
-
-       /**
-        * Returns the default domain from the current environment.
-        *
-        * @return The default domain.
-        */
-       public static String getDefaultDomain() {
-               return DEFAULT_DOMAIN;
-       }
-
-       /**
-        * Returns the default user from the current environment.
-        *
-        * @return The default user.
-        */
-       public static String getDefaultUser() {
-               return DEFAULT_USER;
-       }
-
-       /**
-        * Returns the default password from the current environment.
-        *
-        * @return The default password.
-        */
-       public static String getDefaultPassword() {
-               return DEFAULT_PASSWORD;
-       }
-
-       /**
-        * Returns the default workstation from the current environment.
-        *
-        * @return The default workstation.
-        */
-       public static String getDefaultWorkstation() {
-               return DEFAULT_WORKSTATION;
-       }
-
-       private void parse(byte[] material) throws IOException {
-               for (int i = 0; i < 8; i++) {
-                       if (material[i] != NTLMSSP_SIGNATURE[i]) {
-                               throw new IOException("Not an NTLMSSP message.");
-                       }
-               }
-               if (readULong(material, 8) != 3) {
-                       throw new IOException("Not a Type 3 message.");
-               }
-               byte[] lmResponse = readSecurityBuffer(material, 12);
-               int lmResponseOffset = readULong(material, 16);
-               byte[] ntResponse = readSecurityBuffer(material, 20);
-               int ntResponseOffset = readULong(material, 24);
-               byte[] domain = readSecurityBuffer(material, 28);
-               int domainOffset = readULong(material, 32);
-               byte[] user = readSecurityBuffer(material, 36);
-               int userOffset = readULong(material, 40);
-               byte[] workstation = readSecurityBuffer(material, 44);
-               int workstationOffset = readULong(material, 48);
-               int flags;
-               String charset;
-               if (lmResponseOffset == 52 || ntResponseOffset == 52 ||
-                               domainOffset == 52 || userOffset == 52 ||
-                                               workstationOffset == 52) {
-                       flags = NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_OEM;
-                       charset = getOEMEncoding();
-               } else {
-                       setSessionKey(readSecurityBuffer(material, 52));
-                       flags = readULong(material, 60);
-                       charset = ((flags & NTLMSSP_NEGOTIATE_UNICODE) != 0) ?
-                               "UnicodeLittleUnmarked" : getOEMEncoding();
-               }
-               setFlags(flags);
-               setLMResponse(lmResponse);
-               // NTLMv2 issues w/cross-domain authentication; leave NT empty if >= 3
-               if (LM_COMPATIBILITY < 3) setNTResponse(ntResponse);
-               setDomain(new String(domain, charset));
-               setUser(new String(user, charset));
-               setWorkstation(new String(workstation, charset));
-       }
+    private static final int DEFAULT_FLAGS;
+
+    private static final String DEFAULT_DOMAIN;
+
+    private static final String DEFAULT_USER;
+
+    private static final String DEFAULT_PASSWORD;
+
+    private static final String DEFAULT_WORKSTATION;
+
+    private static final int LM_COMPATIBILITY;
+
+    private static final SecureRandom RANDOM = new SecureRandom();
+
+    private byte[] lmResponse;
+
+    private byte[] ntResponse;
+
+    private String domain;
+
+    private String user;
+
+    private String workstation;
+
+    private byte[] sessionKey;
+
+    static {
+        DEFAULT_FLAGS = NTLMSSP_NEGOTIATE_NTLM |
+                (Config.getBoolean("jcifs.smb.client.useUnicode", true) ?
+                        NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM);
+        DEFAULT_DOMAIN = Config.getProperty("jcifs.smb.client.domain", null);
+        DEFAULT_USER = Config.getProperty("jcifs.smb.client.username", null);
+        DEFAULT_PASSWORD = Config.getProperty("jcifs.smb.client.password",
+                null);
+        String defaultWorkstation = null;
+        try {
+            defaultWorkstation = NbtAddress.getLocalHost().getHostName();
+        } catch (UnknownHostException ex) { }
+        DEFAULT_WORKSTATION = defaultWorkstation;
+        LM_COMPATIBILITY = Config.getInt("jcifs.smb.lmCompatibility", 0);
+    }
+
+    /**
+     * Creates a Type-3 message using default values from the current
+     * environment.
+     */
+    public Type3Message() {
+        setFlags(getDefaultFlags());
+        setDomain(getDefaultDomain());
+        setUser(getDefaultUser());
+        setWorkstation(getDefaultWorkstation());
+    }
+
+    /**
+     * Creates a Type-3 message in response to the given Type-2 message
+     * using default values from the current environment.
+     *
+     * @param type2 The Type-2 message which this represents a response to.
+     */
+    public Type3Message(Type2Message type2) {
+        setFlags(getDefaultFlags(type2));
+        setWorkstation(getDefaultWorkstation());
+        String domain = getDefaultDomain();
+        setDomain(domain);
+        String user = getDefaultUser();
+        setUser(user);
+        String password = getDefaultPassword();
+        switch (LM_COMPATIBILITY) {
+        case 0:
+        case 1:
+            setLMResponse(getLMResponse(type2, password));
+            setNTResponse(getNTResponse(type2, password));
+            break;
+        case 2:
+            byte[] nt = getNTResponse(type2, password);
+            setLMResponse(nt);
+            setNTResponse(nt);
+            break;
+        case 3:
+        case 4:
+        case 5:
+            byte[] clientChallenge = new byte[8];
+            RANDOM.nextBytes(clientChallenge);
+            setLMResponse(getLMv2Response(type2, domain, user, password,
+                    clientChallenge));
+            /*
+            setNTResponse(getNTLMv2Response(type2, domain, user, password,
+                    clientChallenge));
+            */
+            break;
+        default:
+            setLMResponse(getLMResponse(type2, password));
+            setNTResponse(getNTResponse(type2, password));
+        }
+    }
+
+    /**
+     * Creates a Type-3 message in response to the given Type-2 message.
+     *
+     * @param type2 The Type-2 message which this represents a response to.
+     * @param password The password to use when constructing the response.
+     * @param domain The domain in which the user has an account.
+     * @param user The username for the authenticating user.
+     * @param workstation The workstation from which authentication is
+     * taking place.
+     */
+    public Type3Message(Type2Message type2, String password, String domain,
+            String user, String workstation) {
+        setFlags(getDefaultFlags(type2));
+        setDomain(domain);
+        setUser(user);
+        setWorkstation(workstation);
+        switch (LM_COMPATIBILITY) {
+        case 0:
+        case 1:
+            setLMResponse(getLMResponse(type2, password));
+            setNTResponse(getNTResponse(type2, password));
+            break;
+        case 2:
+            byte[] nt = getNTResponse(type2, password);
+            setLMResponse(nt);
+            setNTResponse(nt);
+            break;
+        case 3:
+        case 4:
+        case 5:
+            byte[] clientChallenge = new byte[8];
+            RANDOM.nextBytes(clientChallenge);
+            setLMResponse(getLMv2Response(type2, domain, user, password,
+                    clientChallenge));
+            /*
+            setNTResponse(getNTLMv2Response(type2, domain, user, password,
+                    clientChallenge));
+            */
+            break;
+        default:
+            setLMResponse(getLMResponse(type2, password));
+            setNTResponse(getNTResponse(type2, password));
+        }
+    }
+
+    /**
+     * Creates a Type-3 message with the specified parameters.
+     *
+     * @param flags The flags to apply to this message.
+     * @param lmResponse The LanManager/LMv2 response.
+     * @param domain The NT/NTLMv2 response.
+     * @param domain The domain in which the user has an account.
+     * @param user The username for the authenticating user.
+     * @param workstation The workstation from which authentication is
+     * taking place.
+     */
+    public Type3Message(int flags, byte[] lmResponse, byte[] ntResponse,
+            String domain, String user, String workstation) {
+        setFlags(flags);
+        setLMResponse(lmResponse);
+        setNTResponse(ntResponse);
+        setDomain(domain);
+        setUser(user);
+        setWorkstation(workstation);
+    }
+
+    /**
+     * Creates a Type-3 message using the given raw Type-3 material.
+     *
+     * @param material The raw Type-3 material used to construct this message.
+     * @throws IOException If an error occurs while parsing the material.
+     */
+    public Type3Message(byte[] material) throws IOException {
+        parse(material);
+    }
+
+    /**
+     * Returns the LanManager/LMv2 response.
+     *
+     * @return A <code>byte[]</code> containing the LanManager response.
+     */
+    public byte[] getLMResponse() {
+        return lmResponse;
+    }
+
+    /**
+     * Sets the LanManager/LMv2 response for this message.
+     *
+     * @param lmResponse The LanManager response.
+     */
+    public void setLMResponse(byte[] lmResponse) {
+        this.lmResponse = lmResponse;
+    }
+
+    /**
+     * Returns the NT/NTLMv2 response.
+     *
+     * @return A <code>byte[]</code> containing the NT/NTLMv2 response.
+     */
+    public byte[] getNTResponse() {
+        return ntResponse;
+    }
+
+    /**
+     * Sets the NT/NTLMv2 response for this message.
+     *
+     * @param lmResponse The NT/NTLMv2 response.
+     */
+    public void setNTResponse(byte[] ntResponse) {
+        this.ntResponse = ntResponse;
+    }
+
+    /**
+     * Returns the domain in which the user has an account.
+     *
+     * @return A <code>String</code> containing the domain for the user.
+     */
+    public String getDomain() {
+        return domain;
+    }
+
+    /**
+     * Sets the domain for this message.
+     *
+     * @param domain The domain.
+     */
+    public void setDomain(String domain) {
+        this.domain = domain;
+    }
+
+    /**
+     * Returns the username for the authenticating user.
+     *
+     * @return A <code>String</code> containing the user for this message.
+     */
+    public String getUser() {
+        return user;
+    }
+
+    /**
+     * Sets the user for this message.
+     *
+     * @param user The user.
+     */
+    public void setUser(String user) {
+        this.user = user;
+    }
+
+    /**
+     * Returns the workstation from which authentication is being performed.
+     *
+     * @return A <code>String</code> containing the workstation.
+     */
+    public String getWorkstation() {
+        return workstation;
+    }
+
+    /**
+     * Sets the workstation for this message.
+     *
+     * @param workstation The workstation.
+     */
+    public void setWorkstation(String workstation) {
+        this.workstation = workstation;
+    }
+
+    /**
+     * Returns the session key.
+     *
+     * @return A <code>byte[]</code> containing the session key.
+     */
+    public byte[] getSessionKey() {
+        return sessionKey;
+    }
+
+    /**
+     * Sets the session key.
+     *
+     * @param sessionKey The session key.
+     */
+    public void setSessionKey(byte[] sessionKey) {
+        this.sessionKey = sessionKey;
+    }
+
+    public byte[] toByteArray() {
+        try {
+            int flags = getFlags();
+            boolean unicode = (flags & NTLMSSP_NEGOTIATE_UNICODE) != 0;
+            String oem = unicode ? null : getOEMEncoding();
+            String domainName = getDomain();
+            byte[] domain = null;
+            if (domainName != null && domainName.length() != 0) {
+                domain = unicode ?
+                        domainName.getBytes("UnicodeLittleUnmarked") :
+                                domainName.toUpperCase().getBytes(oem);
+            }
+            int domainLength = (domain != null) ? domain.length : 0;
+            String userName = getUser();
+            byte[] user = null;
+            if (userName != null && userName.length() != 0) {
+                user = unicode ? userName.getBytes("UnicodeLittleUnmarked") :
+                        userName.toUpperCase().getBytes(oem);
+            }
+            int userLength = (user != null) ? user.length : 0;
+            String workstationName = getWorkstation();
+            byte[] workstation = null;
+            if (workstationName != null && workstationName.length() != 0) {
+                workstation = unicode ?
+                        workstationName.getBytes("UnicodeLittleUnmarked") :
+                                workstationName.toUpperCase().getBytes(oem);
+            }
+            int workstationLength = (workstation != null) ?
+                    workstation.length : 0;
+            byte[] lmResponse = getLMResponse();
+            int lmLength = (lmResponse != null) ? lmResponse.length : 0;
+            byte[] ntResponse = getNTResponse();
+            int ntLength = (ntResponse != null) ? ntResponse.length : 0;
+            byte[] sessionKey = getSessionKey();
+            int keyLength = (sessionKey != null) ? sessionKey.length : 0;
+            byte[] type3 = new byte[64 + domainLength + userLength +
+                    workstationLength + lmLength + ntLength + keyLength];
+            System.arraycopy(NTLMSSP_SIGNATURE, 0, type3, 0, 8);
+            writeULong(type3, 8, 3);
+            int offset = 64;
+            writeSecurityBuffer(type3, 12, offset, lmResponse);
+            offset += lmLength;
+            writeSecurityBuffer(type3, 20, offset, ntResponse);
+            offset += ntLength;
+            writeSecurityBuffer(type3, 28, offset, domain);
+            offset += domainLength;
+            writeSecurityBuffer(type3, 36, offset, user);
+            offset += userLength;
+            writeSecurityBuffer(type3, 44, offset, workstation);
+            offset += workstationLength;
+            writeSecurityBuffer(type3, 52, offset, sessionKey);
+            writeULong(type3, 60, flags);
+            return type3;
+        } catch (IOException ex) {
+            throw new IllegalStateException(ex.getMessage());
+        }
+    }
+
+    public String toString() {
+        String user = getUser();
+        String domain = getDomain();
+        String workstation = getWorkstation();
+        byte[] lmResponse = getLMResponse();
+        byte[] ntResponse = getNTResponse();
+        byte[] sessionKey = getSessionKey();
+        int flags = getFlags();
+        StringBuffer buffer = new StringBuffer();
+        if (domain != null) {
+            buffer.append("domain: ").append(domain);
+        }
+        if (user != null) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("user: ").append(user);
+        }
+        if (workstation != null) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("workstation: ").append(workstation);
+        }
+        if (lmResponse != null) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("lmResponse: ");
+            buffer.append("0x");
+            for (int i = 0; i < lmResponse.length; i++) {
+                buffer.append(Integer.toHexString((lmResponse[i] >> 4) & 0x0f));
+                buffer.append(Integer.toHexString(lmResponse[i] & 0x0f));
+            }
+        }
+        if (ntResponse != null) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("ntResponse: ");
+            buffer.append("0x");
+            for (int i = 0; i < ntResponse.length; i++) {
+                buffer.append(Integer.toHexString((ntResponse[i] >> 4) & 0x0f));
+                buffer.append(Integer.toHexString(ntResponse[i] & 0x0f));
+            }
+        }
+        if (sessionKey != null) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("sessionKey: ");
+            buffer.append("0x");
+            for (int i = 0; i < sessionKey.length; i++) {
+                buffer.append(Integer.toHexString((sessionKey[i] >> 4) & 0x0f));
+                buffer.append(Integer.toHexString(sessionKey[i] & 0x0f));
+            }
+        }
+        if (flags != 0) {
+            if (buffer.length() > 0) buffer.append("; ");
+            buffer.append("flags: ");
+            buffer.append("0x");
+            buffer.append(Integer.toHexString((flags >> 28) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 24) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 20) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 16) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 12) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 8) & 0x0f));
+            buffer.append(Integer.toHexString((flags >> 4) & 0x0f));
+            buffer.append(Integer.toHexString(flags & 0x0f));
+        }
+        return buffer.toString();
+    }
+
+    /**
+     * Returns the default flags for a generic Type-3 message in the
+     * current environment.
+     *
+     * @return An <code>int</code> containing the default flags.
+     */
+    public static int getDefaultFlags() {
+        return DEFAULT_FLAGS;
+    }
+
+    /**
+     * Returns the default flags for a Type-3 message created in response
+     * to the given Type-2 message in the current environment.
+     *
+     * @return An <code>int</code> containing the default flags.
+     */
+    public static int getDefaultFlags(Type2Message type2) {
+        if (type2 == null) return DEFAULT_FLAGS;
+        int flags = NTLMSSP_NEGOTIATE_NTLM;
+        flags |= ((type2.getFlags() & NTLMSSP_NEGOTIATE_UNICODE) != 0) ?
+                NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM;
+        return flags;
+    }
+
+    /**
+     * Constructs the LanManager response to the given Type-2 message using
+     * the supplied password.
+     *
+     * @param type2 The Type-2 message.
+     * @param password The password.
+     * @return A <code>byte[]</code> containing the LanManager response.
+     */
+    public static byte[] getLMResponse(Type2Message type2, String password) {
+        if (type2 == null || password == null) return null;
+        return NtlmPasswordAuthentication.getPreNTLMResponse(password,
+                type2.getChallenge());
+    }
+
+    public static byte[] getLMv2Response(Type2Message type2,
+            String domain, String user, String password,
+                    byte[] clientChallenge) {
+        if (type2 == null || domain == null || user == null ||
+                password == null || clientChallenge == null) {
+            return null;
+        }
+        return NtlmPasswordAuthentication.getLMv2Response(domain, user,
+                password, type2.getChallenge(), clientChallenge);
+    }
+
+    /**
+     * Constructs the NT response to the given Type-2 message using
+     * the supplied password.
+     *
+     * @param type2 The Type-2 message.
+     * @param password The password.
+     * @return A <code>byte[]</code> containing the NT response.
+     */
+    public static byte[] getNTResponse(Type2Message type2, String password) {
+        if (type2 == null || password == null) return null;
+        return NtlmPasswordAuthentication.getNTLMResponse(password,
+                type2.getChallenge());
+    }
+
+    /**
+     * Returns the default domain from the current environment.
+     *
+     * @return The default domain.
+     */
+    public static String getDefaultDomain() {
+        return DEFAULT_DOMAIN;
+    }
+
+    /**
+     * Returns the default user from the current environment.
+     *
+     * @return The default user.
+     */
+    public static String getDefaultUser() {
+        return DEFAULT_USER;
+    }
+
+    /**
+     * Returns the default password from the current environment.
+     *
+     * @return The default password.
+     */
+    public static String getDefaultPassword() {
+        return DEFAULT_PASSWORD;
+    }
+
+    /**
+     * Returns the default workstation from the current environment.
+     *
+     * @return The default workstation.
+     */
+    public static String getDefaultWorkstation() {
+        return DEFAULT_WORKSTATION;
+    }
+
+    private void parse(byte[] material) throws IOException {
+        for (int i = 0; i < 8; i++) {
+            if (material[i] != NTLMSSP_SIGNATURE[i]) {
+                throw new IOException("Not an NTLMSSP message.");
+            }
+        }
+        if (readULong(material, 8) != 3) {
+            throw new IOException("Not a Type 3 message.");
+        }
+        byte[] lmResponse = readSecurityBuffer(material, 12);
+        int lmResponseOffset = readULong(material, 16);
+        byte[] ntResponse = readSecurityBuffer(material, 20);
+        int ntResponseOffset = readULong(material, 24);
+        byte[] domain = readSecurityBuffer(material, 28);
+        int domainOffset = readULong(material, 32);
+        byte[] user = readSecurityBuffer(material, 36);
+        int userOffset = readULong(material, 40);
+        byte[] workstation = readSecurityBuffer(material, 44);
+        int workstationOffset = readULong(material, 48);
+        int flags;
+        String charset;
+        if (lmResponseOffset == 52 || ntResponseOffset == 52 ||
+                domainOffset == 52 || userOffset == 52 ||
+                        workstationOffset == 52) {
+            flags = NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_OEM;
+            charset = getOEMEncoding();
+        } else {
+            setSessionKey(readSecurityBuffer(material, 52));
+            flags = readULong(material, 60);
+            charset = ((flags & NTLMSSP_NEGOTIATE_UNICODE) != 0) ?
+                "UnicodeLittleUnmarked" : getOEMEncoding();
+        }
+        setFlags(flags);
+        setLMResponse(lmResponse);
+        // NTLMv2 issues w/cross-domain authentication; leave NT empty if >= 3
+        if (LM_COMPATIBILITY < 3) setNTResponse(ntResponse);
+        setDomain(new String(domain, charset));
+        setUser(new String(user, charset));
+        setWorkstation(new String(workstation, charset));
+    }
 
 }
index 42325d3..299bb60 100644 (file)
@@ -19,6 +19,6 @@
 package jcifs.smb;
 
 interface AllocInfo {
-       long getCapacity();
-       long getFree();
+    long getCapacity();
+    long getFree();
 }
index 6d77323..925c8ba 100644 (file)
@@ -20,365 +20,364 @@ package jcifs.smb;
 
 import java.io.InputStream;
 import java.io.IOException;
+import jcifs.util.Hexdump;
 
 abstract class AndXServerMessageBlock extends ServerMessageBlock {
 
-       static final int ANDX_COMMAND_OFFSET  = 1;
-       static final int ANDX_RESERVED_OFFSET = 2;
-       static final int ANDX_OFFSET_OFFSET   = 3;
-
-       ServerMessageBlock andx = null;
-       byte andxCommand        = (byte)0xFF;
-       int andxOffset          = 0;
-
-       AndXServerMessageBlock() {
-       }
-       AndXServerMessageBlock( ServerMessageBlock andx ) {
-               this.andx = andx;
-               if( andx != null ) {
-                       andxCommand = andx.command;
-               }
-       }
-
-       /* The SmbComReadAndXResponse can read from the InputStream
-        * directly by implementing this method. The default
-        * behavior is to arraycopy all bytes into the buffer and call
-        * readBytesWireFormat. The alternative would have been to overload
-        * the readAndXWireFormat method but that would have resulted in
-        * copying a fairly large chunck of code into the subclass.
-        */
-
-       abstract int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException;
-
-       int getBatchLimit( byte command ) {
-               /* the default limit is 0 batched messages before this
-                * one, meaning this message cannot be batched.
-                */
-               return 0;
-       }
-
-       /* 
-        * We overload this method from ServerMessageBlock because
-        * we want writeAndXWireFormat to write the parameterWords
-        * and bytes. This is so we can write batched smbs because
-        * all but the first smb of the chaain do not have a header
-        * and therefore we do not want to writeHeaderWireFormat. We
-        * just recursivly call writeAndXWireFormat.
-        */ 
-
-       int writeWireFormat( byte[] dst, int dstIndex ) {
-               int start = headerStart = dstIndex;
-               dstIndex += writeHeaderWireFormat( dst, dstIndex );
-               dstIndex += writeAndXWireFormat( dst, dstIndex );
-               length = dstIndex - start;
-//Log.printHexDump( System.err, Thread.currentThread().getName() + ": writeWireFormat", dst, 0, Math.min( dstIndex, 63 ));
-               return length;
-       }
-
-       /*
-        * We overload this because we want readAndXWireFormat to
-        * read the parameter words and bytes. This is so when
-        * commands are batched together we can recursivly call
-        * readAndXWireFormat without reading the non-existent header.
-        */
-
-       int readWireFormat( InputStream in,
-                                                                       byte[] buffer,
-                                                                       int bufferIndex )
-                                                                       throws IOException {
-               int start = bufferIndex;
-
-               if( in.read( buffer, bufferIndex, HEADER_LENGTH ) != HEADER_LENGTH ) {
-                       throw new IOException( "unexpected EOF reading smb header" );
-               }
-               bufferIndex += readHeaderWireFormat( buffer, bufferIndex );
-               bufferIndex += readAndXWireFormat( in, buffer, bufferIndex );
-
-               length = bufferIndex - start;
-               return length;
-       }
-       int writeAndXWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-
-               wordCount = writeParameterWordsWireFormat( dst,
-                                                                                               start + ANDX_OFFSET_OFFSET + 2 );
-               wordCount += 4; // for command, reserved, and offset
-               dstIndex += wordCount + 1;
-               wordCount /= 2;
-               dst[start] = (byte)( wordCount & 0xFF );
-
-               byteCount = writeBytesWireFormat( dst, dstIndex + 2 );
-               dst[dstIndex++] = (byte)( byteCount & 0xFF );
-               dst[dstIndex++] = (byte)(( byteCount >> 8 ) & 0xFF );
-               dstIndex += byteCount;
-
-               /* Normally, without intervention everything would batch
-                * with everything else. If the below clause evaluates true
-                * the andx command will not be written and therefore the
-                * response will not read a batched command and therefore
-                * the 'received' member of the response object will not
-                * be set to true indicating the send and sendTransaction
-                * methods that the next part should be sent. This is a
-                * very indirect and simple batching control mechanism.
-                */
-
-
-               if( andx == null || useBatching == false ||
-                                                               batchLevel >= getBatchLimit( andx.command )) {
-                       andxCommand = (byte)0xFF;
-                       andx = null;
-
-                       dst[start + ANDX_COMMAND_OFFSET] = (byte)0xFF;
-                       dst[start + ANDX_RESERVED_OFFSET] = (byte)0x00;
-                       dst[start + ANDX_OFFSET_OFFSET] = (byte)0x00;
-                       dst[start + ANDX_OFFSET_OFFSET + 1] = (byte)0x00;
-
-                       // andx not used; return
-//Log.printHexDump( System.err, Thread.currentThread().getName() + ": writeAndXWireFormat1", dst, 0, Math.min( dstIndex, 63 ));
-                       return dstIndex - start;
-               }
-
-               /* The message provided to batch has a batchLimit that is
-                * higher than the current batchLevel so we will now encode
-                * that chained message. Before doing so we must increment
-                * the batchLevel of the andx message in case it itself is an
-                * andx message and needs to perform the same check as above.
-                */
-
-               andx.batchLevel = batchLevel + 1;
-
-
-               dst[start + ANDX_COMMAND_OFFSET] = andxCommand;
-               dst[start + ANDX_RESERVED_OFFSET] = (byte)0x00;
-               andxOffset = dstIndex - headerStart;
-               writeInt2( andxOffset, dst, start + ANDX_OFFSET_OFFSET );
-
-               andx.useUnicode = useUnicode;
-               if( andx instanceof AndXServerMessageBlock ) {
-
-                       /*
-                        * A word about communicating header info to andx smbs
-                        *
-                        * This is where we recursively invoke the provided andx smb
-                        * object to write it's parameter words and bytes to our outgoing
-                        * array. Incedentally when these andx smbs are created they are not
-                        * necessarily populated with header data because they're not writing
-                        * the header, only their body. But for whatever reason one might wish
-                        * to populate fields if the writeXxx operation needs this header data
-                        * for whatever reason. I copy over the uid here so it appears correct
-                        * in logging output. Logging of andx segments of messages inadvertantly
-                        * print header information because of the way toString always makes a
-                        * super.toString() call(see toString() at the end of all smbs classes).
-                        */
-
-                       andx.uid = uid;
-                       dstIndex += ((AndXServerMessageBlock)andx).writeAndXWireFormat( dst, dstIndex );
-               } else {
-                       // the andx smb is not of type andx so lets just write it here and
-                       // were done.
-                       int andxStart = dstIndex;
-                       andx.wordCount = andx.writeParameterWordsWireFormat( dst, dstIndex );
-                       dstIndex += andx.wordCount + 1;
-                       andx.wordCount /= 2;
-                       dst[andxStart] = (byte)( andx.wordCount & 0xFF );
-       
-                       andx.byteCount = andx.writeBytesWireFormat( dst, dstIndex + 2 );
-                       dst[dstIndex++] = (byte)( andx.byteCount & 0xFF );
-                       dst[dstIndex++] = (byte)(( andx.byteCount >> 8 ) & 0xFF );
-                       dstIndex += andx.byteCount;
-               }
-
-//Log.printHexDump( System.err, Thread.currentThread().getName() + ": writeAndXWireFormat1", dst, 0, Math.min( dstIndex, 63 ));
-               return dstIndex - start;
-       }
-       int readAndXWireFormat( InputStream in,
-                                                                       byte[] buffer,
-                                                                       int bufferIndex )
-                                                                       throws IOException {
-               int start = bufferIndex;
-
-               /*
-                * read wordCount
-                */
-
-               if(( wordCount = in.read() ) == -1 ) {
-                       throw new IOException( "unexpected EOF reading smb wordCount" );
-               }
-               buffer[bufferIndex++] = (byte)( wordCount & 0xFF );
-
-               /*
-                * read parameterWords
-                */
-
-               if( wordCount != 0 ) {
-                       if( in.read( buffer, bufferIndex, wordCount * 2 ) != ( wordCount * 2 )) {
-                               throw new IOException( "unexpected EOF reading andx parameter words" );
-                       }
-
-                       /*
-                        * these fields are common to all andx commands
-                        * so let's populate them here
-                        */
-       
-                       andxCommand = buffer[bufferIndex];
-                       bufferIndex += 2;
-                       andxOffset = readInt2( buffer, bufferIndex );
-                       bufferIndex += 2;
-       
-                       /*
-                        * no point in calling readParameterWordsWireFormat if there are no more
-                        * parameter words. besides, win98 doesn't return "OptionalSupport" field
-                        */
-       
-                       if( wordCount > 2 ) {
-                               bufferIndex += readParameterWordsWireFormat( buffer, bufferIndex );
-                       }
-               }
-
-               /*
-                * read byteCount
-                */
-
-               if( in.read( buffer, bufferIndex, 2 ) != 2 ) {
-                       throw new IOException( "unexpected EOF reading smb byteCount" );
-               }
-               byteCount = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-       
-               /*
-                * read bytes
-                */
-       
-               if( byteCount != 0 ) {
-                       int n;
-                       n = readBytesDirectWireFormat( in, byteCount );
-                       if( n == 0 ) {
-                               if( in.read( buffer, bufferIndex, byteCount ) != byteCount ) {
-                                       throw new IOException( "unexpected EOF reading andx bytes" );
-                               }
-                               n = readBytesWireFormat( buffer, bufferIndex );
-                       }
-                       bufferIndex += byteCount;
-               }
-
-               /*
-                * if there is an andx and it itself is an andx then just recur by
-                * calling this method for it. otherwise just read it's parameter words
-                * and bytes as usual. Note how we can't just call andx.readWireFormat
-                * because there's no header.
-                */
-
-
-               if( errorCode > 0 || andxCommand == (byte)0xFF ) {
-                       andxCommand = (byte)0xFF;
-                       andx = null;
-               } else if( andx == null ) {
-                       andxCommand = (byte)0xFF;
-                       throw new IOException( "no andx command supplied with response" );
-               } else {
-
-                       /*
-                        * This is where we take into account andxOffset
-                        *
-                        * Before we call readAndXWireFormat on the next andx
-                        * part we must take into account the andxOffset. The
-                        * input stream must be positioned at this location. The
-                        * new location is the just read andxOffset(say 68)
-                        * minus the current bufferIndex(say 65). But this packet
-                        * construction/deconstruction technique does not require that
-                        * the bufferIndex begin at 0. The header might be at another
-                        * location(say 4). So we must subtract the current buffer
-                        * index from the real start of the header and substract that
-                        * from the andxOffset(like 68 - ( 65 - 0 ) if headerStart
-                        * were 0 or 68 - ( 69 - 4 ) if the headerStart were 4. We
-                        * also need to communicate to our newly instantiated andx
-                        * smb the headerStart value so that it may perform the same
-                        * calculation as this is a recursive process.
-                        */
-
-                       bufferIndex += in.read( buffer, bufferIndex,
-                                                                       andxOffset - ( bufferIndex - headerStart ));
-
-                       andx.headerStart = headerStart;
-                       andx.command = andxCommand;
-                       andx.errorCode = errorCode;
-                       andx.flags = flags;
-                       andx.flags2 = flags2;
-                       andx.tid = tid;
-                       andx.pid = pid;
-                       andx.uid = uid;
-                       andx.mid = mid;
-                       andx.useUnicode = useUnicode;
-
-                       if( andx instanceof AndXServerMessageBlock ) {
-                               bufferIndex += ((AndXServerMessageBlock)andx).readAndXWireFormat(
-                                                                                               in, buffer, andxOffset - headerStart );
-                       } else {
-
-                               /*
-                                * Just a plain smb. Read it as normal.
-                                */
-
-                               /*
-                                * read wordCount
-                                */
-
-                               if(( andx.wordCount = in.read() ) == -1 ) {
-                                       throw new IOException( "unexpected EOF reading smb wordCount" );
-                               }
-                               buffer[bufferIndex++] = (byte)( andx.wordCount & 0xFF );
-
-                               /*
-                                * read parameterWords
-                                */
-
-                               if( andx.wordCount != 0 ) {
-                                       if( in.read( buffer, bufferIndex, andx.wordCount * 2 ) !=
-                                                                                                                               ( andx.wordCount * 2 )) {
-                                               throw new IOException( "unexpected EOF reading andx parameter words" );
-                                       }
-
-                                       /*
-                                        * no point in calling readParameterWordsWireFormat if there are no more
-                                        * parameter words. besides, win98 doesn't return "OptionalSupport" field
-                                        */
-
-                                       if( andx.wordCount > 2 ) {
-                                               bufferIndex +=
-                                                               andx.readParameterWordsWireFormat( buffer, bufferIndex );
-                                       }
-                               }
-
-                               /*
-                                * read byteCount
-                                */
-
-                               if( in.read( buffer, bufferIndex, 2 ) != 2 ) {
-                                       throw new IOException( "unexpected EOF reading smb byteCount" );
-                               }
-                               andx.byteCount = readInt2( buffer, bufferIndex );
-                               bufferIndex += 2;
-
-                               /*
-                                * read bytes
-                                */
-
-                               if( andx.byteCount != 0 ) {
-                                       if( in.read( buffer, bufferIndex, andx.byteCount ) != andx.byteCount ) {
-                                               throw new IOException( "unexpected EOF reading andx bytes" );
-                                       }
-                                       andx.readBytesWireFormat( buffer, bufferIndex );
-                                       bufferIndex += andx.byteCount;
-                               }
-                       }
-                       andx.received = true;
-               }
-
-               return bufferIndex - start;
-       }
-       public String toString() {
-               return new String( super.toString() +
-                       ",andxCommand=0x" + Log.getHexString( andxCommand, 2 ) +
-                       ",andxOffset=" + andxOffset );
-       }
+    private static final int ANDX_COMMAND_OFFSET  = 1;
+    private static final int ANDX_RESERVED_OFFSET = 2;
+    private static final int ANDX_OFFSET_OFFSET   = 3;
+
+    private byte andxCommand        = (byte)0xFF;
+    private int andxOffset          = 0;
+
+    ServerMessageBlock andx = null;
+
+    AndXServerMessageBlock() {
+    }
+    AndXServerMessageBlock( ServerMessageBlock andx ) {
+        this.andx = andx;
+        if( andx != null ) {
+            andxCommand = andx.command;
+        }
+    }
+
+    /* The SmbComReadAndXResponse can read from the InputStream
+     * directly by implementing this method. The default
+     * behavior is to arraycopy all bytes into the buffer and call
+     * readBytesWireFormat. The alternative would have been to overload
+     * the readAndXWireFormat method but that would have resulted in
+     * copying a fairly large chunck of code into the subclass.
+     */
+
+    abstract int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException;
+
+    int getBatchLimit( byte command ) {
+        /* the default limit is 0 batched messages before this
+         * one, meaning this message cannot be batched.
+         */
+        return 0;
+    }
+
+    /* 
+     * We overload this method from ServerMessageBlock because
+     * we want writeAndXWireFormat to write the parameterWords
+     * and bytes. This is so we can write batched smbs because
+     * all but the first smb of the chaain do not have a header
+     * and therefore we do not want to writeHeaderWireFormat. We
+     * just recursivly call writeAndXWireFormat.
+     */ 
+
+    int writeWireFormat( byte[] dst, int dstIndex ) {
+        int start = headerStart = dstIndex;
+        dstIndex += writeHeaderWireFormat( dst, dstIndex );
+        dstIndex += writeAndXWireFormat( dst, dstIndex );
+        length = dstIndex - start;
+        return length;
+    }
+
+    /*
+     * We overload this because we want readAndXWireFormat to
+     * read the parameter words and bytes. This is so when
+     * commands are batched together we can recursivly call
+     * readAndXWireFormat without reading the non-existent header.
+     */
+
+    int readWireFormat( InputStream in,
+                                    byte[] buffer,
+                                    int bufferIndex )
+                                    throws IOException {
+        int start = bufferIndex;
+
+        if( in.read( buffer, bufferIndex, HEADER_LENGTH ) != HEADER_LENGTH ) {
+            throw new IOException( "unexpected EOF reading smb header" );
+        }
+        bufferIndex += readHeaderWireFormat( buffer, bufferIndex );
+        bufferIndex += readAndXWireFormat( in, buffer, bufferIndex );
+
+        length = bufferIndex - start;
+        return length;
+    }
+    int writeAndXWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+
+        wordCount = writeParameterWordsWireFormat( dst,
+                                                start + ANDX_OFFSET_OFFSET + 2 );
+        wordCount += 4; // for command, reserved, and offset
+        dstIndex += wordCount + 1;
+        wordCount /= 2;
+        dst[start] = (byte)( wordCount & 0xFF );
+
+        byteCount = writeBytesWireFormat( dst, dstIndex + 2 );
+        dst[dstIndex++] = (byte)( byteCount & 0xFF );
+        dst[dstIndex++] = (byte)(( byteCount >> 8 ) & 0xFF );
+        dstIndex += byteCount;
+
+        /* Normally, without intervention everything would batch
+         * with everything else. If the below clause evaluates true
+         * the andx command will not be written and therefore the
+         * response will not read a batched command and therefore
+         * the 'received' member of the response object will not
+         * be set to true indicating the send and sendTransaction
+         * methods that the next part should be sent. This is a
+         * very indirect and simple batching control mechanism.
+         */
+
+
+        if( andx == null || USE_BATCHING == false ||
+                                batchLevel >= getBatchLimit( andx.command )) {
+            andxCommand = (byte)0xFF;
+            andx = null;
+
+            dst[start + ANDX_COMMAND_OFFSET] = (byte)0xFF;
+            dst[start + ANDX_RESERVED_OFFSET] = (byte)0x00;
+            dst[start + ANDX_OFFSET_OFFSET] = (byte)0x00;
+            dst[start + ANDX_OFFSET_OFFSET + 1] = (byte)0x00;
+
+            // andx not used; return
+            return dstIndex - start;
+        }
+
+        /* The message provided to batch has a batchLimit that is
+         * higher than the current batchLevel so we will now encode
+         * that chained message. Before doing so we must increment
+         * the batchLevel of the andx message in case it itself is an
+         * andx message and needs to perform the same check as above.
+         */
+
+        andx.batchLevel = batchLevel + 1;
+
+
+        dst[start + ANDX_COMMAND_OFFSET] = andxCommand;
+        dst[start + ANDX_RESERVED_OFFSET] = (byte)0x00;
+        andxOffset = dstIndex - headerStart;
+        writeInt2( andxOffset, dst, start + ANDX_OFFSET_OFFSET );
+
+        andx.useUnicode = useUnicode;
+        if( andx instanceof AndXServerMessageBlock ) {
+
+            /*
+             * A word about communicating header info to andx smbs
+             *
+             * This is where we recursively invoke the provided andx smb
+             * object to write it's parameter words and bytes to our outgoing
+             * array. Incedentally when these andx smbs are created they are not
+             * necessarily populated with header data because they're not writing
+             * the header, only their body. But for whatever reason one might wish
+             * to populate fields if the writeXxx operation needs this header data
+             * for whatever reason. I copy over the uid here so it appears correct
+             * in logging output. Logging of andx segments of messages inadvertantly
+             * print header information because of the way toString always makes a
+             * super.toString() call(see toString() at the end of all smbs classes).
+             */
+
+            andx.uid = uid;
+            dstIndex += ((AndXServerMessageBlock)andx).writeAndXWireFormat( dst, dstIndex );
+        } else {
+            // the andx smb is not of type andx so lets just write it here and
+            // were done.
+            int andxStart = dstIndex;
+            andx.wordCount = andx.writeParameterWordsWireFormat( dst, dstIndex );
+            dstIndex += andx.wordCount + 1;
+            andx.wordCount /= 2;
+            dst[andxStart] = (byte)( andx.wordCount & 0xFF );
+    
+            andx.byteCount = andx.writeBytesWireFormat( dst, dstIndex + 2 );
+            dst[dstIndex++] = (byte)( andx.byteCount & 0xFF );
+            dst[dstIndex++] = (byte)(( andx.byteCount >> 8 ) & 0xFF );
+            dstIndex += andx.byteCount;
+        }
+
+        return dstIndex - start;
+    }
+    int readAndXWireFormat( InputStream in,
+                                    byte[] buffer,
+                                    int bufferIndex )
+                                    throws IOException {
+        int start = bufferIndex;
+
+        /*
+         * read wordCount
+         */
+
+        if(( wordCount = in.read() ) == -1 ) {
+            throw new IOException( "unexpected EOF reading smb wordCount" );
+        }
+        buffer[bufferIndex++] = (byte)( wordCount & 0xFF );
+
+        /*
+         * read parameterWords
+         */
+
+        if( wordCount != 0 ) {
+            if( in.read( buffer, bufferIndex, wordCount * 2 ) != ( wordCount * 2 )) {
+                throw new IOException( "unexpected EOF reading andx parameter words" );
+            }
+
+            /*
+             * these fields are common to all andx commands
+             * so let's populate them here
+             */
+    
+            andxCommand = buffer[bufferIndex];
+            bufferIndex += 2;
+            andxOffset = readInt2( buffer, bufferIndex );
+            bufferIndex += 2;
+    
+            /*
+             * no point in calling readParameterWordsWireFormat if there are no more
+             * parameter words. besides, win98 doesn't return "OptionalSupport" field
+             */
+    
+            if( wordCount > 2 ) {
+                bufferIndex += readParameterWordsWireFormat( buffer, bufferIndex );
+            }
+        }
+
+        /*
+         * read byteCount
+         */
+
+        if( in.read( buffer, bufferIndex, 2 ) != 2 ) {
+            throw new IOException( "unexpected EOF reading smb byteCount" );
+        }
+        byteCount = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+    
+        /*
+         * read bytes
+         */
+    
+        if( byteCount != 0 ) {
+            int n;
+            n = readBytesDirectWireFormat( in, byteCount, buffer, bufferIndex );
+            if( n == 0 ) {
+                if( in.read( buffer, bufferIndex, byteCount ) != byteCount ) {
+                    throw new IOException( "unexpected EOF reading andx bytes" );
+                }
+                n = readBytesWireFormat( buffer, bufferIndex );
+            }
+            bufferIndex += byteCount;
+        }
+
+        /*
+         * if there is an andx and it itself is an andx then just recur by
+         * calling this method for it. otherwise just read it's parameter words
+         * and bytes as usual. Note how we can't just call andx.readWireFormat
+         * because there's no header.
+         */
+
+        if( errorCode != 0 || andxCommand == (byte)0xFF ) {
+            andxCommand = (byte)0xFF;
+            andx = null;
+        } else if( andx == null ) {
+            andxCommand = (byte)0xFF;
+            throw new IOException( "no andx command supplied with response" );
+        } else {
+
+            /*
+             * This is where we take into account andxOffset
+             *
+             * Before we call readAndXWireFormat on the next andx
+             * part we must take into account the andxOffset. The
+             * input stream must be positioned at this location. The
+             * new location is the just read andxOffset(say 68)
+             * minus the current bufferIndex(say 65). But this packet
+             * construction/deconstruction technique does not require that
+             * the bufferIndex begin at 0. The header might be at another
+             * location(say 4). So we must subtract the current buffer
+             * index from the real start of the header and substract that
+             * from the andxOffset(like 68 - ( 65 - 0 ) if headerStart
+             * were 0 or 68 - ( 69 - 4 ) if the headerStart were 4. We
+             * also need to communicate to our newly instantiated andx
+             * smb the headerStart value so that it may perform the same
+             * calculation as this is a recursive process.
+             */
+
+            bufferIndex += in.read( buffer, bufferIndex,
+                                    andxOffset - ( bufferIndex - headerStart ));
+
+            andx.headerStart = headerStart;
+            andx.command = andxCommand;
+            andx.errorCode = errorCode;
+            andx.flags = flags;
+            andx.flags2 = flags2;
+            andx.tid = tid;
+            andx.pid = pid;
+            andx.uid = uid;
+            andx.mid = mid;
+            andx.useUnicode = useUnicode;
+
+            if( andx instanceof AndXServerMessageBlock ) {
+                bufferIndex += ((AndXServerMessageBlock)andx).readAndXWireFormat(
+                                                in, buffer, andxOffset - headerStart );
+            } else {
+
+                /*
+                 * Just a plain smb. Read it as normal.
+                 */
+
+                /*
+                 * read wordCount
+                 */
+
+                if(( andx.wordCount = in.read() ) == -1 ) {
+                    throw new IOException( "unexpected EOF reading smb wordCount" );
+                }
+                buffer[bufferIndex++] = (byte)( andx.wordCount & 0xFF );
+
+                /*
+                 * read parameterWords
+                 */
+
+                if( andx.wordCount != 0 ) {
+                    if( in.read( buffer, bufferIndex, andx.wordCount * 2 ) !=
+                                                                ( andx.wordCount * 2 )) {
+                        throw new IOException( "unexpected EOF reading andx parameter words" );
+                    }
+
+                    /*
+                     * no point in calling readParameterWordsWireFormat if there are no more
+                     * parameter words. besides, win98 doesn't return "OptionalSupport" field
+                     */
+
+                    if( andx.wordCount > 2 ) {
+                        bufferIndex +=
+                                andx.readParameterWordsWireFormat( buffer, bufferIndex );
+                    }
+                }
+
+                /*
+                 * read byteCount
+                 */
+
+                if( in.read( buffer, bufferIndex, 2 ) != 2 ) {
+                    throw new IOException( "unexpected EOF reading smb byteCount" );
+                }
+                andx.byteCount = readInt2( buffer, bufferIndex );
+                bufferIndex += 2;
+
+                /*
+                 * read bytes
+                 */
+
+                if( andx.byteCount != 0 ) {
+                    if( in.read( buffer, bufferIndex, andx.byteCount ) != andx.byteCount ) {
+                        throw new IOException( "unexpected EOF reading andx bytes" );
+                    }
+                    andx.readBytesWireFormat( buffer, bufferIndex );
+                    bufferIndex += andx.byteCount;
+                }
+            }
+            andx.received = true;
+        }
+
+        return bufferIndex - start;
+    }
+    public String toString() {
+        return new String( super.toString() +
+            ",andxCommand=0x" + Hexdump.toHexString( andxCommand, 2 ) +
+            ",andxOffset=" + andxOffset );
+    }
 }
index 41d1ec8..120886e 100644 (file)
@@ -22,51 +22,51 @@ import jcifs.Config;
 
 class BufferCache {
 
-       static final int MAX_BUFFERS = Config.getInt( "jcifs.smb.maxBuffers", 16 );
+    private static final int MAX_BUFFERS = Config.getInt( "jcifs.smb.maxBuffers", 16 );
 
-       static Object[] cache = new Object[MAX_BUFFERS];
-       static int numBuffers = 0;
-       static int freeBuffers = 0;
+    private static Object[] cache = new Object[MAX_BUFFERS];
+    private static int numBuffers = 0;
+    private static int freeBuffers = 0;
 
-       static byte[] getBuffer() {
-               byte[] buf;
+    static byte[] getBuffer() {
+        byte[] buf;
 
-               synchronized( cache ) {
-                       while( freeBuffers == 0 && numBuffers == MAX_BUFFERS ) {
-                               try {
-                                       cache.wait();
-                               } catch( InterruptedException ie ) {
-                                       return null;
-                               }
-                       }
+        synchronized( cache ) {
+            while( freeBuffers == 0 && numBuffers == MAX_BUFFERS ) {
+                try {
+                    cache.wait();
+                } catch( InterruptedException ie ) {
+                    return null;
+                }
+            }
 
-                       if( freeBuffers > 0 ) {
-                               for( int i = 0; i < MAX_BUFFERS; i++ ) {
-                                       if( cache[i] != null ) {
-                                               buf = (byte[])cache[i];
-                                               cache[i] = null;
-                                               freeBuffers--;
-                                               return buf;
-                                       }
-                               }
-                       }
+            if( freeBuffers > 0 ) {
+                for( int i = 0; i < MAX_BUFFERS; i++ ) {
+                    if( cache[i] != null ) {
+                        buf = (byte[])cache[i];
+                        cache[i] = null;
+                        freeBuffers--;
+                        return buf;
+                    }
+                }
+            }
 
-                       buf = new byte[SmbComTransaction.TRANSACTION_BUF_SIZE];
-                       numBuffers++;
-               }
+            buf = new byte[SmbComTransaction.TRANSACTION_BUF_SIZE];
+            numBuffers++;
+        }
 
-               return buf;
-       }
-       static void releaseBuffer( byte[] buf ) {
-               synchronized( cache ) {
-                       for( int i = 0; i < MAX_BUFFERS; i++ ) {
-                               if( cache[i] == null ) {
-                                       cache[i] = buf;
-                                       freeBuffers++;
-                                       cache.notify();
-                                       return;
-                               }
-                       }
-               }
-       }
+        return buf;
+    }
+    static void releaseBuffer( byte[] buf ) {
+        synchronized( cache ) {
+            for( int i = 0; i < MAX_BUFFERS; i++ ) {
+                if( cache[i] == null ) {
+                    cache[i] = buf;
+                    freeBuffers++;
+                    cache.notify();
+                    return;
+                }
+            }
+        }
+    }
 }
index 132a682..584db85 100644 (file)
@@ -20,19 +20,19 @@ package jcifs.smb;
 
 public class DfsReferral extends SmbException {
 
-       public String path;     // Path relative to tree from which this referral was thrown
-       public String node;     // Server and share
-       public String server;   // Server
-       public String share;    // Share
-       public String nodepath; // Path relative to tree
-       public boolean resolveHashes;
+    public String path;     // Path relative to tree from which this referral was thrown
+    public String node;     // Server and share
+    public String server;   // Server
+    public String share;    // Share
+    public String nodepath; // Path relative to tree
+    public boolean resolveHashes;
 
-       public String toString() {
-               return "DfsReferral[path=" + path +
-                       ",node=" + node +
-                       ",server=" + server +
-                       ",share=" + share +
-                       ",nodepath=" + nodepath +
-                       ",resolveHashes=" + resolveHashes + "]";
-       }
+    public String toString() {
+        return "DfsReferral[path=" + path +
+            ",node=" + node +
+            ",server=" + server +
+            ",share=" + share +
+            ",nodepath=" + nodepath +
+            ",resolveHashes=" + resolveHashes + "]";
+    }
 }
diff --git a/src/jcifs/smb/DosError.java b/src/jcifs/smb/DosError.java
new file mode 100644 (file)
index 0000000..f3c78fe
--- /dev/null
@@ -0,0 +1,110 @@
+/* jcifs smb client library in Java
+ * Copyright (C) 2004  "Michael B. Allen" <jcifs at samba dot org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package jcifs.smb;
+
+public interface DosError {
+
+    static final int[][] DOS_ERROR_CODES = {
+        { 0x00000000, 0x00000000 },
+        { 0x00010001, 0xc0000002 },
+        { 0x00010002, 0xc0000002 },
+        { 0x00020001, 0xc000000f },
+        { 0x00020002, 0xc000006a },
+        { 0x00030001, 0xc000003a },
+        { 0x00030002, 0xc00000cb },
+        { 0x00040002, 0xc00000ca },
+        { 0x00050001, 0xc0000022 },
+        { 0x00050002, 0xc00000c9 },
+        { 0x00060001, 0xc0000008 },
+        { 0x00060002, 0xc00000cc },
+        { 0x00080001, 0xc000009a },
+        { 0x00130003, 0xc00000a2 },
+        { 0x00150003, 0xc0000013 },
+        { 0x001f0001, 0xc0000001 },
+        { 0x001f0003, 0xc0000001 },
+        { 0x00200001, 0xc0000043 },
+        { 0x00200003, 0xc0000043 },
+        { 0x00210003, 0xc0000054 },
+        { 0x00270003, 0xc000007f },
+        { 0x00340001, 0xC00000bd },
+        { 0x00430001, 0xc00000cc },
+        { 0x00470001, 0xC00000d0 },
+        { 0x00500001, 0xc0000035 },
+        { 0x00570001, 0xc0000003 },
+        { 0x005a0002, 0xc00000ce },
+        { 0x006d0001, 0xC000014b },
+        { 0x007b0001, 0xc0000033 },
+        { 0x00910001, 0xC0000101 },
+        { 0x00b70001, 0xc0000035 },
+        { 0x00e70001, 0xc00000ab },
+        { 0x00e80001, 0xc00000b1 },
+        { 0x00e90001, 0xc00000b0 },
+        { 0x00ea0001, 0xc0000016 },
+        { 0x08bf0002, 0xC0000193 },
+        { 0x08c00002, 0xC0000070 },
+        { 0x08c10002, 0xC000006f },
+        { 0x08c20002, 0xC0000071 }
+    };
+
+    /* These aren't really used by jCIFS -- the map above is used
+     * to immediately map to NTSTATUS codes.
+     */
+    static final String[] DOS_ERROR_MESSAGES = {
+        "The operation completed successfully.",
+        "Incorrect function.",
+        "Incorrect function.",
+        "The system cannot find the file specified.",
+        "Bad password.",
+        "The system cannot find the path specified.",
+        "reserved",
+        "The client does not have the necessary access rights to perform the requested function.",
+        "Access is denied.",
+        "The TID specified was invalid.",
+        "The handle is invalid.",
+        "The network name cannot be found.",
+        "Not enough storage is available to process this command.",
+        "The media is write protected.",
+        "The device is not ready.",
+        "A device attached to the system is not functioning.",
+        "A device attached to the system is not functioning.",
+        "The process cannot access the file because it is being used by another process.",
+        "The process cannot access the file because it is being used by another process.",
+        "The process cannot access the file because another process has locked a portion of the file.",
+        "The disk is full.",
+        "A duplicate name exists on the network.",
+        "The network name cannot be found.",
+        "ERRnomoreconn.",
+        "The file exists.",
+        "The parameter is incorrect.",
+        "Too many Uids active on this session.",
+        "The pipe has been ended.",
+        "The filename, directory name, or volume label syntax is incorrect.",
+        "The directory is not empty.",
+        "Cannot create a file when that file already exists.",
+        "All pipe instances are busy.",
+        "The pipe is being closed.",
+        "No process is on the other end of the pipe.",
+        "More data is available.",
+        "This user account has expired.",
+        "The user is not allowed to log on from this workstation.",
+        "The user is not allowed to log on at this time.",
+        "The password of this user has expired."
+    };
+}
+
index bad58af..8ac89b4 100644 (file)
@@ -20,21 +20,21 @@ package jcifs.smb;
 
 public class DosFileFilter implements SmbFileFilter {
 
-       protected String wildcard;
-       protected int attributes;
+    protected String wildcard;
+    protected int attributes;
 
-       public DosFileFilter( String wildcard, int attributes ) {
-               this.wildcard = wildcard;
-               this.attributes = attributes;
-       }
+    public DosFileFilter( String wildcard, int attributes ) {
+        this.wildcard = wildcard;
+        this.attributes = attributes;
+    }
 
-       /**
-        * This always returns <tt>true</tt> as the wildcard and
-        * attributes members are passed to the server which uses them to
-        * filter on behalf of the client. Sub-classes might overload this
-        * method to further filter the list however.
-        */
-       public boolean accept( SmbFile file ) throws SmbException {
-               return true;
-       }
+    /**
+     * This always returns <tt>true</tt> as the wildcard and
+     * attributes members are passed to the server which uses them to
+     * filter on behalf of the client. Sub-classes might overload this
+     * method to further filter the list however.
+     */
+    public boolean accept( SmbFile file ) throws SmbException {
+        return true;
+    }
 }
index e16afb2..a659707 100644 (file)
@@ -2,10 +2,10 @@ package jcifs.smb;
 
 interface FileEntry {
 
-       String getName();
-       int getType();
-       int getAttributes();
-       long createTime();
-       long lastModified();
-       long length();
+    String getName();
+    int getType();
+    int getAttributes();
+    long createTime();
+    long lastModified();
+    long length();
 }
index 84ac84c..116f964 100644 (file)
@@ -28,80 +28,75 @@ import java.io.PrintStream;
 
 public class Handler extends URLStreamHandler {
 
-       static final URLStreamHandler SMB_HANDLER = new Handler();
+    static final URLStreamHandler SMB_HANDLER = new Handler();
 
-static void printURL( URL u, PrintStream out ) {
-       out.println( "host=" + u.getHost() + ",port=" + u.getPort() + ",authority=" + u.getAuthority() + ",userInfo=" + u.getUserInfo() + ",path=" + u.getPath() + ",query=" + u.getQuery() + ",ref=" + u.getRef() );
-}
-
-       static String unescape( String str ) throws NumberFormatException, UnsupportedEncodingException {
-               char ch;
-               int i, j, state, len;
-               char[] out;
-               byte[] b = new byte[1];
+    static String unescape( String str ) throws NumberFormatException, UnsupportedEncodingException {
+        char ch;
+        int i, j, state, len;
+        char[] out;
+        byte[] b = new byte[1];
 
-               if( str == null ) {
-                       return null;
-               }
+        if( str == null ) {
+            return null;
+        }
 
-               len = str.length();
-               out = new char[len];
-               state = 0;
-               for( i = j = 0; i < len; i++ ) {
-                       switch( state ) {
-                               case 0:
-                                       ch = str.charAt( i );
-                                       if( ch == '%' ) {
-                                               state = 1;
-                                       } else {
-                                               out[j++] = ch;
-                                       }
-                                       break;
-                               case 1:
-                                       /* Get ASCII hex value and convert to platform dependant
-                                        * encoding like EBCDIC perhaps
-                                        */
-                                       b[0] = (byte)(Integer.parseInt( str.substring( i, i + 2 ), 16 ) & 0xFF);
-                                       out[j++] = (new String( b, 0, 1, "ASCII" )).charAt( 0 );
-                                       i++;
-                                       state = 0;
-                       }
-               }
+        len = str.length();
+        out = new char[len];
+        state = 0;
+        for( i = j = 0; i < len; i++ ) {
+            switch( state ) {
+                case 0:
+                    ch = str.charAt( i );
+                    if( ch == '%' ) {
+                        state = 1;
+                    } else {
+                        out[j++] = ch;
+                    }
+                    break;
+                case 1:
+                    /* Get ASCII hex value and convert to platform dependant
+                     * encoding like EBCDIC perhaps
+                     */
+                    b[0] = (byte)(Integer.parseInt( str.substring( i, i + 2 ), 16 ) & 0xFF);
+                    out[j++] = (new String( b, 0, 1, "ASCII" )).charAt( 0 );
+                    i++;
+                    state = 0;
+            }
+        }
 
-               return new String( out, 0, j );
-       }
+        return new String( out, 0, j );
+    }
 
-       protected int getDefaultPort() {
-               return 139;
-       }
-       public URLConnection openConnection( URL u ) throws IOException {
-               return new SmbFile( u );
-       }
-       protected void parseURL( URL u, String spec, int start, int limit ) {
-               String host = u.getHost();
-               String userinfo, path, ref;
-               if( spec.equals( "smb://" )) {
-                       spec = "smb:////";
-                       limit += 2;
-               } else if( spec.startsWith( "smb://" ) == false &&
-                                       host != null && host.length() == 0 ) {
-                       spec = "//" + spec;
-                       limit += 2;
-               }
-               super.parseURL( u, spec, start, limit );
-               userinfo = u.getUserInfo();
-               path = u.getPath();
-               ref = u.getRef();
-               try {
-                       userinfo = unescape( userinfo );
-               } catch( UnsupportedEncodingException uee ) {
-               }
-               if (ref != null) {
-                       path += '#' + ref;
-               }
-               setURL( u, "smb://", u.getHost(), getDefaultPort(),
-                                       u.getAuthority(), userinfo,
-                                       path, u.getQuery(), null );
-//printURL( u, System.err );
-       }
+    protected int getDefaultPort() {
+        return 139;
+    }
+    public URLConnection openConnection( URL u ) throws IOException {
+        return new SmbFile( u );
+    }
+    protected void parseURL( URL u, String spec, int start, int limit ) {
+        String host = u.getHost();
+        String userinfo, path, ref;
+        if( spec.equals( "smb://" )) {
+            spec = "smb:////";
+            limit += 2;
+        } else if( spec.startsWith( "smb://" ) == false &&
+                    host != null && host.length() == 0 ) {
+            spec = "//" + spec;
+            limit += 2;
+        }
+        super.parseURL( u, spec, start, limit );
+        userinfo = u.getUserInfo();
+        path = u.getPath();
+        ref = u.getRef();
+        try {
+            userinfo = unescape( userinfo );
+        } catch( UnsupportedEncodingException uee ) {
+        }
+        if (ref != null) {
+            path += '#' + ref;
+        }
+        setURL( u, "smb://", u.getHost(), getDefaultPort(),
+                    u.getAuthority(), userinfo,
+                    path, u.getQuery(), null );
+    }
 }
index 17b6129..ef0dd91 100644 (file)
@@ -19,8 +19,8 @@
 package jcifs.smb;
 
 interface Info {
-       int getAttributes();
-       long getCreateTime();
-       long getLastWriteTime();
-       long getSize();
+    int getAttributes();
+    long getCreateTime();
+    long getLastWriteTime();
+    long getSize();
 }
diff --git a/src/jcifs/smb/Log.java b/src/jcifs/smb/Log.java
deleted file mode 100644 (file)
index 94ad2b6..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-/* jcifs smb client library in Java
- * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-package jcifs.smb;
-
-/**
- * Provides logging methods specific to the smb package. Log class
- * members are applied to the Log's mask(set as an arithmetic expression
- * from {@link jcifs.util.Log#setMask(int mask)}) to "flip on" logging of
- * smb specific information.
- * <p><blockquote><pre>
- *     Log.setMask( Log.EXCEPTIONS |
- *                 jcifs.smb.Log.MESSAGE_DATA );
- * </pre></blockquote>
- * <p>
- * See the {@link jcifs.util.Log} parent class for details about this
- * logging style.
- *
- * @see       jcifs.util.Log
- * @since     jcifs-0.1
- */
-
-public class Log extends jcifs.util.Log {
-
-    // supress javadoc constructor summary
-    Log() {}
-
-    public static final int MESSAGE_DATA     = 0x00000100;
-    public static final int TEST1            = 0x00000200;
-    public static final int RESERVED2        = 0x00000400;
-    public static final int RESERVED3        = 0x00000800;
-
-       static void printMessageData( String desc, ServerMessageBlock smb ) {
-               if(( mask & MESSAGE_DATA ) == 0 ) {
-                       return;
-               }
-               try {
-            out.println( desc, smb.toString() + NL );
-        } catch( Exception e ) {
-            Log.printStackTrace( "jcifs.smb.Log.printMessageData()", e );
-        }
-       }
-}
-
index b9e8dc1..c76838c 100644 (file)
@@ -22,67 +22,68 @@ import java.io.UnsupportedEncodingException;
 
 class NetServerEnum2 extends SmbComTransaction {
 
-       static final int SV_TYPE_ALL         = 0xFFFFFFFF;
-       static final int SV_TYPE_DOMAIN_ENUM = 0x80000000;
+    static final int SV_TYPE_ALL         = 0xFFFFFFFF;
+    static final int SV_TYPE_DOMAIN_ENUM = 0x80000000;
 
-       static final String DESCR = "WrLehDz\u0000B16BBDz\u0000";
+    static final String DESCR = "WrLehDz\u0000B16BBDz\u0000";
 
-       String domain;
-       int serverTypes;
+    String domain;
+    int serverTypes;
 
-       NetServerEnum2( String domain, int serverTypes ) {
-               this.domain = domain;
-               this.serverTypes = serverTypes;
-               command = SMB_COM_TRANSACTION;
-               subCommand = NET_SERVER_ENUM2; // not really true be used by upper logic
-               name = "\\PIPE\\LANMAN";
+    NetServerEnum2( String domain, int serverTypes ) {
+        this.domain = domain;
+        this.serverTypes = serverTypes;
+        command = SMB_COM_TRANSACTION;
+        subCommand = NET_SERVER_ENUM2; // not really true be used by upper logic
+        name = "\\PIPE\\LANMAN";
 
-               maxParameterCount = 8;
-               maxSetupCount = (byte)0x00;
-               setupCount = 0;
-               timeout = 5000;
-       }
+        maxParameterCount = 8;
+        maxDataCount = 4096;
+        maxSetupCount = (byte)0x00;
+        setupCount = 0;
+        timeout = 5000;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-               byte[] descr;
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+        byte[] descr;
 
-               try {
-                       descr = DESCR.getBytes( "ASCII" );
-               } catch( UnsupportedEncodingException uee )     {
-                       return 0;
-               }
+        try {
+            descr = DESCR.getBytes( "ASCII" );
+        } catch( UnsupportedEncodingException uee ) {
+            return 0;
+        }
 
-               writeInt2( NET_SERVER_ENUM2, dst, dstIndex );
-               dstIndex += 2;
-               System.arraycopy( descr, 0, dst, dstIndex, descr.length );
-               dstIndex += descr.length;
-               writeInt2( 0x0001, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( maxDataCount, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( serverTypes, dst, dstIndex );
-               dstIndex += 4;
-               dstIndex += writeString( domain.toUpperCase(), dst, dstIndex, false );
+        writeInt2( NET_SERVER_ENUM2, dst, dstIndex );
+        dstIndex += 2;
+        System.arraycopy( descr, 0, dst, dstIndex, descr.length );
+        dstIndex += descr.length;
+        writeInt2( 0x0001, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( maxDataCount, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( serverTypes, dst, dstIndex );
+        dstIndex += 4;
+        dstIndex += writeString( domain.toUpperCase(), dst, dstIndex, false );
 
-               return dstIndex - start;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "NetServerEnum2[" + super.toString() + ",name=" + name + ",serverTypes=" + (serverTypes == SV_TYPE_ALL ? "SV_TYPE_ALL" : "SV_TYPE_DOMAIN_ENUM" ) + "]" );
-       }
+        return dstIndex - start;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "NetServerEnum2[" + super.toString() + ",name=" + name + ",serverTypes=" + (serverTypes == SV_TYPE_ALL ? "SV_TYPE_ALL" : "SV_TYPE_DOMAIN_ENUM" ) + "]" );
+    }
 }
index de6571f..dabb0fa 100644 (file)
 
 package jcifs.smb;
 
-import jcifs.util.Log;
 import java.io.InputStream;
 import java.io.IOException;
+import jcifs.util.Hexdump;
 
 class NetServerEnum2Response extends SmbComTransactionResponse {
 
-       class ServerInfo1 implements FileEntry {
-               String name;
-               int versionMajor;
-               int versionMinor;
-               int type;
-               String commentOrMasterBrowser;
+    class ServerInfo1 implements FileEntry {
+        String name;
+        int versionMajor;
+        int versionMinor;
+        int type;
+        String commentOrMasterBrowser;
 
-               public String getName() {
-                       return name;
-               }
-               public int getType() {
-                       return (type & 0x80000000) != 0 ? SmbFile.TYPE_WORKGROUP : SmbFile.TYPE_SERVER;
-               }
-               public int getAttributes() {
-                       return SmbFile.ATTR_READONLY | SmbFile.ATTR_DIRECTORY;
-               }
-               public long createTime() {
-                       return 0L;
-               }
-               public long lastModified() {
-                       return 0L;
-               }
-               public long length() {
-                       return 0L;
-               }
+        public String getName() {
+            return name;
+        }
+        public int getType() {
+            return (type & 0x80000000) != 0 ? SmbFile.TYPE_WORKGROUP : SmbFile.TYPE_SERVER;
+        }
+        public int getAttributes() {
+            return SmbFile.ATTR_READONLY | SmbFile.ATTR_DIRECTORY;
+        }
+        public long createTime() {
+            return 0L;
+        }
+        public long lastModified() {
+            return 0L;
+        }
+        public long length() {
+            return 0L;
+        }
 
-               public String toString() {
-                       return new String( "ServerInfo1[" +
-                                       "name=" + name +
-                                       ",versionMajor=" + versionMajor +
-                                       ",versionMinor=" + versionMinor +
-                                       ",type=0x" + Log.getHexString( type, 8 ) +
-                                       ",commentOrMasterBrowser=" + commentOrMasterBrowser + "]" );
-               }
-       }
+        public String toString() {
+            return new String( "ServerInfo1[" +
+                    "name=" + name +
+                    ",versionMajor=" + versionMajor +
+                    ",versionMinor=" + versionMinor +
+                    ",type=0x" + Hexdump.toHexString( type, 8 ) +
+                    ",commentOrMasterBrowser=" + commentOrMasterBrowser + "]" );
+        }
+    }
 
-       int converter, totalAvailableEntries;
+    private int converter, totalAvailableEntries;
 
-       NetServerEnum2Response() {
-       }
+    NetServerEnum2Response() {
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               int start = bufferIndex;
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        int start = bufferIndex;
 
-               status = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               converter = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               numEntries = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               totalAvailableEntries = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
+        status = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        converter = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        numEntries = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        totalAvailableEntries = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
 
-               return bufferIndex - start;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               int start = bufferIndex;
-               ServerInfo1 e;
+        return bufferIndex - start;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        int start = bufferIndex;
+        ServerInfo1 e;
 
-               results = new ServerInfo1[numEntries];
-               for( int i = 0; i < numEntries; i++ ) {
-                       results[i] = e = new ServerInfo1();
-                       e.name = readString( buffer, bufferIndex, 16, false );
-                       bufferIndex += 16;
-                       e.versionMajor = (int)( buffer[bufferIndex++] & 0xFF );
-                       e.versionMinor = (int)( buffer[bufferIndex++] & 0xFF );
-                       e.type = readInt4( buffer, bufferIndex );
-                       bufferIndex += 4;
-                       int off = readInt4( buffer, bufferIndex );
-                       bufferIndex += 4;
-                       off = ( off & 0xFFFF ) - converter;
-                       off = start + off;
-                       e.commentOrMasterBrowser = readString( buffer, off, 48, false );
-Log.println( Log.WARNINGS, "net server enum response entry",  e );
-               }
+        results = new ServerInfo1[numEntries];
+        for( int i = 0; i < numEntries; i++ ) {
+            results[i] = e = new ServerInfo1();
+            e.name = readString( buffer, bufferIndex, 16, false );
+            bufferIndex += 16;
+            e.versionMajor = (int)( buffer[bufferIndex++] & 0xFF );
+            e.versionMinor = (int)( buffer[bufferIndex++] & 0xFF );
+            e.type = readInt4( buffer, bufferIndex );
+            bufferIndex += 4;
+            int off = readInt4( buffer, bufferIndex );
+            bufferIndex += 4;
+            off = ( off & 0xFFFF ) - converter;
+            off = start + off;
+            e.commentOrMasterBrowser = readString( buffer, off, 48, false );
 
-               return bufferIndex - start;
-       }
-       public String toString() {
-               return new String( "NetServerEnum2Response[" +
-                               super.toString() +
-                               ",status=" + status +
-                               ",converter=" + converter +
-                               ",entriesReturned=" + numEntries +
-                               ",totalAvailableEntries=" + totalAvailableEntries + "]" );
-       }
+            if( log.level > 2 )
+                log.println( e );
+        }
+
+        return bufferIndex - start;
+    }
+    public String toString() {
+        return new String( "NetServerEnum2Response[" +
+                super.toString() +
+                ",status=" + status +
+                ",converter=" + converter +
+                ",entriesReturned=" + numEntries +
+                ",totalAvailableEntries=" + totalAvailableEntries + "]" );
+    }
 }
index 56c04d0..685fb9f 100644 (file)
@@ -22,57 +22,57 @@ import java.io.UnsupportedEncodingException;
 
 class NetShareEnum extends SmbComTransaction {
 
-       static final String DESCR = "WrLeh\u0000B13BWz\u0000";
+    private static final String DESCR = "WrLeh\u0000B13BWz\u0000";
 
-       NetShareEnum() {
-               command = SMB_COM_TRANSACTION;
-               subCommand = NET_SHARE_ENUM; // not really true be used by upper logic
-               name = new String( "\\PIPE\\LANMAN" );
-               maxParameterCount = 8;
+    NetShareEnum() {
+        command = SMB_COM_TRANSACTION;
+        subCommand = NET_SHARE_ENUM; // not really true be used by upper logic
+        name = new String( "\\PIPE\\LANMAN" );
+        maxParameterCount = 8;
 
-               maxDataCount = 4096;
-               maxSetupCount = (byte)0x00;
-               setupCount = 0;
-               timeout = 5000;
-       }
+        maxDataCount = 4096;
+        maxSetupCount = (byte)0x00;
+        setupCount = 0;
+        timeout = 5000;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-               byte[] descr;
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+        byte[] descr;
 
-               try {
-                       descr = DESCR.getBytes( "ASCII" );
-               } catch( UnsupportedEncodingException uee ) {
-                       return 0;
-               }
+        try {
+            descr = DESCR.getBytes( "ASCII" );
+        } catch( UnsupportedEncodingException uee ) {
+            return 0;
+        }
 
-               writeInt2( NET_SHARE_ENUM, dst, dstIndex );
-               dstIndex += 2;
-               System.arraycopy( descr, 0, dst, dstIndex, descr.length );
-               dstIndex += descr.length;
-               writeInt2( 0x0001, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( maxDataCount, dst, dstIndex );
-               dstIndex += 2;
+        writeInt2( NET_SHARE_ENUM, dst, dstIndex );
+        dstIndex += 2;
+        System.arraycopy( descr, 0, dst, dstIndex, descr.length );
+        dstIndex += descr.length;
+        writeInt2( 0x0001, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( maxDataCount, dst, dstIndex );
+        dstIndex += 2;
 
-               return dstIndex - start;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "NetShareEnum[" + super.toString() + "]" );
-       }
+        return dstIndex - start;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "NetShareEnum[" + super.toString() + "]" );
+    }
 }
index 3b7024a..b8514eb 100644 (file)
 
 package jcifs.smb;
 
-import jcifs.util.Log;
 import java.io.InputStream;
 import java.io.IOException;
+import jcifs.util.Hexdump;
 
 class NetShareEnumResponse extends SmbComTransactionResponse {
 
-       class ShareInfo1 implements FileEntry {
-               String netName;
-               int type;
-               String remark;
+    class ShareInfo1 implements FileEntry {
+        String netName;
+        int type;
+        String remark;
 
-               public String getName() {
-                       return netName;
-               }
-               public int getType() {
-                       switch( type ) {
-                               case 1:
-                                       return SmbFile.TYPE_PRINTER;
-                               case 3:
-                                       return SmbFile.TYPE_NAMED_PIPE;
-                       }
-                       return SmbFile.TYPE_SHARE;
-               }
-               public int getAttributes() {
-                       return SmbFile.ATTR_READONLY | SmbFile.ATTR_DIRECTORY;
-               }
-               public long createTime() {
-                       return 0L;
-               }
-               public long lastModified() {
-                       return 0L;
-               }
-               public long length() {
-                       return 0L;
-               }
+        public String getName() {
+            return netName;
+        }
+        public int getType() {
+            switch( type ) {
+                case 1:
+                    return SmbFile.TYPE_PRINTER;
+                case 3:
+                    return SmbFile.TYPE_NAMED_PIPE;
+            }
+            return SmbFile.TYPE_SHARE;
+        }
+        public int getAttributes() {
+            return SmbFile.ATTR_READONLY | SmbFile.ATTR_DIRECTORY;
+        }
+        public long createTime() {
+            return 0L;
+        }
+        public long lastModified() {
+            return 0L;
+        }
+        public long length() {
+            return 0L;
+        }
 
-               public String toString() {
-                       return new String( "ShareInfo1[" +
-                                       "netName=" + netName +
-                                       ",type=0x" + Log.getHexString( type, 4 ) +
-                                       ",remark=" + remark + "]" );
-               }
-       }
+        public String toString() {
+            return new String( "ShareInfo1[" +
+                    "netName=" + netName +
+                    ",type=0x" + Hexdump.toHexString( type, 4 ) +
+                    ",remark=" + remark + "]" );
+        }
+    }
 
-       int converter, totalAvailableEntries;
+    private int converter, totalAvailableEntries;
 
-       NetShareEnumResponse() {
-       }
+    NetShareEnumResponse() {
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               int start = bufferIndex;
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        int start = bufferIndex;
 
-               status = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               converter = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               numEntries = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               totalAvailableEntries = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
+        status = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        converter = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        numEntries = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        totalAvailableEntries = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
 
-               return bufferIndex - start;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               int start = bufferIndex;
-               ShareInfo1 e;
+        return bufferIndex - start;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        int start = bufferIndex;
+        ShareInfo1 e;
 
-               useUnicode = false;
+        useUnicode = false;
 
-               results = new ShareInfo1[numEntries];
-               for( int i = 0; i < numEntries; i++ ) {
-                       results[i] = e = new ShareInfo1();
-                       e.netName = readString( buffer, bufferIndex, 13, false );
-                       bufferIndex += 14;
-                       e.type = readInt2( buffer, bufferIndex );
-                       bufferIndex += 2;
-                       int off = readInt4( buffer, bufferIndex );
-                       bufferIndex += 4;
-                       off = ( off & 0xFFFF ) - converter;
-                       off = start + off;
-                       e.remark = readString( buffer, off, 128, false );
-Log.println( Log.WARNINGS, "smb warning", e );
-               }
+        results = new ShareInfo1[numEntries];
+        for( int i = 0; i < numEntries; i++ ) {
+            results[i] = e = new ShareInfo1();
+            e.netName = readString( buffer, bufferIndex, 13, false );
+            bufferIndex += 14;
+            e.type = readInt2( buffer, bufferIndex );
+            bufferIndex += 2;
+            int off = readInt4( buffer, bufferIndex );
+            bufferIndex += 4;
+            off = ( off & 0xFFFF ) - converter;
+            off = start + off;
+            e.remark = readString( buffer, off, 128, false );
 
-               return bufferIndex - start;
-       }
-       public String toString() {
-               return new String( "NetShareEnumResponse[" +
-                               super.toString() +
-                               ",status=" + status +
-                               ",converter=" + converter +
-                               ",entriesReturned=" + numEntries +
-                               ",totalAvailableEntries=" + totalAvailableEntries + "]" );
-       }
+            if( log.level > 2 )
+                log.println( e );
+        }
+
+        return bufferIndex - start;
+    }
+    public String toString() {
+        return new String( "NetShareEnumResponse[" +
+                super.toString() +
+                ",status=" + status +
+                ",converter=" + converter +
+                ",entriesReturned=" + numEntries +
+                ",totalAvailableEntries=" + totalAvailableEntries + "]" );
+    }
 }
diff --git a/src/jcifs/smb/NtStatus.java b/src/jcifs/smb/NtStatus.java
new file mode 100644 (file)
index 0000000..8e0213a
--- /dev/null
@@ -0,0 +1,148 @@
+/* jcifs smb client library in Java
+ * Copyright (C) 2004  "Michael B. Allen" <jcifs at samba dot org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package jcifs.smb;
+
+public interface NtStatus {
+
+    /* Don't bother to edit this. Everthing within the interface
+     * block is automatically generated from the ntstatus package.
+     */
+
+    public static final int NT_STATUS_OK = 0x00000000;
+    public static final int NT_STATUS_UNSUCCESSFUL = 0xC0000001;
+    public static final int NT_STATUS_NOT_IMPLEMENTED = 0xC0000002;
+    public static final int NT_STATUS_INVALID_INFO_CLASS = 0xC0000003;
+    public static final int NT_STATUS_INVALID_HANDLE = 0xC0000008;
+    public static final int NT_STATUS_NO_SUCH_FILE = 0xC000000f;
+    public static final int NT_STATUS_ACCESS_DENIED = 0xC0000022;
+    public static final int NT_STATUS_OBJECT_NAME_INVALID = 0xC0000033;
+    public static final int NT_STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034;
+    public static final int NT_STATUS_OBJECT_NAME_COLLISION = 0xC0000035;
+    public static final int NT_STATUS_PORT_DISCONNECTED = 0xC0000037;
+    public static final int NT_STATUS_OBJECT_PATH_NOT_FOUND = 0xC000003a;
+    public static final int NT_STATUS_OBJECT_PATH_SYNTAX_BAD = 0xC000003b;
+    public static final int NT_STATUS_SHARING_VIOLATION = 0xC0000043;
+    public static final int NT_STATUS_DELETE_PENDING = 0xC0000056;
+    public static final int NT_STATUS_NO_SUCH_USER = 0xC0000064;
+    public static final int NT_STATUS_WRONG_PASSWORD = 0xC000006a;
+    public static final int NT_STATUS_LOGON_FAILURE = 0xC000006d;
+    public static final int NT_STATUS_ACCOUNT_RESTRICTION = 0xC000006e;
+    public static final int NT_STATUS_INVALID_LOGON_HOURS = 0xC000006f;
+    public static final int NT_STATUS_INVALID_WORKSTATION = 0xC0000070;
+    public static final int NT_STATUS_PASSWORD_EXPIRED = 0xC0000071;
+    public static final int NT_STATUS_ACCOUNT_DISABLED = 0xC0000072;
+    public static final int NT_STATUS_INSTANCE_NOT_AVAILABLE = 0xC00000ab;
+    public static final int NT_STATUS_PIPE_NOT_AVAILABLE = 0xC00000ac;
+    public static final int NT_STATUS_INVALID_PIPE_STATE = 0xC00000ad;
+    public static final int NT_STATUS_PIPE_BUSY = 0xC00000ae;
+    public static final int NT_STATUS_PIPE_DISCONNECTED = 0xC00000b0;
+    public static final int NT_STATUS_PIPE_CLOSING = 0xC00000b1;
+    public static final int NT_STATUS_PIPE_LISTENING = 0xC00000b3;
+    public static final int NT_STATUS_FILE_IS_A_DIRECTORY = 0xC00000ba;
+    public static final int NT_STATUS_BAD_NETWORK_NAME = 0xC00000cc;
+    public static final int NT_STATUS_NOT_A_DIRECTORY = 0xC0000103;
+    public static final int NT_STATUS_CANNOT_DELETE = 0xC0000121;
+    public static final int NT_STATUS_PIPE_BROKEN = 0xC000014b;
+    public static final int NT_STATUS_LOGON_TYPE_NOT_GRANTED = 0xC000015b;
+    public static final int NT_STATUS_ACCOUNT_LOCKED_OUT = 0xC0000234;
+    public static final int NT_STATUS_PATH_NOT_COVERED = 0xC0000257;
+
+    static final int[] NT_STATUS_CODES = {
+        NT_STATUS_OK,
+        NT_STATUS_UNSUCCESSFUL,
+        NT_STATUS_NOT_IMPLEMENTED,
+        NT_STATUS_INVALID_INFO_CLASS,
+        NT_STATUS_INVALID_HANDLE,
+        NT_STATUS_NO_SUCH_FILE,
+        NT_STATUS_ACCESS_DENIED,
+        NT_STATUS_OBJECT_NAME_INVALID,
+        NT_STATUS_OBJECT_NAME_NOT_FOUND,
+        NT_STATUS_OBJECT_NAME_COLLISION,
+        NT_STATUS_PORT_DISCONNECTED,
+        NT_STATUS_OBJECT_PATH_NOT_FOUND,
+        NT_STATUS_OBJECT_PATH_SYNTAX_BAD,
+        NT_STATUS_SHARING_VIOLATION,
+        NT_STATUS_DELETE_PENDING,
+        NT_STATUS_NO_SUCH_USER,
+        NT_STATUS_WRONG_PASSWORD,
+        NT_STATUS_LOGON_FAILURE,
+        NT_STATUS_ACCOUNT_RESTRICTION,
+        NT_STATUS_INVALID_LOGON_HOURS,
+        NT_STATUS_INVALID_WORKSTATION,
+        NT_STATUS_PASSWORD_EXPIRED,
+        NT_STATUS_ACCOUNT_DISABLED,
+        NT_STATUS_INSTANCE_NOT_AVAILABLE,
+        NT_STATUS_PIPE_NOT_AVAILABLE,
+        NT_STATUS_INVALID_PIPE_STATE,
+        NT_STATUS_PIPE_BUSY,
+        NT_STATUS_PIPE_DISCONNECTED,
+        NT_STATUS_PIPE_CLOSING,
+        NT_STATUS_PIPE_LISTENING,
+        NT_STATUS_FILE_IS_A_DIRECTORY,
+        NT_STATUS_BAD_NETWORK_NAME,
+        NT_STATUS_NOT_A_DIRECTORY,
+        NT_STATUS_CANNOT_DELETE,
+        NT_STATUS_PIPE_BROKEN,
+        NT_STATUS_LOGON_TYPE_NOT_GRANTED,
+        NT_STATUS_ACCOUNT_LOCKED_OUT,
+        NT_STATUS_PATH_NOT_COVERED,
+    };
+
+    static final String[] NT_STATUS_MESSAGES = {
+        "The operation completed successfully.",
+        "A device attached to the system is not functioning.",
+        "Incorrect function.",
+        "The parameter is incorrect.",
+        "The handle is invalid.",
+        "The system cannot find the file specified.",
+        "Access is denied.",
+        "The filename, directory name, or volume label syntax is incorrect.",
+        "The system cannot find the file specified.",
+        "Cannot create a file when that file already exists.",
+        "The handle is invalid.",
+        "The system cannot find the path specified.",
+        "The specified path is invalid.",
+        "The process cannot access the file because it is being used by another process.",
+        "Access is denied.",
+        "The specified user does not exist.",
+        "The specified network password is not correct.",
+        "Logon failure: unknown user name or bad password.",
+        "Logon failure: user account restriction.",
+        "Logon failure: account logon time restriction violation.",
+        "Logon failure: user not allowed to log on to this computer.",
+        "Logon failure: the specified account password has expired.",
+        "Logon failure: account currently disabled.",
+        "All pipe instances are busy.",
+        "All pipe instances are busy.",
+        "The pipe state is invalid.",
+        "All pipe instances are busy.",
+        "No process is on the other end of the pipe.",
+        "The pipe is being closed.",
+        "Waiting for a process to open the other end of the pipe.",
+        "Access is denied.",
+        "The network name cannot be found.",
+        "The directory name is invalid.",
+        "Access is denied.",
+        "The pipe has been ended.",
+        "Logon failure: the user has not been granted the requested logon type at this computer.",
+        "The referenced account is currently locked out and may not be logged on to.",
+        "The remote system is not reachable by the transport.",
+    };
+}
+
index 9eb5bad..58e6323 100644 (file)
@@ -24,54 +24,54 @@ This class can be extended by applications that wish to trap authentication rela
 
 public abstract class NtlmAuthenticator {
 
-       private static NtlmAuthenticator auth;
+    private static NtlmAuthenticator auth;
 
-       private String url;
-       private SmbAuthException sae;
+    private String url;
+    private SmbAuthException sae;
 
-       private void reset() {
-               url = null;
-               sae = null;
-       }
+    private void reset() {
+        url = null;
+        sae = null;
+    }
 
 /**
 Set the default <tt>NtlmAuthenticator</tt>. Once the default authenticator is set it cannot be changed. Calling this metho again will have no effect.
  */
 
-       public synchronized static void setDefault( NtlmAuthenticator a ) {
-               if( auth != null ) {
-                       return;
-               }
-               auth = a;
-       }
+    public synchronized static void setDefault( NtlmAuthenticator a ) {
+        if( auth != null ) {
+            return;
+        }
+        auth = a;
+    }
 
-       protected final String getRequestingURL() {
-               return url;
-       }
-       protected final SmbAuthException getRequestingException() {
-               return sae;
-       }
+    protected final String getRequestingURL() {
+        return url;
+    }
+    protected final SmbAuthException getRequestingException() {
+        return sae;
+    }
 
 /**
 Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
  */
 
-       public static NtlmPasswordAuthentication
-                               requestNtlmPasswordAuthentication( String url, SmbAuthException sae ) {
-               if( auth == null ) {
-                       return null;
-               }
-               synchronized( auth ) {
-                       auth.url = url;
-                       auth.sae = sae;
-                       return auth.getNtlmPasswordAuthentication();
-               }
-       }
+    public static NtlmPasswordAuthentication
+                requestNtlmPasswordAuthentication( String url, SmbAuthException sae ) {
+        if( auth == null ) {
+            return null;
+        }
+        synchronized( auth ) {
+            auth.url = url;
+            auth.sae = sae;
+            return auth.getNtlmPasswordAuthentication();
+        }
+    }
 /**
 An application extending this class must provide an implementation for this method that returns new user credentials try try when accessing SMB resources described by the <tt>getRequestingURL</tt> and <tt>getRequestingException</tt> methods.
 If this method returns <tt>null</tt> the <tt>SmbAuthException</tt> that triggered the authenticator check will simply be rethrown. The default implementation returns <tt>null</tt>.
 */
-       protected NtlmPasswordAuthentication getNtlmPasswordAuthentication() {
-               return null;
-       }
+    protected NtlmPasswordAuthentication getNtlmPasswordAuthentication() {
+        return null;
+    }
 }
index e6c02e6..aceb373 100644 (file)
@@ -1,6 +1,6 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2002  "Michael B. Allen" <jcifs at samba dot org>
- *                                     "Eric Glass" <jcifs at samba dot org>
+ *                  "Eric Glass" <jcifs at samba dot org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
 
 package jcifs.smb;
 
-import jcifs.util.DES;
-import jcifs.util.MD4;
-import jcifs.util.HMACT64;
 import java.io.UnsupportedEncodingException;
 import java.io.Serializable;
 import java.security.Principal;
 import java.util.Random;
 import java.util.Arrays;
 import jcifs.Config;
+import jcifs.util.LogStream;
+import jcifs.util.DES;
+import jcifs.util.MD4;
+import jcifs.util.HMACT64;
 
 /**
  * This class stores and encrypts NTLM user credentials. The default
@@ -41,126 +42,131 @@ import jcifs.Config;
 
 public final class NtlmPasswordAuthentication implements Principal, Serializable {
 
-       private static final int LM_COMPATIBILITY =
-                       Config.getInt("jcifs.smb.lmCompatibility", 0);
+    private static final int LM_COMPATIBILITY =
+            Config.getInt("jcifs.smb.lmCompatibility", 0);
 
-       private static final String DEFAULT_DOMAIN =
-                       Config.getProperty("jcifs.smb.client.domain", "?");
+    private static final String DEFAULT_DOMAIN =
+            Config.getProperty("jcifs.smb.client.domain", "?");
 
-       private static final String DEFAULT_USERNAME =
-                       Config.getProperty("jcifs.smb.client.username", "GUEST");
+    private static final String DEFAULT_USERNAME =
+            Config.getProperty("jcifs.smb.client.username", "GUEST");
 
-       private static final String DEFAULT_PASSWORD =
-                       Config.getProperty("jcifs.smb.client.password", "");
+    private static final String DEFAULT_PASSWORD =
+            Config.getProperty("jcifs.smb.client.password", "");
 
-       private static final Random RANDOM = new Random();
+    private static final Random RANDOM = new Random();
 
-       // KGS!@#$%
-       static final byte[] S8 = {
-               (byte)0x4b, (byte)0x47, (byte)0x53, (byte)0x21,
-               (byte)0x40, (byte)0x23, (byte)0x24, (byte)0x25
-       };
-       static void E( byte[] key, byte[] data, byte[] e ) {
-               byte[] key7 = new byte[7];
-               byte[] e8 = new byte[8];
+    private static LogStream log = LogStream.getInstance();
 
-               for( int i = 0; i < key.length / 7; i++ ) {
-                       System.arraycopy( key, i * 7, key7, 0, 7 );
-                       DES des = new DES( key7 );
-                       des.encrypt( data, e8 );
-                       System.arraycopy( e8, 0, e, i * 8, 8 );
-               }
-       }
+    // KGS!@#$%
+    private static final byte[] S8 = {
+        (byte)0x4b, (byte)0x47, (byte)0x53, (byte)0x21,
+        (byte)0x40, (byte)0x23, (byte)0x24, (byte)0x25
+    };
+    private static void E( byte[] key, byte[] data, byte[] e ) {
+        byte[] key7 = new byte[7];
+        byte[] e8 = new byte[8];
+
+        for( int i = 0; i < key.length / 7; i++ ) {
+            System.arraycopy( key, i * 7, key7, 0, 7 );
+            DES des = new DES( key7 );
+            des.encrypt( data, e8 );
+            System.arraycopy( e8, 0, e, i * 8, 8 );
+        }
+    }
 /**
  * Generate the ANSI DES hash for the password associated with these credentials.
  */
-       static public byte[] getPreNTLMResponse( String password, byte[] challenge ) {
-               byte[] p14 = new byte[14];
-               byte[] p21 = new byte[21];
-               byte[] p24 = new byte[24];
-               byte[] passwordBytes;
-               try {
-                       passwordBytes = password.toUpperCase().getBytes( ServerMessageBlock.encoding );
-               } catch( UnsupportedEncodingException uee ) {
-                       return null;
-               }
-               int passwordLength = passwordBytes.length;
+    static public byte[] getPreNTLMResponse( String password, byte[] challenge ) {
+        byte[] p14 = new byte[14];
+        byte[] p21 = new byte[21];
+        byte[] p24 = new byte[24];
+        byte[] passwordBytes;
+        try {
+            passwordBytes = password.toUpperCase().getBytes( ServerMessageBlock.OEM_ENCODING );
+        } catch( UnsupportedEncodingException uee ) {
+            return null;
+        }
+        int passwordLength = passwordBytes.length;
 
-               // Only encrypt the first 14 bytes of the password for Pre 0.12 NT LM
-               if( passwordLength > 14) {
-                       passwordLength = 14;
-               }
-               System.arraycopy( passwordBytes, 0, p14, 0, passwordLength );
-               E( p14, S8, p21);
-               E( p21, challenge, p24);
-               return p24;
-       }
+        // Only encrypt the first 14 bytes of the password for Pre 0.12 NT LM
+        if( passwordLength > 14) {
+            passwordLength = 14;
+        }
+        System.arraycopy( passwordBytes, 0, p14, 0, passwordLength );
+        E( p14, S8, p21);
+        E( p21, challenge, p24);
+        return p24;
+    }
 /**
  * Generate the Unicode MD4 hash for the password associated with these credentials.
  */
-       static public byte[] getNTLMResponse( String password, byte[] challenge ) {
-               byte[] uni = null;
-               byte[] p21 = new byte[21];
-               byte[] p24 = new byte[24];
+    static public byte[] getNTLMResponse( String password, byte[] challenge ) {
+        byte[] uni = null;
+        byte[] p21 = new byte[21];
+        byte[] p24 = new byte[24];
 
-               try {
-                       uni = password.getBytes( "UnicodeLittleUnmarked" );
-               } catch( UnsupportedEncodingException uee ) {
-                       Log.printStackTrace( "password encryption exception", uee );
-               }
-               MD4 md4 = new MD4();
-               md4.update( uni );
-               try {
-                       md4.digest(p21, 0, 16);
-               } catch (Exception ex) {
-                       Log.printStackTrace( "digest exception", ex );
-               }
-               E( p21, challenge, p24 );
-               return p24;
-       }
+        try {
+            uni = password.getBytes( "UnicodeLittleUnmarked" );
+        } catch( UnsupportedEncodingException uee ) {
+            if( log.level > 0 )
+                uee.printStackTrace( log );
+        }
+        MD4 md4 = new MD4();
+        md4.update( uni );
+        try {
+            md4.digest(p21, 0, 16);
+        } catch (Exception ex) {
+            if( log.level > 0 )
+                ex.printStackTrace( log );
+        }
+        E( p21, challenge, p24 );
+        return p24;
+    }
 
-       /**
-        * Creates the LMv2 response for the supplied information.
-        *
-        * @param domain The domain in which the username exists.
-        * @param user The username.
-        * @param password The user's password.
-        * @param challenge The server challenge.
-        * @param clientChallenge The client challenge (nonce). 
-        */ 
-       public static byte[] getLMv2Response(String domain, String user,
-                       String password, byte[] challenge, byte[] clientChallenge) {
-               try {
-                       byte[] hash = new byte[16];
-                       byte[] response = new byte[24];
-                       MD4 md4 = new MD4();
-                       md4.update(password.getBytes("UnicodeLittleUnmarked"));
-                       HMACT64 hmac = new HMACT64(md4.digest());
-                       hmac.update(user.toUpperCase().getBytes("UnicodeLittleUnmarked"));
-                       hmac.update(domain.toUpperCase().getBytes("UnicodeLittleUnmarked"));
-                       hmac = new HMACT64(hmac.digest());
-                       hmac.update(challenge);
-                       hmac.update(clientChallenge);
-                       hmac.digest(response, 0, 16);
-                       System.arraycopy(clientChallenge, 0, response, 16, 8);
-                       return response;
-               } catch (Exception ex) {
-                       Log.printStackTrace("Error creating LMv2 response", ex);
-                       return null;
-               }
-       }
+    /**
+     * Creates the LMv2 response for the supplied information.
+     *
+     * @param domain The domain in which the username exists.
+     * @param user The username.
+     * @param password The user's password.
+     * @param challenge The server challenge.
+     * @param clientChallenge The client challenge (nonce). 
+     */ 
+    public static byte[] getLMv2Response(String domain, String user,
+            String password, byte[] challenge, byte[] clientChallenge) {
+        try {
+            byte[] hash = new byte[16];
+            byte[] response = new byte[24];
+            MD4 md4 = new MD4();
+            md4.update(password.getBytes("UnicodeLittleUnmarked"));
+            HMACT64 hmac = new HMACT64(md4.digest());
+            hmac.update(user.toUpperCase().getBytes("UnicodeLittleUnmarked"));
+            hmac.update(domain.toUpperCase().getBytes("UnicodeLittleUnmarked"));
+            hmac = new HMACT64(hmac.digest());
+            hmac.update(challenge);
+            hmac.update(clientChallenge);
+            hmac.digest(response, 0, 16);
+            System.arraycopy(clientChallenge, 0, response, 16, 8);
+            return response;
+        } catch (Exception ex) {
+            if( log.level > 0 )
+                ex.printStackTrace( log );
+            return null;
+        }
+    }
 
-       static final NtlmPasswordAuthentication NULL =
-                               new NtlmPasswordAuthentication( "", "", "" );
-       static final NtlmPasswordAuthentication GUEST =
-                               new NtlmPasswordAuthentication( "?", "GUEST", "" );
+public  static final NtlmPasswordAuthentication NULL =
+                new NtlmPasswordAuthentication( "", "", "" );
+    static final NtlmPasswordAuthentication GUEST =
+                new NtlmPasswordAuthentication( "?", "GUEST", "" );
 
-       String domain;
-       String username;
-       String password;
-       byte[] ansiHash;
-       byte[] unicodeHash;
-       boolean hashesExternal = false;
+    String domain;
+    String username;
+    String password;
+    byte[] ansiHash;
+    byte[] unicodeHash;
+    boolean hashesExternal = false;
     byte[] clientChallenge = null;
 
 /**
@@ -169,31 +175,31 @@ public final class NtlmPasswordAuthentication implements Principal, Serializable
  * is used internally be jCIFS when parsing SMB URLs.
  */
 
-       public NtlmPasswordAuthentication( String userInfo ) {
-               domain = username = password = null;
+    public NtlmPasswordAuthentication( String userInfo ) {
+        domain = username = password = null;
 
-               if( userInfo != null ) {
-                       int i, u, end;
-                       char c;
+        if( userInfo != null ) {
+            int i, u, end;
+            char c;
 
-                       end = userInfo.length();
-                       for( i = 0, u = 0; i < end; i++ ) {
-                               c = userInfo.charAt( i );
-                               if( c == ';' ) {
-                                       domain = userInfo.substring( 0, i );
-                                       u = i + 1;
-                               } else if( c == ':' ) {
-                                       password = userInfo.substring( i + 1 );
-                                       break;
-                               }
-                       }
-                       username = userInfo.substring( u, i );
-               }
+            end = userInfo.length();
+            for( i = 0, u = 0; i < end; i++ ) {
+                c = userInfo.charAt( i );
+                if( c == ';' ) {
+                    domain = userInfo.substring( 0, i );
+                    u = i + 1;
+                } else if( c == ':' ) {
+                    password = userInfo.substring( i + 1 );
+                    break;
+                }
+            }
+            username = userInfo.substring( u, i );
+        }
 
-               if( domain == null ) this.domain = DEFAULT_DOMAIN;
-               if( username == null ) this.username = DEFAULT_USERNAME;
-               if( password == null ) this.password = DEFAULT_PASSWORD;
-       }
+        if( domain == null ) this.domain = DEFAULT_DOMAIN;
+        if( username == null ) this.username = DEFAULT_USERNAME;
+        if( password == null ) this.password = DEFAULT_PASSWORD;
+    }
 /**
  * Create an <tt>NtlmPasswordAuthentication</tt> object from a
  * domain, username, and password. Parameters that are <tt>null</tt>
@@ -201,45 +207,45 @@ public final class NtlmPasswordAuthentication implements Principal, Serializable
  * <tt>jcifs.smb.client.username</tt>, <tt>jcifs.smb.client.password</tt>
  * property values.
  */
-       public NtlmPasswordAuthentication( String domain, String username, String password ) {
-               this.domain = domain;
-               this.username = username;
-               this.password = password;
-               if( domain == null ) this.domain = DEFAULT_DOMAIN;
-               if( username == null ) this.username = DEFAULT_USERNAME;
-               if( password == null ) this.password = DEFAULT_PASSWORD;
-       }
+    public NtlmPasswordAuthentication( String domain, String username, String password ) {
+        this.domain = domain;
+        this.username = username;
+        this.password = password;
+        if( domain == null ) this.domain = DEFAULT_DOMAIN;
+        if( username == null ) this.username = DEFAULT_USERNAME;
+        if( password == null ) this.password = DEFAULT_PASSWORD;
+    }
 /**
  * Create an <tt>NtlmPasswordAuthentication</tt> object with raw password
  * hashes. This is used exclusively by the <tt>jcifs.http.NtlmSsp</tt>
  * class which is in turn used by NTLM HTTP authentication functionality.
  */
-       public NtlmPasswordAuthentication( String domain, String username,
-                                                                       byte[] ansiHash, byte[] unicodeHash ) {
-               if( domain == null || username == null ||
-                                                                       ansiHash == null || unicodeHash == null ) {
-                       throw new IllegalArgumentException( "External credentials cannot null" );
-               }
-               this.domain = domain;
-               this.username = username;
-               this.password = null;
-               this.ansiHash = ansiHash;
-               this.unicodeHash = unicodeHash;
-               hashesExternal = true;
-       }
+    public NtlmPasswordAuthentication( String domain, String username,
+                                    byte[] ansiHash, byte[] unicodeHash ) {
+        if( domain == null || username == null ||
+                                    ansiHash == null || unicodeHash == null ) {
+            throw new IllegalArgumentException( "External credentials cannot null" );
+        }
+        this.domain = domain;
+        this.username = username;
+        this.password = null;
+        this.ansiHash = ansiHash;
+        this.unicodeHash = unicodeHash;
+        hashesExternal = true;
+    }
 
 /**
  * Returns the domain.
  */
-       public String getDomain() {
-               return domain;
-       }
+    public String getDomain() {
+        return domain;
+    }
 /**
  * Returns the username.
  */
-       public String getUsername() {
-               return username;
-       }
+    public String getUsername() {
+        return username;
+    }
 /**
  * Returns the password in plain text or <tt>null</tt> if the raw password
  * hashes were used to construct this <tt>NtlmPasswordAuthentication</tt>
@@ -247,72 +253,72 @@ public final class NtlmPasswordAuthentication implements Principal, Serializable
  * used. There is no way to retrieve a users password in plain text unless
  * it is supplied by the user at runtime.
  */
-       public String getPassword() {
-               return password;
-       }
+    public String getPassword() {
+        return password;
+    }
 /**
  * Return the domain and username in the format:
  * <tt>domain\\username</tt>. This is equivalent to <tt>toString()</tt>.
  */
-       public String getName() {
-               boolean d = domain.length() > 0 && domain.equals( "?" ) == false;
-               return d ? domain + "\\" + username : username;
-       }
+    public String getName() {
+        boolean d = domain.length() > 0 && domain.equals( "?" ) == false;
+        return d ? domain + "\\" + username : username;
+    }
 
 /**
  * Computes the 24 byte ANSI password hash given the 8 byte server challenge.
  */
-       public byte[] getAnsiHash( byte[] challenge ) {
-               if( hashesExternal ) {
-                       return ansiHash;
-               }
-               switch (LM_COMPATIBILITY) {
-               case 0:
-               case 1:
-                       return getPreNTLMResponse( password, challenge );
-               case 2:
-                       return getNTLMResponse( password, challenge );
-               case 3:
-               case 4:
-               case 5:
-                       if( clientChallenge == null ) {
-                               clientChallenge = new byte[8];
-                               RANDOM.nextBytes( clientChallenge );
-                       }
-                       return getLMv2Response(domain, username, password, challenge,
-                                       clientChallenge);
-               default:
-                       return getPreNTLMResponse( password, challenge );
-               }
-       }
+    public byte[] getAnsiHash( byte[] challenge ) {
+        if( hashesExternal ) {
+            return ansiHash;
+        }
+        switch (LM_COMPATIBILITY) {
+        case 0:
+        case 1:
+            return getPreNTLMResponse( password, challenge );
+        case 2:
+            return getNTLMResponse( password, challenge );
+        case 3:
+        case 4:
+        case 5:
+            if( clientChallenge == null ) {
+                clientChallenge = new byte[8];
+                RANDOM.nextBytes( clientChallenge );
+            }
+            return getLMv2Response(domain, username, password, challenge,
+                    clientChallenge);
+        default:
+            return getPreNTLMResponse( password, challenge );
+        }
+    }
 /**
  * Computes the 24 byte Unicode password hash given the 8 byte server challenge.
  */
-       public byte[] getUnicodeHash( byte[] challenge ) {
-               if( hashesExternal ) {
-                       return unicodeHash;
-               }
-               switch (LM_COMPATIBILITY) {
-               case 0:
-               case 1:
-               case 2:
-                       return getNTLMResponse( password, challenge );
-               case 3:
-               case 4:
-               case 5:
-                       /*
-                       if( clientChallenge == null ) {
-                               clientChallenge = new byte[8];
-                               RANDOM.nextBytes( clientChallenge );
-                       }
-                       return getNTLMv2Response(domain, username, password, null,
-                                       challenge, clientChallenge);
-                       */
-                       return new byte[0];
-               default:
-                       return getNTLMResponse( password, challenge );
-               }
-       }
+    public byte[] getUnicodeHash( byte[] challenge ) {
+        if( hashesExternal ) {
+            return unicodeHash;
+        }
+        switch (LM_COMPATIBILITY) {
+        case 0:
+        case 1:
+        case 2:
+            return getNTLMResponse( password, challenge );
+        case 3:
+        case 4:
+        case 5:
+            /*
+            if( clientChallenge == null ) {
+                clientChallenge = new byte[8];
+                RANDOM.nextBytes( clientChallenge );
+            }
+            return getNTLMv2Response(domain, username, password, null,
+                    challenge, clientChallenge);
+            */
+            return new byte[0];
+        default:
+            return getNTLMResponse( password, challenge );
+        }
+    }
 
     /**
      * Returns the effective user session key.
@@ -327,7 +333,8 @@ public final class NtlmPasswordAuthentication implements Principal, Serializable
         try {
             getUserSessionKey(challenge, key, 0); 
         } catch (Exception ex) {
-            Log.printStackTrace("Unable to calculate user session key.", ex);
+            if( log.level > 0 )
+                ex.printStackTrace( log );
         }
         return key; 
     }
@@ -356,10 +363,10 @@ public final class NtlmPasswordAuthentication implements Principal, Serializable
         case 3:
         case 4:
         case 5:
-                       if( clientChallenge == null ) {
-                               clientChallenge = new byte[8];
-                               RANDOM.nextBytes( clientChallenge );
-                       }
+            if( clientChallenge == null ) {
+                clientChallenge = new byte[8];
+                RANDOM.nextBytes( clientChallenge );
+            }
 
             HMACT64 hmac = new HMACT64(md4.digest());
             hmac.update(username.toUpperCase().getBytes(
@@ -386,39 +393,39 @@ public final class NtlmPasswordAuthentication implements Principal, Serializable
  * equality. Two <tt>NtlmPasswordAuthentication</tt> objects are equal if
  * their caseless domain and username fields are equal and either both hashes are external and they are equal or both internally supplied passwords are equal. If one <tt>NtlmPasswordAuthentication</tt> object has external hashes (meaning negotiated via NTLM HTTP Authentication) and the other does not they will not be equal. This is technically not correct however the server 8 byte challage would be required to compute and compare the password hashes but that it not available with this method.
  */
-       public boolean equals( Object obj ) {
-               if( obj instanceof NtlmPasswordAuthentication ) {
-                       NtlmPasswordAuthentication ntlm = (NtlmPasswordAuthentication)obj;
-                       if( ntlm.domain.toUpperCase().equals( domain.toUpperCase() ) &&
-                                               ntlm.username.toUpperCase().equals( username.toUpperCase() )) {
-                               if( hashesExternal && ntlm.hashesExternal ) {
-                                       return Arrays.equals( ansiHash, ntlm.ansiHash ) &&
-                                                               Arrays.equals( unicodeHash, ntlm.unicodeHash );
-                                       /* This still isn't quite right. If one npa object does not have external
-                                        * hashes and the other does then they will not be considered equal even
-                                        * though they may be.
-                                        */
-                               } else if( !hashesExternal && password.equals( ntlm.password )) {
-                                       return true;
-                               }
-                       }
-               }
-               return false;
-       }
+    public boolean equals( Object obj ) {
+        if( obj instanceof NtlmPasswordAuthentication ) {
+            NtlmPasswordAuthentication ntlm = (NtlmPasswordAuthentication)obj;
+            if( ntlm.domain.toUpperCase().equals( domain.toUpperCase() ) &&
+                        ntlm.username.toUpperCase().equals( username.toUpperCase() )) {
+                if( hashesExternal && ntlm.hashesExternal ) {
+                    return Arrays.equals( ansiHash, ntlm.ansiHash ) &&
+                                Arrays.equals( unicodeHash, ntlm.unicodeHash );
+                    /* This still isn't quite right. If one npa object does not have external
+                     * hashes and the other does then they will not be considered equal even
+                     * though they may be.
+                     */
+                } else if( !hashesExternal && password.equals( ntlm.password )) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
 
 
 /**
  * Return the upcased username hash code.
  */
-       public int hashCode() {
-               return getName().toUpperCase().hashCode();
-       }
+    public int hashCode() {
+        return getName().toUpperCase().hashCode();
+    }
 /**
  * Return the domain and username in the format:
  * <tt>domain\\username</tt>. This is equivalent to <tt>getName()</tt>.
  */
-       public String toString() {
-               return getName();
-       }
+    public String toString() {
+        return getName();
+    }
 }
 
index 77d717e..833c8df 100644 (file)
@@ -26,598 +26,608 @@ import java.io.UnsupportedEncodingException;
 import java.util.TimeZone;
 import java.util.Calendar;
 import java.util.Date;
+import jcifs.util.Hexdump;
+import jcifs.util.LogStream;
 
 abstract class ServerMessageBlock {
 
-       static final int FLAGS_NONE                           = 0x00;
-       static final int FLAGS_LOCK_AND_READ_WRITE_AND_UNLOCK = 0x01;
-       static final int FLAGS_RECEIVE_BUFFER_POSTED          = 0x02;
-       static final int FLAGS_PATH_NAMES_CASELESS            = 0x08;
-       static final int FLAGS_PATH_NAMES_CANONICALIZED       = 0x10;
-       static final int FLAGS_OPLOCK_REQUESTED_OR_GRANTED    = 0x20;
-       static final int FLAGS_NOTIFY_OF_MODIFY_ACTION        = 0x40;
-       static final int FLAGS_RESPONSE                       = 0x80;
-
-       static final int FLAGS2_NONE                          = 0x0000;
-       static final int FLAGS2_LONG_FILENAMES                = 0x0001;
-       static final int FLAGS2_EXTENDED_ATTRIBUTES           = 0x0002;
-       static final int FLAGS2_SECURITY_SIGNATURES           = 0x0004;
-       static final int FLAGS2_EXTENDED_SECURITY_NEGOTIATION = 0x0800;
-       static final int FLAGS2_RESOLVE_PATHS_IN_DFS          = 0x1000;
-       static final int FLAGS2_PERMIT_READ_IF_EXECUTE_PERM   = 0x2000;
-       static final int FLAGS2_STATUS32                      = 0x4000;
-       static final int FLAGS2_UNICODE                       = 0x8000;
-
-       static final int CAP_NONE             = 0x0000;
-       static final int CAP_RAW_MODE         = 0x0001;
-       static final int CAP_MPX_MODE         = 0x0002;
-       static final int CAP_UNICODE          = 0x0004;
-       static final int CAP_LARGE_FILES      = 0x0008;
-       static final int CAP_NT_SMBS          = 0x0010;
-       static final int CAP_RPC_REMOTE_APIS  = 0x0020;
-       static final int CAP_STATUS32         = 0x0040;
-       static final int CAP_LEVEL_II_OPLOCKS = 0x0080;
-       static final int CAP_LOCK_AND_READ    = 0x0100;
-       static final int CAP_NT_FIND          = 0x0200;
-       static final int CAP_DFS              = 0x1000;
-
-       // file attribute encoding
-       static final int ATTR_READONLY   = 0x01;
-       static final int ATTR_HIDDEN     = 0x02;
-       static final int ATTR_SYSTEM     = 0x04;
-       static final int ATTR_VOLUME     = 0x08;
-       static final int ATTR_DIRECTORY  = 0x10;
-       static final int ATTR_ARCHIVE    = 0x20;
-
-       // extended file attribute encoding(others same as above)
-       static final int ATTR_COMPRESSED = 0x800;
-       static final int ATTR_NORMAL     = 0x080;
-       static final int ATTR_TEMPORARY  = 0x100;
-
-       // flags for move and copy
-       static final int FLAGS_TARGET_MUST_BE_FILE         = 0x0001; 
-       static final int FLAGS_TARGET_MUST_BE_DIRECTORY    = 0x0002; 
-       static final int FLAGS_COPY_TARGET_MODE_ASCII      = 0x0004; 
-       static final int FLAGS_COPY_SOURCE_MODE_ASCII      = 0x0008;
-       static final int FLAGS_VERIFY_ALL_WRITES           = 0x0010; 
-       static final int FLAGS_TREE_COPY                   = 0x0020; 
-
-       // open function
-       static final int OPEN_FUNCTION_FAIL_IF_EXISTS      = 0x0000;
-       static final int OPEN_FUNCTION_OVERWRITE_IF_EXISTS = 0x0020;
-
-       static final int PID = (int)( Math.random() * 65536d );
-
-       static final int SECURITY_SHARE = 0x00;
-       static final int SECURITY_USER  = 0x01;
-
-       static final int CMD_OFFSET        = 4;
-       static final int ERROR_CODE_OFFSET = 5;
-       static final int FLAGS_OFFSET      = 9;
-       static final int SIGNATURE_OFFSET  = 14;
-       static final int TID_OFFSET        = 24;
-       static final int HEADER_LENGTH     = 32;
-
-       static final long MILLISECONDS_BETWEEN_1970_AND_1601 = 11644473600000L;
-       static final TimeZone TZ = TimeZone.getDefault();
-
-       static boolean useBatching = Config.getBoolean( "jcifs.smb.client.useBatching", true );
-       static String encoding = Config.getProperty( "jcifs.smb.client.codepage",
-                                                       Config.getProperty( "jcifs.encoding",
-                                                       System.getProperty( "file.encoding" )));
-
-       static final byte[] header = {
-               (byte)0xFF, (byte)'S', (byte)'M', (byte)'B',
-               (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
-               (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
-               (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
-               (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
-               (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00
-       };
-
-
-       static void writeInt2( long val, byte[] dst, int dstIndex ) {
-               dst[dstIndex] = (byte)(val);
-               dst[++dstIndex] = (byte)(val >> 8);
-       }
-       static void writeInt4( long val, byte[] dst, int dstIndex ) {
-               dst[dstIndex] = (byte)(val);
-               dst[++dstIndex] = (byte)(val >>= 8);
-               dst[++dstIndex] = (byte)(val >>= 8);
-               dst[++dstIndex] = (byte)(val >> 8);
-       }
-       static int readInt2( byte[] src, int srcIndex ) {
-               return ( src[srcIndex] & 0xFF ) +
-                               (( src[srcIndex + 1] & 0xFF ) << 8 );
-       }
-       static int readInt4( byte[] src, int srcIndex ) {
-               return ( src[srcIndex] & 0xFF ) +
-                               (( src[srcIndex + 1] & 0xFF ) << 8 ) +
-                               (( src[srcIndex + 2] & 0xFF ) << 16 ) +
-                               (( src[srcIndex + 3] & 0xFF ) << 24 );
-       }
-       static long readLong( byte[] src, int srcIndex ) {
-               return (readInt4( src, srcIndex ) & 0xFFFFFFFFL) +
-                       ((long)(readInt4( src, srcIndex + 4 )) << 32);
-       }
-       static void writeInt8( long val, byte[] dst, int dstIndex ) {
-               dst[dstIndex] = (byte)(val);
-               dst[++dstIndex] = (byte)(val >>= 8);
-               dst[++dstIndex] = (byte)(val >>= 8);
-               dst[++dstIndex] = (byte)(val >>= 8);
-               dst[++dstIndex] = (byte)(val >>= 8);
-               dst[++dstIndex] = (byte)(val >>= 8);
-               dst[++dstIndex] = (byte)(val >>= 8);
-               dst[++dstIndex] = (byte)(val >> 8);
-       }
-       static long readTime( byte[] src, int srcIndex ) {
-               int low = readInt4( src, srcIndex );
-               int hi = readInt4( src, srcIndex + 4 );
-               long t = ((long)hi << 32L ) | (low & 0xFFFFFFFFL);
-               t = ( t / 10000L - MILLISECONDS_BETWEEN_1970_AND_1601 );
+    static final int FLAGS_NONE                           = 0x00;
+    static final int FLAGS_LOCK_AND_READ_WRITE_AND_UNLOCK = 0x01;
+    static final int FLAGS_RECEIVE_BUFFER_POSTED          = 0x02;
+    static final int FLAGS_PATH_NAMES_CASELESS            = 0x08;
+    static final int FLAGS_PATH_NAMES_CANONICALIZED       = 0x10;
+    static final int FLAGS_OPLOCK_REQUESTED_OR_GRANTED    = 0x20;
+    static final int FLAGS_NOTIFY_OF_MODIFY_ACTION        = 0x40;
+    static final int FLAGS_RESPONSE                       = 0x80;
+
+    static final int FLAGS2_NONE                          = 0x0000;
+    static final int FLAGS2_LONG_FILENAMES                = 0x0001;
+    static final int FLAGS2_EXTENDED_ATTRIBUTES           = 0x0002;
+    static final int FLAGS2_SECURITY_SIGNATURES           = 0x0004;
+    static final int FLAGS2_EXTENDED_SECURITY_NEGOTIATION = 0x0800;
+    static final int FLAGS2_RESOLVE_PATHS_IN_DFS          = 0x1000;
+    static final int FLAGS2_PERMIT_READ_IF_EXECUTE_PERM   = 0x2000;
+    static final int FLAGS2_STATUS32                      = 0x4000;
+    static final int FLAGS2_UNICODE                       = 0x8000;
+
+    static final int CAP_NONE             = 0x0000;
+    static final int CAP_RAW_MODE         = 0x0001;
+    static final int CAP_MPX_MODE         = 0x0002;
+    static final int CAP_UNICODE          = 0x0004;
+    static final int CAP_LARGE_FILES      = 0x0008;
+    static final int CAP_NT_SMBS          = 0x0010;
+    static final int CAP_RPC_REMOTE_APIS  = 0x0020;
+    static final int CAP_STATUS32         = 0x0040;
+    static final int CAP_LEVEL_II_OPLOCKS = 0x0080;
+    static final int CAP_LOCK_AND_READ    = 0x0100;
+    static final int CAP_NT_FIND          = 0x0200;
+    static final int CAP_DFS              = 0x1000;
+
+    // file attribute encoding
+    static final int ATTR_READONLY   = 0x01;
+    static final int ATTR_HIDDEN     = 0x02;
+    static final int ATTR_SYSTEM     = 0x04;
+    static final int ATTR_VOLUME     = 0x08;
+    static final int ATTR_DIRECTORY  = 0x10;
+    static final int ATTR_ARCHIVE    = 0x20;
+
+    // extended file attribute encoding(others same as above)
+    static final int ATTR_COMPRESSED = 0x800;
+    static final int ATTR_NORMAL     = 0x080;
+    static final int ATTR_TEMPORARY  = 0x100;
+
+    // flags for move and copy
+    static final int FLAGS_TARGET_MUST_BE_FILE         = 0x0001; 
+    static final int FLAGS_TARGET_MUST_BE_DIRECTORY    = 0x0002; 
+    static final int FLAGS_COPY_TARGET_MODE_ASCII      = 0x0004; 
+    static final int FLAGS_COPY_SOURCE_MODE_ASCII      = 0x0008;
+    static final int FLAGS_VERIFY_ALL_WRITES           = 0x0010; 
+    static final int FLAGS_TREE_COPY                   = 0x0020; 
+
+    // open function
+    static final int OPEN_FUNCTION_FAIL_IF_EXISTS      = 0x0000;
+    static final int OPEN_FUNCTION_OVERWRITE_IF_EXISTS = 0x0020;
+
+    static final int PID = (int)( Math.random() * 65536d );
+
+    static final int SECURITY_SHARE = 0x00;
+    static final int SECURITY_USER  = 0x01;
+
+    static final int CMD_OFFSET        = 4;
+    static final int ERROR_CODE_OFFSET = 5;
+    static final int FLAGS_OFFSET      = 9;
+    static final int SIGNATURE_OFFSET  = 14;
+    static final int TID_OFFSET        = 24;
+    static final int HEADER_LENGTH     = 32;
+
+    static final long MILLISECONDS_BETWEEN_1970_AND_1601 = 11644473600000L;
+    static final TimeZone TZ = TimeZone.getDefault();
+
+    static final boolean USE_BATCHING = Config.getBoolean( "jcifs.smb.client.useBatching", true );
+    static final String OEM_ENCODING =
+            Config.getProperty( "jcifs.smb.client.codepage",
+                    Config.getProperty( "jcifs.encoding",
+                            System.getProperty( "file.encoding" )));
+
+    static LogStream log = LogStream.getInstance();
+
+    static final byte[] header = {
+        (byte)0xFF, (byte)'S', (byte)'M', (byte)'B',
+        (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
+        (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
+        (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
+        (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
+        (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00
+    };
+
+    static void writeInt2( long val, byte[] dst, int dstIndex ) {
+        dst[dstIndex] = (byte)(val);
+        dst[++dstIndex] = (byte)(val >> 8);
+    }
+    static void writeInt4( long val, byte[] dst, int dstIndex ) {
+        dst[dstIndex] = (byte)(val);
+        dst[++dstIndex] = (byte)(val >>= 8);
+        dst[++dstIndex] = (byte)(val >>= 8);
+        dst[++dstIndex] = (byte)(val >> 8);
+    }
+    static int readInt2( byte[] src, int srcIndex ) {
+        return ( src[srcIndex] & 0xFF ) +
+                (( src[srcIndex + 1] & 0xFF ) << 8 );
+    }
+    static int readInt4( byte[] src, int srcIndex ) {
+        return ( src[srcIndex] & 0xFF ) +
+                (( src[srcIndex + 1] & 0xFF ) << 8 ) +
+                (( src[srcIndex + 2] & 0xFF ) << 16 ) +
+                (( src[srcIndex + 3] & 0xFF ) << 24 );
+    }
+    static long readInt8( byte[] src, int srcIndex ) {
+        return (readInt4( src, srcIndex ) & 0xFFFFFFFFL) +
+            ((long)(readInt4( src, srcIndex + 4 )) << 32);
+    }
+    static void writeInt8( long val, byte[] dst, int dstIndex ) {
+        dst[dstIndex] = (byte)(val);
+        dst[++dstIndex] = (byte)(val >>= 8);
+        dst[++dstIndex] = (byte)(val >>= 8);
+        dst[++dstIndex] = (byte)(val >>= 8);
+        dst[++dstIndex] = (byte)(val >>= 8);
+        dst[++dstIndex] = (byte)(val >>= 8);
+        dst[++dstIndex] = (byte)(val >>= 8);
+        dst[++dstIndex] = (byte)(val >> 8);
+    }
+    static long readTime( byte[] src, int srcIndex ) {
+        int low = readInt4( src, srcIndex );
+        int hi = readInt4( src, srcIndex + 4 );
+        long t = ((long)hi << 32L ) | (low & 0xFFFFFFFFL);
+        t = ( t / 10000L - MILLISECONDS_BETWEEN_1970_AND_1601 );
 
 /*
-               synchronized( TZ ) {
-                       if( TZ.inDaylightTime( new Date() )) {
-                               // in DST
-                               if( TZ.inDaylightTime( new Date( t ))) {
-                                       // t also in DST so no correction
-                                       return t;
-                               }
-                               // t not in DST so add 1 hour
-                               return t + 3600000;
-                       } else {
-                               // not in DST
-                               if( TZ.inDaylightTime( new Date( t ))) {
-                                       // t is in DST so subtract 1 hour
-                                       return t - 3600000;
-                               }
-                               // t isn't in DST either
-                               return t;
-                       }
-               }
+        synchronized( TZ ) {
+            if( TZ.inDaylightTime( new Date() )) {
+                // in DST
+                if( TZ.inDaylightTime( new Date( t ))) {
+                    // t also in DST so no correction
+                    return t;
+                }
+                // t not in DST so add 1 hour
+                return t + 3600000;
+            } else {
+                // not in DST
+                if( TZ.inDaylightTime( new Date( t ))) {
+                    // t is in DST so subtract 1 hour
+                    return t - 3600000;
+                }
+                // t isn't in DST either
+                return t;
+            }
+        }
 */
-               return t;
-       }
-       static void writeTime( long t, byte[] dst, int dstIndex ) {
+        return t;
+    }
+    static void writeTime( long t, byte[] dst, int dstIndex ) {
 
-               if( t != 0L ) {
+        if( t != 0L ) {
 /*
-                       synchronized( TZ ) {
-                               if( TZ.inDaylightTime( new Date() )) {
-                                       // in DST
-                                       if( TZ.inDaylightTime( new Date( t ))) {
-                                               // t also in DST so no correction
-                                       } else {
-                                               // t not in DST so subtract 1 hour
-                                               t -= 3600000;
-                                       }
-                               } else {
-                                       // not in DST
-                                       if( TZ.inDaylightTime( new Date( t ))) {
-                                               // t is in DST so add 1 hour
-                                               t += 3600000;
-                                       } else {
-                                               // t isn't in DST either
-                                       }
-                               }
-                       }
+            synchronized( TZ ) {
+                if( TZ.inDaylightTime( new Date() )) {
+                    // in DST
+                    if( TZ.inDaylightTime( new Date( t ))) {
+                        // t also in DST so no correction
+                    } else {
+                        // t not in DST so subtract 1 hour
+                        t -= 3600000;
+                    }
+                } else {
+                    // not in DST
+                    if( TZ.inDaylightTime( new Date( t ))) {
+                        // t is in DST so add 1 hour
+                        t += 3600000;
+                    } else {
+                        // t isn't in DST either
+                    }
+                }
+            }
 */
-                       t = (t + MILLISECONDS_BETWEEN_1970_AND_1601) * 10000L;
-               }
-
-               writeInt8( t, dst, dstIndex );
-       }
-       static long readUTime( byte[] buffer, int bufferIndex ) {
-               return readInt4( buffer, bufferIndex ) * 1000L;
-       }
-       static void writeUTime( long t, byte[] dst, int dstIndex ) {
-               if( t == 0L || t == 0xFFFFFFFFFFFFFFFFL ) {
-                       writeInt4( 0xFFFFFFFF, dst, dstIndex );
-                       return;
-               }
-               synchronized( TZ ) {
-                       if( TZ.inDaylightTime( new Date() )) {
-                               // in DST
-                               if( TZ.inDaylightTime( new Date( t ))) {
-                                       // t also in DST so no correction
-                               } else {
-                                       // t not in DST so subtract 1 hour
-                                       t -= 3600000;
-                               }
-                       } else {
-                               // not in DST
-                               if( TZ.inDaylightTime( new Date( t ))) {
-                                       // t is in DST so add 1 hour
-                                       t += 3600000;
-                               } else {
-                                       // t isn't in DST either
-                               }
-                       }
-               }
-               writeInt4( (int)(t / 1000L), dst, dstIndex );
-       }
-
-
-       /*
-        * These are all the smbs supported by this library. This includes requests
-        * and well as their responses for each type however the actuall implementations
-        * of the readXxxWireFormat and writeXxxWireFormat methods may not be in
-        * place. For example at the time of this writing the readXxxWireFormat
-        * for requests and the writeXxxWireFormat for responses are not implemented
-        * and simply return 0. These would need to be completed for a server
-        * implementation.
-        */
-
-       static final byte SMB_COM_CREATE_DIRECTORY   = (byte)0x00;
-       static final byte SMB_COM_DELETE_DIRECTORY   = (byte)0x01;
-       static final byte SMB_COM_CLOSE              = (byte)0x04;
-       static final byte SMB_COM_DELETE             = (byte)0x06;
-       static final byte SMB_COM_RENAME             = (byte)0x07;
-       static final byte SMB_COM_QUERY_INFORMATION  = (byte)0x08;
-       static final byte SMB_COM_WRITE              = (byte)0x0B;
-       static final byte SMB_COM_CHECK_DIRECTORY    = (byte)0x10;
-       static final byte SMB_COM_TRANSACTION        = (byte)0x25;
-       static final byte SMB_COM_TRANSACTION_SECONDARY = (byte)0x26;
-       static final byte SMB_COM_MOVE               = (byte)0x2A;
-       static final byte SMB_COM_ECHO               = (byte)0x2B;
-       static final byte SMB_COM_OPEN_ANDX          = (byte)0x2D;
-       static final byte SMB_COM_READ_ANDX          = (byte)0x2E;
-       static final byte SMB_COM_WRITE_ANDX         = (byte)0x2F;
-       static final byte SMB_COM_TRANSACTION2       = (byte)0x32;
-       static final byte SMB_COM_FIND_CLOSE2        = (byte)0x34;
-       static final byte SMB_COM_TREE_DISCONNECT    = (byte)0x71;
-       static final byte SMB_COM_NEGOTIATE          = (byte)0x72;
-       static final byte SMB_COM_SESSION_SETUP_ANDX = (byte)0x73;
-       static final byte SMB_COM_LOGOFF_ANDX        = (byte)0x74;
-       static final byte SMB_COM_TREE_CONNECT_ANDX  = (byte)0x75;
-       static final byte SMB_COM_NT_CREATE_ANDX     = (byte)0xA2;
-
-       /*
-        * Some fields specify the offset from the beginning of the header. This
-        * field should be used for calculating that. This would likely be zero
-        * but an implemantation that encorporates the transport header(for
-        * efficiency) might use a different initial bufferIndex. For example,
-        * to eliminate copying data when writing NbtSession data one might
-        * manage that 4 byte header specifically and therefore the initial
-        * bufferIndex, and thus headerStart, would be 4).(NOTE: If one where
-        * looking for a way to improve perfomance this is precisly what you
-        * would want to do as the jcifs.netbios.SocketXxxputStream classes
-        * arraycopy all data read or written into a new buffer shifted over 4!)
-        */
-
-       byte command, flags;
-       int headerStart,
-               length,
-               batchLevel,
-               errorCode,
-               flags2,
-               tid, pid, uid, mid,
-               wordCount, byteCount;
-       boolean useUnicode, received;
-       long responseTimeout = 1;
-       int verifySequence;
-       boolean verifyFailed;
-       NtlmPasswordAuthentication auth = null;
-       String path;
-
-       ServerMessageBlock() {
-               flags = (byte)( FLAGS_PATH_NAMES_CASELESS | FLAGS_PATH_NAMES_CANONICALIZED );
-               pid = PID;
-               batchLevel = 0;
-       }
-
-       int writeString( String str, byte[] dst, int dstIndex ) {
-               return writeString( str, dst, dstIndex, useUnicode );
-       }
-       int writeString( String str, byte[] dst, int dstIndex, boolean useUnicode ) {
-               int start = dstIndex;
-
-               try {
-                       if( useUnicode ) {
-                               // Unicode requires word alignment
-                               if((( dstIndex - headerStart ) % 2 ) != 0 ) {
-                                       dst[dstIndex++] = (byte)'\0';
-                               }
-                               System.arraycopy( str.getBytes( "UnicodeLittleUnmarked" ), 0,
-                                                                       dst, dstIndex, str.length() * 2 );
-                               dstIndex += str.length() * 2;
-                               dst[dstIndex++] = (byte)'\0';
-                               dst[dstIndex++] = (byte)'\0';
-                       } else {
-                               byte[] b = str.getBytes( encoding );
-                               System.arraycopy( b, 0, dst, dstIndex, b.length );
-                               dstIndex += b.length;
-                               dst[dstIndex++] = (byte)'\0';
-                       }
-               } catch( UnsupportedEncodingException uee ) {
-                       Log.printStackTrace( "smb exception", uee );
-               }
-
-               return dstIndex - start;
-       }
-       String readString( byte[] src, int srcIndex ) {
-               return readString( src, srcIndex, 256, useUnicode );
-       }
-       String readString( byte[] src, int srcIndex, int maxLen, boolean useUnicode ) {
-               int len = 0;
-               String str = null;
-               try {
-                       if( useUnicode ) {
-                               // Unicode requires word alignment
-                               if((( srcIndex - headerStart ) % 2 ) != 0 ) {
-                                       srcIndex++;
-                               }
-                               while( src[srcIndex + len] != (byte)0x00 ||
-                                                                                       src[srcIndex + len + 1] != (byte)0x00 ) {
-                                       len += 2;
-                                       if( len > maxLen ) {
-jcifs.util.Log.printHexDump( System.err, src, 0, 256 );
-                                               throw new RuntimeException( "zero termination not found" );
-                                       }
-                               }
-                               str = new String( src, srcIndex, len, "UnicodeLittle" );
-                       } else {
-                               while( src[srcIndex + len] != (byte)0x00 ) {
-                                       len++;
-                                       if( len > maxLen ) {
-                                               throw new RuntimeException( "zero termination not found" );
-                                       }
-                               }
-                               str = new String( src, srcIndex, len, encoding );
-                       }
-               } catch( UnsupportedEncodingException uee ) {
-                       Log.printStackTrace( "smb exception", uee );
-               }
-               return str;
-       }
-       int stringWireLength( String str, int offset ) {
-               int len = str.length() + 1;
-               if( useUnicode ) {
-                       len = str.length() * 2 + 2;
-                       len = ( offset % 2 ) != 0 ? len + 1 : len;
-               }
-               return len;
-       }
-       int readStringLength( byte[] src, int srcIndex, int max ) {
-               int len = 0;
-               while( src[srcIndex + len] != (byte)0x00 ) {
-                       if( len++ > max ) {
-                               throw new RuntimeException( "zero termination not found: " + this );
-                       }
-               }
-               return len;
-       }
-       int writeWireFormat( byte[] dst, int dstIndex ) {
-               int start = headerStart = dstIndex;
-
-               dstIndex += writeHeaderWireFormat( dst, dstIndex );
-               wordCount = writeParameterWordsWireFormat( dst, dstIndex + 1 );
-               dst[dstIndex++] = (byte)(( wordCount / 2 ) & 0xFF );
-               dstIndex += wordCount;
-               wordCount /= 2;
-               byteCount = writeBytesWireFormat( dst, dstIndex + 2 );
-               dst[dstIndex++] = (byte)( byteCount & 0xFF );
-               dst[dstIndex++] = (byte)(( byteCount >> 8 ) & 0xFF );
-               dstIndex += byteCount;
-
-               length = dstIndex - start;
-               return length;
-       }
-       int readWireFormat( InputStream in,
-                                                       byte[] buffer,
-                                                       int bufferIndex )
-                                                       throws IOException {
-
-               int start = headerStart = bufferIndex;
-
-               /*
-                * read header
-                */
-
-               if( in.read( buffer, bufferIndex, HEADER_LENGTH ) != HEADER_LENGTH ) {
-                       throw new IOException( "unexpected EOF reading smb header" );
-               }
-               bufferIndex += readHeaderWireFormat( buffer, bufferIndex );
-
-               /*
-                * read wordCount
-                */
-
-               if(( wordCount = in.read() ) == -1 ) {
-                       throw new IOException( "unexpected EOF reading smb wordCount" );
-               }
-               buffer[bufferIndex++] = (byte)( wordCount & 0xFF );
-
-               /*
-                * read parameter words
-                */
-
-               if( wordCount != 0 ) {
-                       if( in.read( buffer, bufferIndex, wordCount * 2 ) != wordCount * 2 ) {
-                               throw new IOException( "unexpected EOF reading smb parameter words" );
-                       }
-                       int n;
-                       if(( n = readParameterWordsWireFormat( buffer, bufferIndex )) != wordCount * 2 ) {
-                               Log.println( Log.WARNINGS, "smb packet format warning", "wordCount * 2=" +
-                                                               ( wordCount * 2 ) +
-                                                               " but readParameterWordsWireFormat returned " + n );
-                       }
-                       bufferIndex += wordCount * 2;
-               }
-
-               /*
-                * read byteCount
-                */
-
-               if( in.read( buffer, bufferIndex, 2 ) != 2 ) {
-                       throw new IOException( "unexpected EOF reading smb byteCount" );
-               }
-               byteCount = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-
-               /*
-                * read bytes
-                */
-
-               if( byteCount != 0 ) {
-                       if( in.read( buffer, bufferIndex, byteCount ) != byteCount ) {
-                               throw new IOException( "unexpected EOF reading smb" );
-                       }
-                       int n;
-                       if(( n = readBytesWireFormat( buffer, bufferIndex )) != byteCount ) {
-                               Log.println( Log.WARNINGS, "smb packet format warning", "byteCount=" +
-                                                               byteCount + " but readBytesWireFormat returned " + n );
-                       }
-                       // Don't think we can rely on n being correct here. Must use byteCount.
-                       // Last paragraph of section 3.13.3 eludes to this.
-
-                       bufferIndex += byteCount;
-               }
-
-               length = bufferIndex - start;
-               return length;
-       }
-       int writeHeaderWireFormat( byte[] dst, int dstIndex ) {
-               System.arraycopy( header, 0, dst, dstIndex, header.length );
-               dst[dstIndex + CMD_OFFSET] = command;
-               dst[dstIndex + FLAGS_OFFSET] = flags;
-               writeInt2( flags2, dst, dstIndex + FLAGS_OFFSET + 1 );
-               dstIndex += TID_OFFSET;
-               writeInt2( tid, dst, dstIndex );
-               writeInt2( pid, dst, dstIndex + 2 );
-               writeInt2( uid, dst, dstIndex + 4 );
-               writeInt2( mid, dst, dstIndex + 6 );
-               return HEADER_LENGTH;
-       }
-       int readHeaderWireFormat( byte[] buffer, int bufferIndex ) throws IOException {
-               command = buffer[bufferIndex + CMD_OFFSET];
-               errorCode = readInt4( buffer, bufferIndex + ERROR_CODE_OFFSET );
-               flags = buffer[bufferIndex + FLAGS_OFFSET];
-               flags2 = readInt2( buffer, bufferIndex + FLAGS_OFFSET + 1 );
-               tid = readInt2( buffer, bufferIndex + TID_OFFSET );
-               pid = readInt2( buffer, bufferIndex + TID_OFFSET + 2 );
-               uid = readInt2( buffer, bufferIndex + TID_OFFSET + 4 );
-               mid = readInt2( buffer, bufferIndex + TID_OFFSET + 6 );
-               return HEADER_LENGTH;
-       }
-       boolean isResponse() {
-               return ( flags & FLAGS_RESPONSE ) == FLAGS_RESPONSE;
-       }
-
-       /* 
-        * For this packet deconstruction technique to work for
-        * other networking protocols the InputStream may need
-        * to be passed to the readXxxWireFormat methods. This is
-        * actually purer. However, in the case of smb we know the
-        * wordCount and byteCount. And since every subclass of
-        * ServerMessageBlock would have to perform the same read
-        * operation on the input stream, we might as will pull that
-        * common functionality into the superclass and read wordCount
-        * and byteCount worth of data.
-        * 
-        * We will still use the readXxxWireFormat return values to
-        * indicate how many bytes(note: readParameterWordsWireFormat
-        * returns bytes read and not the number of words(but the
-        * wordCount member DOES store the number of words)) we
-        * actually read. Incedentally this is important to the
-        * AndXServerMessageBlock class that needs to potentially
-        * read in another smb's parameter words and bytes based on
-        * information in it's andxCommand, andxOffset, ...etc.
-        */ 
-
-       abstract int writeParameterWordsWireFormat( byte[] dst, int dstIndex );
-       abstract int writeBytesWireFormat( byte[] dst, int dstIndex );
-       abstract int readParameterWordsWireFormat( byte[] buffer,
-                                                                               int bufferIndex )
-                                                                               throws IOException;
-       abstract int readBytesWireFormat( byte[] buffer,
-                                                                               int bufferIndex )
-                                                                               throws IOException;
-
-       public String toString() {
-               String c;
-               switch( command ) {
-                       case SMB_COM_NEGOTIATE:
-                               c = "SMB_COM_NEGOTIATE";
-                               break;
-                       case SMB_COM_SESSION_SETUP_ANDX:
-                               c = "SMB_COM_SESSION_SETUP_ANDX";
-                               break;
-                       case SMB_COM_TREE_CONNECT_ANDX:
-                               c = "SMB_COM_TREE_CONNECT_ANDX";
-                               break;
-                       case SMB_COM_QUERY_INFORMATION:
-                               c = "SMB_COM_QUERY_INFORMATION";
-                               break;
-                       case SMB_COM_CHECK_DIRECTORY:
-                               c = "SMB_COM_CHECK_DIRECTORY";
-                               break;
-                       case SMB_COM_TRANSACTION:
-                               c = "SMB_COM_TRANSACTION";
-                               break;
-                       case SMB_COM_TRANSACTION2:
-                               c = "SMB_COM_TRANSACTION2";
-                               break;
-                       case SMB_COM_TRANSACTION_SECONDARY:
-                               c = "SMB_COM_TRANSACTION_SECONDARY";
-                               break;
-                       case SMB_COM_FIND_CLOSE2:
-                               c = "SMB_COM_FIND_CLOSE2";
-                               break;
-                       case SMB_COM_TREE_DISCONNECT:
-                               c = "SMB_COM_TREE_DISCONNECT";
-                               break;
-                       case SMB_COM_LOGOFF_ANDX:
-                               c = "SMB_COM_LOGOFF_ANDX";
-                               break;
-                       case SMB_COM_ECHO:
-                               c = "SMB_COM_ECHO";
-                               break;
-                       case SMB_COM_MOVE:
-                               c = "SMB_COM_MOVE";
-                               break;
-                       case SMB_COM_RENAME:
-                               c = "SMB_COM_RENAME";
-                               break;
-                       case SMB_COM_DELETE:
-                               c = "SMB_COM_DELETE";
-                               break;
-                       case SMB_COM_DELETE_DIRECTORY:
-                               c = "SMB_COM_DELETE_DIRECTORY";
-                               break;
-                       case SMB_COM_NT_CREATE_ANDX:
-                               c = "SMB_COM_NT_CREATE_ANDX";
-                               break;
-                       case SMB_COM_OPEN_ANDX:
-                               c = "SMB_COM_OPEN_ANDX";
-                               break;
-                       case SMB_COM_READ_ANDX:
-                               c = "SMB_COM_READ_ANDX";
-                               break;
-                       case SMB_COM_CLOSE:
-                               c = "SMB_COM_CLOSE";
-                               break;
-                       case SMB_COM_WRITE_ANDX:
-                               c = "SMB_COM_WRITE_ANDX";
-                               break;
-                       case SMB_COM_CREATE_DIRECTORY:
-                               c = "SMB_COM_CREATE_DIRECTORY";
-                               break;
-                       default:
-                               c = "UNKNOWN";
-               }
-               return new String(
-                       "command="      + c +
-                       ",received="    + received +
-                       ",errorCode=" + SmbException.getErrorString( errorCode ) +
-                       ",flags=0x"     + Log.getHexString( flags & 0xFF, 4 ) +
-                       ",flags2=0x"    + Log.getHexString( flags2, 4 ) +
-                       ",tid="         + tid +
-                       ",pid="         + pid +
-                       ",uid="         + uid +
-                       ",mid="         + mid +
-                       ",wordCount="   + wordCount +
-                       ",byteCount="   + byteCount );
-       }
+            t = (t + MILLISECONDS_BETWEEN_1970_AND_1601) * 10000L;
+        }
+
+        writeInt8( t, dst, dstIndex );
+    }
+    static long readUTime( byte[] buffer, int bufferIndex ) {
+        return readInt4( buffer, bufferIndex ) * 1000L;
+    }
+    static void writeUTime( long t, byte[] dst, int dstIndex ) {
+        if( t == 0L || t == 0xFFFFFFFFFFFFFFFFL ) {
+            writeInt4( 0xFFFFFFFF, dst, dstIndex );
+            return;
+        }
+        synchronized( TZ ) {
+            if( TZ.inDaylightTime( new Date() )) {
+                // in DST
+                if( TZ.inDaylightTime( new Date( t ))) {
+                    // t also in DST so no correction
+                } else {
+                    // t not in DST so subtract 1 hour
+                    t -= 3600000;
+                }
+            } else {
+                // not in DST
+                if( TZ.inDaylightTime( new Date( t ))) {
+                    // t is in DST so add 1 hour
+                    t += 3600000;
+                } else {
+                    // t isn't in DST either
+                }
+            }
+        }
+        writeInt4( (int)(t / 1000L), dst, dstIndex );
+    }
+
+
+    /*
+     * These are all the smbs supported by this library. This includes requests
+     * and well as their responses for each type however the actuall implementations
+     * of the readXxxWireFormat and writeXxxWireFormat methods may not be in
+     * place. For example at the time of this writing the readXxxWireFormat
+     * for requests and the writeXxxWireFormat for responses are not implemented
+     * and simply return 0. These would need to be completed for a server
+     * implementation.
+     */
+
+    static final byte SMB_COM_CREATE_DIRECTORY   = (byte)0x00;
+    static final byte SMB_COM_DELETE_DIRECTORY   = (byte)0x01;
+    static final byte SMB_COM_CLOSE              = (byte)0x04;
+    static final byte SMB_COM_DELETE             = (byte)0x06;
+    static final byte SMB_COM_RENAME             = (byte)0x07;
+    static final byte SMB_COM_QUERY_INFORMATION  = (byte)0x08;
+    static final byte SMB_COM_WRITE              = (byte)0x0B;
+    static final byte SMB_COM_CHECK_DIRECTORY    = (byte)0x10;
+    static final byte SMB_COM_TRANSACTION        = (byte)0x25;
+    static final byte SMB_COM_TRANSACTION_SECONDARY = (byte)0x26;
+    static final byte SMB_COM_MOVE               = (byte)0x2A;
+    static final byte SMB_COM_ECHO               = (byte)0x2B;
+    static final byte SMB_COM_OPEN_ANDX          = (byte)0x2D;
+    static final byte SMB_COM_READ_ANDX          = (byte)0x2E;
+    static final byte SMB_COM_WRITE_ANDX         = (byte)0x2F;
+    static final byte SMB_COM_TRANSACTION2       = (byte)0x32;
+    static final byte SMB_COM_FIND_CLOSE2        = (byte)0x34;
+    static final byte SMB_COM_TREE_DISCONNECT    = (byte)0x71;
+    static final byte SMB_COM_NEGOTIATE          = (byte)0x72;
+    static final byte SMB_COM_SESSION_SETUP_ANDX = (byte)0x73;
+    static final byte SMB_COM_LOGOFF_ANDX        = (byte)0x74;
+    static final byte SMB_COM_TREE_CONNECT_ANDX  = (byte)0x75;
+    static final byte SMB_COM_NT_CREATE_ANDX     = (byte)0xA2;
+
+    /*
+     * Some fields specify the offset from the beginning of the header. This
+     * field should be used for calculating that. This would likely be zero
+     * but an implemantation that encorporates the transport header(for
+     * efficiency) might use a different initial bufferIndex. For example,
+     * to eliminate copying data when writing NbtSession data one might
+     * manage that 4 byte header specifically and therefore the initial
+     * bufferIndex, and thus headerStart, would be 4).(NOTE: If one where
+     * looking for a way to improve perfomance this is precisly what you
+     * would want to do as the jcifs.netbios.SocketXxxputStream classes
+     * arraycopy all data read or written into a new buffer shifted over 4!)
+     */
+
+    byte command, flags;
+    int headerStart,
+        length,
+        batchLevel,
+        errorCode,
+        flags2,
+        tid, pid, uid, mid,
+        wordCount, byteCount;
+    boolean useUnicode, received;
+    long responseTimeout = 1;
+    int signSeq;
+    boolean verifyFailed;
+    NtlmPasswordAuthentication auth = null;
+    String path;
+
+    ServerMessageBlock() {
+        flags = (byte)( FLAGS_PATH_NAMES_CASELESS | FLAGS_PATH_NAMES_CANONICALIZED );
+        pid = PID;
+        batchLevel = 0;
+    }
+
+    int writeString( String str, byte[] dst, int dstIndex ) {
+        return writeString( str, dst, dstIndex, useUnicode );
+    }
+    int writeString( String str, byte[] dst, int dstIndex, boolean useUnicode ) {
+        int start = dstIndex;
+
+        try {
+            if( useUnicode ) {
+                // Unicode requires word alignment
+                if((( dstIndex - headerStart ) % 2 ) != 0 ) {
+                    dst[dstIndex++] = (byte)'\0';
+                }
+                System.arraycopy( str.getBytes( "UnicodeLittleUnmarked" ), 0,
+                                    dst, dstIndex, str.length() * 2 );
+                dstIndex += str.length() * 2;
+                dst[dstIndex++] = (byte)'\0';
+                dst[dstIndex++] = (byte)'\0';
+            } else {
+                byte[] b = str.getBytes( OEM_ENCODING );
+                System.arraycopy( b, 0, dst, dstIndex, b.length );
+                dstIndex += b.length;
+                dst[dstIndex++] = (byte)'\0';
+            }
+        } catch( UnsupportedEncodingException uee ) {
+            if( log.level > 1 )
+                uee.printStackTrace( log );
+        }
+
+        return dstIndex - start;
+    }
+    String readString( byte[] src, int srcIndex ) {
+        return readString( src, srcIndex, 256, useUnicode );
+    }
+    String readString( byte[] src, int srcIndex, int maxLen, boolean useUnicode ) {
+        int len = 0;
+        String str = null;
+        try {
+            if( useUnicode ) {
+                // Unicode requires word alignment
+                if((( srcIndex - headerStart ) % 2 ) != 0 ) {
+                    srcIndex++;
+                }
+                while( src[srcIndex + len] != (byte)0x00 ||
+                                            src[srcIndex + len + 1] != (byte)0x00 ) {
+                    len += 2;
+                    if( len > maxLen ) {
+Hexdump.hexdump( System.err, src, 0, 256 );
+                        throw new RuntimeException( "zero termination not found" );
+                    }
+                }
+                str = new String( src, srcIndex, len, "UnicodeLittle" );
+            } else {
+                while( src[srcIndex + len] != (byte)0x00 ) {
+                    len++;
+                    if( len > maxLen ) {
+                        throw new RuntimeException( "zero termination not found" );
+                    }
+                }
+                str = new String( src, srcIndex, len, OEM_ENCODING );
+            }
+        } catch( UnsupportedEncodingException uee ) {
+            if( log.level > 1 )
+                uee.printStackTrace( log );
+        }
+        return str;
+    }
+    int stringWireLength( String str, int offset ) {
+        int len = str.length() + 1;
+        if( useUnicode ) {
+            len = str.length() * 2 + 2;
+            len = ( offset % 2 ) != 0 ? len + 1 : len;
+        }
+        return len;
+    }
+    int readStringLength( byte[] src, int srcIndex, int max ) {
+        int len = 0;
+        while( src[srcIndex + len] != (byte)0x00 ) {
+            if( len++ > max ) {
+                throw new RuntimeException( "zero termination not found: " + this );
+            }
+        }
+        return len;
+    }
+    int writeWireFormat( byte[] dst, int dstIndex ) {
+        int start = headerStart = dstIndex;
+
+        dstIndex += writeHeaderWireFormat( dst, dstIndex );
+        wordCount = writeParameterWordsWireFormat( dst, dstIndex + 1 );
+        dst[dstIndex++] = (byte)(( wordCount / 2 ) & 0xFF );
+        dstIndex += wordCount;
+        wordCount /= 2;
+        byteCount = writeBytesWireFormat( dst, dstIndex + 2 );
+        dst[dstIndex++] = (byte)( byteCount & 0xFF );
+        dst[dstIndex++] = (byte)(( byteCount >> 8 ) & 0xFF );
+        dstIndex += byteCount;
+
+        length = dstIndex - start;
+        return length;
+    }
+    int readWireFormat( InputStream in,
+                            byte[] buffer,
+                            int bufferIndex )
+                            throws IOException {
+
+        int start = headerStart = bufferIndex;
+
+        /*
+         * read header
+         */
+
+        if( in.read( buffer, bufferIndex, HEADER_LENGTH ) != HEADER_LENGTH ) {
+            throw new IOException( "unexpected EOF reading smb header" );
+        }
+        bufferIndex += readHeaderWireFormat( buffer, bufferIndex );
+
+        /*
+         * read wordCount
+         */
+
+        if(( wordCount = in.read() ) == -1 ) {
+            throw new IOException( "unexpected EOF reading smb wordCount" );
+        }
+        buffer[bufferIndex++] = (byte)( wordCount & 0xFF );
+
+        /*
+         * read parameter words
+         */
+
+        if( wordCount != 0 ) {
+            if( in.read( buffer, bufferIndex, wordCount * 2 ) != wordCount * 2 ) {
+                throw new IOException( "unexpected EOF reading smb parameter words" );
+            }
+            int n;
+            if(( n = readParameterWordsWireFormat( buffer, bufferIndex )) != wordCount * 2 ) {
+                if( log.level > 2 ) {
+                    log.println( "wordCount * 2=" + ( wordCount * 2 ) +
+                            " but readParameterWordsWireFormat returned " + n );
+                }
+            }
+            bufferIndex += wordCount * 2;
+        }
+
+        /*
+         * read byteCount
+         */
+
+        if( in.read( buffer, bufferIndex, 2 ) != 2 ) {
+            throw new IOException( "unexpected EOF reading smb byteCount" );
+        }
+        byteCount = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+
+        /*
+         * read bytes
+         */
+
+        if( byteCount != 0 ) {
+            if( in.read( buffer, bufferIndex, byteCount ) != byteCount ) {
+                throw new IOException( "unexpected EOF reading smb" );
+            }
+            int n;
+            if(( n = readBytesWireFormat( buffer, bufferIndex )) != byteCount ) {
+                if( log.level > 2 ) {
+                    log.println( "byteCount=" + byteCount +
+                            " but readBytesWireFormat returned " + n );
+                }
+            }
+            // Don't think we can rely on n being correct here. Must use byteCount.
+            // Last paragraph of section 3.13.3 eludes to this.
+
+            bufferIndex += byteCount;
+        }
+
+        length = bufferIndex - start;
+        return length;
+    }
+    int writeHeaderWireFormat( byte[] dst, int dstIndex ) {
+        System.arraycopy( header, 0, dst, dstIndex, header.length );
+        dst[dstIndex + CMD_OFFSET] = command;
+        dst[dstIndex + FLAGS_OFFSET] = flags;
+        writeInt2( flags2, dst, dstIndex + FLAGS_OFFSET + 1 );
+        dstIndex += TID_OFFSET;
+        writeInt2( tid, dst, dstIndex );
+        writeInt2( pid, dst, dstIndex + 2 );
+        writeInt2( uid, dst, dstIndex + 4 );
+        writeInt2( mid, dst, dstIndex + 6 );
+        return HEADER_LENGTH;
+    }
+    int readHeaderWireFormat( byte[] buffer, int bufferIndex ) throws IOException {
+        command = buffer[bufferIndex + CMD_OFFSET];
+        errorCode = readInt4( buffer, bufferIndex + ERROR_CODE_OFFSET );
+        flags = buffer[bufferIndex + FLAGS_OFFSET];
+        flags2 = readInt2( buffer, bufferIndex + FLAGS_OFFSET + 1 );
+        tid = readInt2( buffer, bufferIndex + TID_OFFSET );
+        pid = readInt2( buffer, bufferIndex + TID_OFFSET + 2 );
+        uid = readInt2( buffer, bufferIndex + TID_OFFSET + 4 );
+        mid = readInt2( buffer, bufferIndex + TID_OFFSET + 6 );
+        return HEADER_LENGTH;
+    }
+    boolean isResponse() {
+        return ( flags & FLAGS_RESPONSE ) == FLAGS_RESPONSE;
+    }
+
+    /* 
+     * For this packet deconstruction technique to work for
+     * other networking protocols the InputStream may need
+     * to be passed to the readXxxWireFormat methods. This is
+     * actually purer. However, in the case of smb we know the
+     * wordCount and byteCount. And since every subclass of
+     * ServerMessageBlock would have to perform the same read
+     * operation on the input stream, we might as will pull that
+     * common functionality into the superclass and read wordCount
+     * and byteCount worth of data.
+     * 
+     * We will still use the readXxxWireFormat return values to
+     * indicate how many bytes(note: readParameterWordsWireFormat
+     * returns bytes read and not the number of words(but the
+     * wordCount member DOES store the number of words)) we
+     * actually read. Incedentally this is important to the
+     * AndXServerMessageBlock class that needs to potentially
+     * read in another smb's parameter words and bytes based on
+     * information in it's andxCommand, andxOffset, ...etc.
+     */ 
+
+    abstract int writeParameterWordsWireFormat( byte[] dst, int dstIndex );
+    abstract int writeBytesWireFormat( byte[] dst, int dstIndex );
+    abstract int readParameterWordsWireFormat( byte[] buffer,
+                                        int bufferIndex )
+                                        throws IOException;
+    abstract int readBytesWireFormat( byte[] buffer,
+                                        int bufferIndex )
+                                        throws IOException;
+
+    public String toString() {
+        String c;
+        switch( command ) {
+            case SMB_COM_NEGOTIATE:
+                c = "SMB_COM_NEGOTIATE";
+                break;
+            case SMB_COM_SESSION_SETUP_ANDX:
+                c = "SMB_COM_SESSION_SETUP_ANDX";
+                break;
+            case SMB_COM_TREE_CONNECT_ANDX:
+                c = "SMB_COM_TREE_CONNECT_ANDX";
+                break;
+            case SMB_COM_QUERY_INFORMATION:
+                c = "SMB_COM_QUERY_INFORMATION";
+                break;
+            case SMB_COM_CHECK_DIRECTORY:
+                c = "SMB_COM_CHECK_DIRECTORY";
+                break;
+            case SMB_COM_TRANSACTION:
+                c = "SMB_COM_TRANSACTION";
+                break;
+            case SMB_COM_TRANSACTION2:
+                c = "SMB_COM_TRANSACTION2";
+                break;
+            case SMB_COM_TRANSACTION_SECONDARY:
+                c = "SMB_COM_TRANSACTION_SECONDARY";
+                break;
+            case SMB_COM_FIND_CLOSE2:
+                c = "SMB_COM_FIND_CLOSE2";
+                break;
+            case SMB_COM_TREE_DISCONNECT:
+                c = "SMB_COM_TREE_DISCONNECT";
+                break;
+            case SMB_COM_LOGOFF_ANDX:
+                c = "SMB_COM_LOGOFF_ANDX";
+                break;
+            case SMB_COM_ECHO:
+                c = "SMB_COM_ECHO";
+                break;
+            case SMB_COM_MOVE:
+                c = "SMB_COM_MOVE";
+                break;
+            case SMB_COM_RENAME:
+                c = "SMB_COM_RENAME";
+                break;
+            case SMB_COM_DELETE:
+                c = "SMB_COM_DELETE";
+                break;
+            case SMB_COM_DELETE_DIRECTORY:
+                c = "SMB_COM_DELETE_DIRECTORY";
+                break;
+            case SMB_COM_NT_CREATE_ANDX:
+                c = "SMB_COM_NT_CREATE_ANDX";
+                break;
+            case SMB_COM_OPEN_ANDX:
+                c = "SMB_COM_OPEN_ANDX";
+                break;
+            case SMB_COM_READ_ANDX:
+                c = "SMB_COM_READ_ANDX";
+                break;
+            case SMB_COM_CLOSE:
+                c = "SMB_COM_CLOSE";
+                break;
+            case SMB_COM_WRITE_ANDX:
+                c = "SMB_COM_WRITE_ANDX";
+                break;
+            case SMB_COM_CREATE_DIRECTORY:
+                c = "SMB_COM_CREATE_DIRECTORY";
+                break;
+            default:
+                c = "UNKNOWN";
+        }
+        return new String(
+            "command="      + c +
+            ",received="    + received +
+            ",errorCode=" + SmbException.getMessageByCode( errorCode ) +
+            ",flags=0x"     + Hexdump.toHexString( flags & 0xFF, 4 ) +
+            ",flags2=0x"    + Hexdump.toHexString( flags2, 4 ) +
+            ",signSeq="     + signSeq +
+            ",tid="         + tid +
+            ",pid="         + pid +
+            ",uid="         + uid +
+            ",mid="         + mid +
+            ",wordCount="   + wordCount +
+            ",byteCount="   + byteCount );
+    }
 }
diff --git a/src/jcifs/smb/SigningDigest.java b/src/jcifs/smb/SigningDigest.java
new file mode 100644 (file)
index 0000000..1852b76
--- /dev/null
@@ -0,0 +1,171 @@
+package jcifs.smb;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.io.IOException;
+import jcifs.Config;
+import jcifs.util.LogStream;
+import jcifs.util.Hexdump;
+
+/**
+ * To filter 0 len updates and for debugging
+ */
+
+public class SigningDigest {
+
+    private static final int LM_COMPATIBILITY = Config.getInt( "jcifs.smb.lmCompatibility", 0);
+
+    static LogStream log = LogStream.getInstance();
+
+    private MessageDigest digest;
+    private byte[] macSigningKey;
+    private int updates;
+    private int signSequence;
+    boolean sessionSetup;
+
+    public SigningDigest( SmbTransport transport,
+                NtlmPasswordAuthentication auth ) throws SmbException {
+        try {
+            digest = MessageDigest.getInstance("MD5");
+        } catch (NoSuchAlgorithmException ex) {
+            if( log.level > 0 )
+                ex.printStackTrace( log );
+            throw new SmbException( "MD5", ex );
+        }
+
+        try {
+            switch (LM_COMPATIBILITY) {
+            case 0:
+            case 1:
+            case 2:
+                macSigningKey = new byte[40];
+                auth.getUserSessionKey(transport.server.encryptionKey, macSigningKey, 0);
+                System.arraycopy(auth.getUnicodeHash(transport.server.encryptionKey),
+                            0, macSigningKey, 16, 24);
+                break;
+            case 3:
+            case 4:
+            case 5:
+                macSigningKey = new byte[16];
+                auth.getUserSessionKey(transport.server.encryptionKey, macSigningKey, 0);
+                break;
+            default:
+                macSigningKey = new byte[40];
+                auth.getUserSessionKey(transport.server.encryptionKey, macSigningKey, 0);
+                System.arraycopy(auth.getUnicodeHash(transport.server.encryptionKey),
+                            0, macSigningKey, 16, 24);
+                break;
+            }
+        } catch( Exception ex ) {
+            throw new SmbException( "", ex );
+        }
+        if( log.level > 3 ) {
+            log.println( "LM_COMPATIBILITY=" + LM_COMPATIBILITY );
+            Hexdump.hexdump( log, macSigningKey, 0, macSigningKey.length );
+        }
+    }
+
+    public void update( byte[] input, int offset, int len ) {
+        if( log.level > 3 ) {
+            log.println( "update: " + updates + " " + offset + ":" + len );
+            Hexdump.hexdump( log, input, offset, Math.min( len, 256 ));
+            log.flush();
+        }
+        if( len == 0 ) {
+            return; /* CRITICAL */
+        }
+        digest.update( input, offset, len );
+        updates++;
+    }
+    public byte[] digest() {
+        byte[] b;
+
+        b = digest.digest();
+
+        if( log.level > 3 ) {
+            log.println( "digest: " );
+            Hexdump.hexdump( log, b, 0, b.length );
+            log.flush();
+        }
+        updates = 0;
+
+        return b;
+    }
+
+    /**
+     * Performs MAC signing of the SMB.  This is done as follows.
+     * The signature field of the SMB is overwritted with the sequence number;
+     * The MD5 digest of the MAC signing key + the entire SMB is taken;
+     * The first 8 bytes of this are placed in the signature field.
+     *
+     * @param data The data.
+     * @param offset The starting offset at which the SMB header begins.
+     * @param length The length of the SMB data starting at offset. 
+     */
+    void sign(byte[] data, int offset, int length,
+                ServerMessageBlock request, ServerMessageBlock response) {
+        request.signSeq = signSequence;
+        if( response != null ) {
+            response.signSeq = signSequence + 1;
+            response.verifyFailed = false;
+        }
+
+        try {
+            update(macSigningKey, 0, macSigningKey.length);
+            int index = offset + ServerMessageBlock.SIGNATURE_OFFSET;
+            for (int i = 0; i < 8; i++) data[index + i] = 0;
+            ServerMessageBlock.writeInt4(signSequence, data, index);
+            update(data, offset, length);
+            System.arraycopy(digest(), 0, data, index, 8);
+        } catch (Exception ex) {
+            if( log.level > 0 )
+                ex.printStackTrace( log );
+        } finally {
+            signSequence += 2;
+        }
+    } 
+
+    /**
+     * Performs MAC signature verification.  This calculates the signature
+     * of the SMB and compares it to the signature field on the SMB itself.
+     *
+     * @param data The data.
+     * @param offset The starting offset at which the SMB header begins.
+     * @param length The length of the SMB data starting at offset. 
+     */
+    boolean verify(byte[] data, int offset, ServerMessageBlock response) {
+        update(macSigningKey, 0, macSigningKey.length);
+        int index = offset;
+        update(data, index, ServerMessageBlock.SIGNATURE_OFFSET); 
+        index += ServerMessageBlock.SIGNATURE_OFFSET;
+        byte[] sequence = new byte[8]; 
+        ServerMessageBlock.writeInt4(response.signSeq, sequence, 0); 
+        update(sequence, 0, sequence.length); 
+        index += 8;
+        if( response.command == ServerMessageBlock.SMB_COM_READ_ANDX ) {
+            /* SmbComReadAndXResponse reads directly from the stream into separate byte[] b.
+             */
+            SmbComReadAndXResponse raxr = (SmbComReadAndXResponse)response;
+            int length = response.length - raxr.dataLength;
+            update(data, index, length - ServerMessageBlock.SIGNATURE_OFFSET - 8);
+            update(raxr.b, raxr.off, raxr.dataLength);
+        } else {
+            update(data, index, response.length - ServerMessageBlock.SIGNATURE_OFFSET - 8);
+        }
+        byte[] signature = digest();
+        for (int i = 0; i < 8; i++) {
+            if (signature[i] != data[offset + ServerMessageBlock.SIGNATURE_OFFSET + i]) {
+                if( log.level > 2 ) {
+                    log.println( "signature verification failure" );
+                    Hexdump.hexdump( log, signature, 0, 8 );
+                    Hexdump.hexdump( log, data,
+                        offset + ServerMessageBlock.SIGNATURE_OFFSET, 8 );
+                }
+                return response.verifyFailed = true;
+            }
+        }
+
+        return response.verifyFailed = false;
+    }
+}
+
index b98123d..2e93162 100644 (file)
@@ -27,10 +27,7 @@ package jcifs.smb;
 
 public class SmbAuthException extends SmbException {
 
-       public SmbAuthException( int code ) {
-               super( code );
-       }
-       public SmbAuthException( int errorClass, int errorCode ) {
-               super( errorClass, errorCode );
-       }
+    SmbAuthException( int errcode ) {
+        super( errcode, null );
+    }
 }
index 96b0e36..36b622e 100644 (file)
@@ -20,23 +20,23 @@ package jcifs.smb;
 
 class SmbComBlankResponse extends ServerMessageBlock {
 
-       SmbComBlankResponse() {
-       }
+    SmbComBlankResponse() {
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComBlankResponse[" +
-                       super.toString() + "]" );
-       }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComBlankResponse[" +
+            super.toString() + "]" );
+    }
 }
index 771d3ce..3b4031a 100644 (file)
@@ -20,33 +20,33 @@ package jcifs.smb;
 
 class SmbComCheckDirectory extends ServerMessageBlock {
 
-       String directoryPath;
+    String directoryPath;
 
-       SmbComCheckDirectory( String directoryPath ) {
-               command = SMB_COM_CHECK_DIRECTORY;
-               this.directoryPath = directoryPath;
-       }
+    SmbComCheckDirectory( String directoryPath ) {
+        command = SMB_COM_CHECK_DIRECTORY;
+        this.directoryPath = directoryPath;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               dst[dstIndex++] = (byte)0x04;
-               dstIndex += writeString( directoryPath, dst, dstIndex );
+        dst[dstIndex++] = (byte)0x04;
+        dstIndex += writeString( directoryPath, dst, dstIndex );
 
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComCheckDirectory[" +
-                       super.toString() +
-                       ",directoryPath=" + directoryPath + "]" );
-       }
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComCheckDirectory[" +
+            super.toString() +
+            ",directoryPath=" + directoryPath + "]" );
+    }
 }
index 906fda1..7e5ac51 100644 (file)
@@ -22,34 +22,34 @@ import java.util.Date;
 
 class SmbComClose extends ServerMessageBlock {
 
-       int fid;
-       long lastWriteTime;
+    private int fid;
+    private long lastWriteTime;
 
-       SmbComClose( int fid, long lastWriteTime ) {
-               this.fid = fid;
-               this.lastWriteTime = lastWriteTime;
-               command = SMB_COM_CLOSE;
-       }
+    SmbComClose( int fid, long lastWriteTime ) {
+        this.fid = fid;
+        this.lastWriteTime = lastWriteTime;
+        command = SMB_COM_CLOSE;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               writeInt2( fid, dst, dstIndex );
-               dstIndex += 2;
-               writeUTime( lastWriteTime, dst, dstIndex );
-               return 6;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComClose[" +
-                       super.toString() +
-                       ",fid=" + fid +
-                       ",lastWriteTime=" + lastWriteTime + "]" );
-       }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        writeInt2( fid, dst, dstIndex );
+        dstIndex += 2;
+        writeUTime( lastWriteTime, dst, dstIndex );
+        return 6;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComClose[" +
+            super.toString() +
+            ",fid=" + fid +
+            ",lastWriteTime=" + lastWriteTime + "]" );
+    }
 }
index 979a458..f716fed 100644 (file)
@@ -20,31 +20,31 @@ package jcifs.smb;
 
 class SmbComCreateDirectory extends ServerMessageBlock {
 
-       SmbComCreateDirectory( String directoryName ) {
-               this.path = directoryName;
-               command = SMB_COM_CREATE_DIRECTORY;
-       }
+    SmbComCreateDirectory( String directoryName ) {
+        this.path = directoryName;
+        command = SMB_COM_CREATE_DIRECTORY;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               dst[dstIndex++] = (byte)0x04;
-               dstIndex += writeString( path, dst, dstIndex );
+        dst[dstIndex++] = (byte)0x04;
+        dstIndex += writeString( path, dst, dstIndex );
 
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComCreateDirectory[" +
-                       super.toString() +
-                       ",directoryName=" + path + "]" );
-       }
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComCreateDirectory[" +
+            super.toString() +
+            ",directoryName=" + path + "]" );
+    }
 }
index a1e9baf..63aba98 100644 (file)
 
 package jcifs.smb;
 
+import jcifs.util.Hexdump;
+
 class SmbComDelete extends ServerMessageBlock {
 
-       int searchAttributes;
-       String fileName;
-
-       SmbComDelete( String fileName ) {
-               this.fileName = fileName;
-               command = SMB_COM_DELETE;
-               searchAttributes = ATTR_HIDDEN | ATTR_SYSTEM;
-       }
-
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               writeInt2( searchAttributes, dst, dstIndex );
-               return 2;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-
-               dst[dstIndex++] = (byte)0x04;
-               dstIndex += writeString( fileName, dst, dstIndex );
-
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComDelete[" +
-                       super.toString() +
-                       ",searchAttributes=0x" + Log.getHexString( searchAttributes, 4 ) +
-                       ",fileName=" + fileName + "]" );
-       }
+    private int searchAttributes;
+    private String fileName;
+
+    SmbComDelete( String fileName ) {
+        this.fileName = fileName;
+        command = SMB_COM_DELETE;
+        searchAttributes = ATTR_HIDDEN | ATTR_HIDDEN | ATTR_SYSTEM;
+    }
+
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        writeInt2( searchAttributes, dst, dstIndex );
+        return 2;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+
+        dst[dstIndex++] = (byte)0x04;
+        dstIndex += writeString( fileName, dst, dstIndex );
+
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComDelete[" +
+            super.toString() +
+            ",searchAttributes=0x" + Hexdump.toHexString( searchAttributes, 4 ) +
+            ",fileName=" + fileName + "]" );
+    }
 }
index ee6c6e7..95cd426 100644 (file)
@@ -20,31 +20,31 @@ package jcifs.smb;
 
 class SmbComDeleteDirectory extends ServerMessageBlock {
 
-       SmbComDeleteDirectory( String directoryName ) {
-               this.path = directoryName;
-               command = SMB_COM_DELETE_DIRECTORY;
-       }
+    SmbComDeleteDirectory( String directoryName ) {
+        this.path = directoryName;
+        command = SMB_COM_DELETE_DIRECTORY;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               dst[dstIndex++] = (byte)0x04;
-               dstIndex += writeString( path, dst, dstIndex );
+        dst[dstIndex++] = (byte)0x04;
+        dstIndex += writeString( path, dst, dstIndex );
 
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComDeleteDirectory[" +
-                       super.toString() +
-                       ",directoryName=" + path + "]" );
-       }
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComDeleteDirectory[" +
+            super.toString() +
+            ",directoryName=" + path + "]" );
+    }
 }
index 04dcea9..abb5528 100644 (file)
@@ -20,30 +20,30 @@ package jcifs.smb;
 
 class SmbComEcho extends ServerMessageBlock {
 
-       int echoCount;
+    int echoCount;
 
-       SmbComEcho( int echoCount ) {
-               command = SMB_COM_ECHO;
-               this.echoCount = echoCount;
-       }
+    SmbComEcho( int echoCount ) {
+        command = SMB_COM_ECHO;
+        this.echoCount = echoCount;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               writeInt2( echoCount, dst, dstIndex );
-               return 2;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex] = (byte)'M';
-               return 1;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComEcho[" +
-                       super.toString() +
-                       ",echoCount=" + echoCount + "]" );
-       }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        writeInt2( echoCount, dst, dstIndex );
+        return 2;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex] = (byte)'M';
+        return 1;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComEcho[" +
+            super.toString() +
+            ",echoCount=" + echoCount + "]" );
+    }
 }
index 91f59f8..87530c4 100644 (file)
@@ -20,26 +20,26 @@ package jcifs.smb;
 
 class SmbComEchoResponse extends ServerMessageBlock {
 
-       int sequenceNumber;
+    int sequenceNumber;
 
-       SmbComEchoResponse() {
-       }
+    SmbComEchoResponse() {
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               sequenceNumber = readInt2( buffer, bufferIndex );
-               return 2;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 1;
-       }
-       public String toString() {
-               return new String( "SmbComEchoResponse[" +
-                       super.toString() + "]" );
-       }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        sequenceNumber = readInt2( buffer, bufferIndex );
+        return 2;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 1;
+    }
+    public String toString() {
+        return new String( "SmbComEchoResponse[" +
+            super.toString() + "]" );
+    }
 }
index 42ac876..c296962 100644 (file)
@@ -20,29 +20,29 @@ package jcifs.smb;
 
 class SmbComFindClose2 extends ServerMessageBlock {
 
-       int sid;
+    private int sid;
 
-       SmbComFindClose2( int sid ) {
-               this.sid = sid;
-               command = SMB_COM_FIND_CLOSE2;
-       }
+    SmbComFindClose2( int sid ) {
+        this.sid = sid;
+        command = SMB_COM_FIND_CLOSE2;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               writeInt2( sid, dst, dstIndex );
-               return 2;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComFindClose2[" +
-                       super.toString() +
-                       ",sid=" + sid + "]" );
-       }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        writeInt2( sid, dst, dstIndex );
+        return 2;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComFindClose2[" +
+            super.toString() +
+            ",sid=" + sid + "]" );
+    }
 }
index 8d6404c..bbfaf65 100644 (file)
@@ -23,28 +23,29 @@ import java.io.InputStream;
 
 class SmbComLogoffAndX extends AndXServerMessageBlock {
 
-       SmbComLogoffAndX( ServerMessageBlock andx ) {
-               super( andx );
-               command = SMB_COM_LOGOFF_ANDX;
-       }
+    SmbComLogoffAndX( ServerMessageBlock andx ) {
+        super( andx );
+        command = SMB_COM_LOGOFF_ANDX;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComLogoffAndX[" +
-                       super.toString() + "]" );
-       }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComLogoffAndX[" +
+            super.toString() + "]" );
+    }
 }
index 21de75b..cf096aa 100644 (file)
@@ -20,54 +20,54 @@ package jcifs.smb;
 
 class SmbComMove extends ServerMessageBlock {
 
-       String oldFileName;
-       String newFileName;
-       int tid2;
-       int openFunction;
-       int flags;
+    String oldFileName;
+    String newFileName;
+    int tid2;
+    int openFunction;
+    int flags;
 
-       SmbComMove( String oldFileName, String newFileName, int tid2 ) {
-               command = SMB_COM_MOVE;
-               this.oldFileName = oldFileName;
-               this.newFileName = newFileName;
-               this.tid2 = tid2 == 0 ? -1 : tid2;
+    SmbComMove( String oldFileName, String newFileName, int tid2 ) {
+        command = SMB_COM_MOVE;
+        this.oldFileName = oldFileName;
+        this.newFileName = newFileName;
+        this.tid2 = tid2 == 0 ? -1 : tid2;
 
-               // these will need to be adjusted
-               openFunction = OPEN_FUNCTION_FAIL_IF_EXISTS;
-               flags = FLAGS_TARGET_MUST_BE_FILE;
-       }
+        // these will need to be adjusted
+        openFunction = OPEN_FUNCTION_FAIL_IF_EXISTS;
+        flags = FLAGS_TARGET_MUST_BE_FILE;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               writeInt2( tid2, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( openFunction, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( flags, dst, dstIndex );
-               return 6;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        writeInt2( tid2, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( openFunction, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( flags, dst, dstIndex );
+        return 6;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               dst[dstIndex++] = (byte)0x04;
-               dstIndex += writeString( oldFileName, dst, dstIndex );
-               dst[dstIndex++] = (byte)0x04;
-               dstIndex += writeString( newFileName, dst, dstIndex );
+        dst[dstIndex++] = (byte)0x04;
+        dstIndex += writeString( oldFileName, dst, dstIndex );
+        dst[dstIndex++] = (byte)0x04;
+        dstIndex += writeString( newFileName, dst, dstIndex );
 
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComMove[" +
-                       super.toString() +
-                       ",oldFileName=" + oldFileName +
-                       ",newFileName=" + newFileName +
-                       ",tid2=" + tid2 +
-                       ",openFunction=" + openFunction +
-                       ",flags=" + flags + "]" );
-       }
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComMove[" +
+            super.toString() +
+            ",oldFileName=" + oldFileName +
+            ",newFileName=" + newFileName +
+            ",tid2=" + tid2 +
+            ",openFunction=" + openFunction +
+            ",flags=" + flags + "]" );
+    }
 }
index c30b69b..6c3e894 100644 (file)
@@ -20,33 +20,33 @@ package jcifs.smb;
 
 class SmbComMoveResponse extends ServerMessageBlock {
 
-       int count;
-       String errorFileName;
+    int count;
+    String errorFileName;
 
-       SmbComMoveResponse() {
-               count = 0;
-               errorFileName = "";
-       }
+    SmbComMoveResponse() {
+        count = 0;
+        errorFileName = "";
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               count = readInt2( buffer, bufferIndex );
-               return 2;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               bufferIndex++;
-               errorFileName = readString( buffer, bufferIndex );
-               return stringWireLength( errorFileName, bufferIndex );
-       }
-       public String toString() {
-               return new String( "SmbComMoveResponse[" +
-                       super.toString() +
-                       ",count=" + count +
-                       ",errorFileName=" + errorFileName + "]" );
-       }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        count = readInt2( buffer, bufferIndex );
+        return 2;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        bufferIndex++;
+        errorFileName = readString( buffer, bufferIndex );
+        return stringWireLength( errorFileName, bufferIndex );
+    }
+    public String toString() {
+        return new String( "SmbComMoveResponse[" +
+            super.toString() +
+            ",count=" + count +
+            ",errorFileName=" + errorFileName + "]" );
+    }
 }
index 2ab3c7d..e908da3 100644 (file)
@@ -20,192 +20,198 @@ package jcifs.smb;
 
 import java.io.IOException;
 import java.io.InputStream;
+import jcifs.util.Hexdump;
 
 class SmbComNTCreateAndX extends AndXServerMessageBlock {
 
-       // access mask encoding
-       static final int FILE_READ_DATA        = 0x00000001; // 1
-       static final int FILE_WRITE_DATA       = 0x00000002; // 2
-       static final int FILE_APPEND_DATA      = 0x00000004; // 3
-       static final int FILE_READ_EA          = 0x00000008; // 4
-       static final int FILE_WRITE_EA         = 0x00000010; // 5
-       static final int FILE_EXECUTE          = 0x00000020; // 6
-       static final int FILE_DELETE           = 0x00000040; // 7
-       static final int FILE_READ_ATTRIBUTES  = 0x00000080; // 8
-       static final int FILE_WRITE_ATTRIBUTES = 0x00000100; // 9
-       static final int DELETE                = 0x00010000; // 16
-       static final int READ_CONTROL          = 0x00020000; // 17
-       static final int WRITE_DAC             = 0x00040000; // 18
-       static final int WRITE_OWNER           = 0x00080000; // 19
-       static final int SYNCHRONIZE           = 0x00100000; // 20
-       static final int GENERIC_ALL           = 0x10000000; // 28
-       static final int GENERIC_EXECUTE       = 0x20000000; // 29
-       static final int GENERIC_WRITE         = 0x40000000; // 30
-       static final int GENERIC_READ          = 0x80000000; // 31
-
-       // share access specified in SmbFile
-
-       // create disposition
-
-       /* Creates a new file or supersedes the existing one
-        */
-
-       static final int FILE_SUPERSEDE    = 0x0;
-
-       /* Open the file or fail if it does not exist
-        * aka OPEN_EXISTING
-        */
-
-       static final int FILE_OPEN         = 0x1;
-
-       /* Create the file or fail if it does not exist
-        * aka CREATE_NEW
-        */
-
-       static final int FILE_CREATE       = 0x2;
-
-       /* Open the file or create it if it does not exist
-        * aka OPEN_ALWAYS
-        */
-
-       static final int FILE_OPEN_IF      = 0x3;
-
-       /* Open the file and overwrite it's contents or fail if it does not exist
-        * aka TRUNCATE_EXISTING
-        */
-
-       static final int FILE_OVERWRITE    = 0x4;
-
-       /* Open the file and overwrite it's contents or create it if it does not exist
-        * aka CREATE_ALWAYS (according to the wire when calling CreateFile)
-        */
-
-       static final int FILE_OVERWRITE_IF = 0x5;
-
-
-       // create options
-       static final int FILE_WRITE_THROUGH           = 0x00000002;
-       static final int FILE_SEQUENTIAL_ONLY         = 0x00000004;
-       static final int FILE_SYNCHRONOUS_IO_ALERT    = 0x00000010;
-       static final int FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020;
-
-       // security flags
-       static final int SECURITY_CONTEXT_TRACKING = 0x01;
-       static final int SECURITY_EFFECTIVE_ONLY   = 0x02;
-
-       int flags,
-               rootDirectoryFid,
-               desiredAccess,
-               extFileAttributes,
-               shareAccess,
-               createDisposition,
-               createOptions,
-               impersonationLevel;
-       long allocationSize;
-       byte securityFlags;
-
-       SmbComNTCreateAndX( String name, int flags,
-                               int shareAccess,
-                               int extFileAttributes,
-                               int createOptions,
-                               ServerMessageBlock andx ) {
-               super( andx );
-               this.path = name;
-               command = SMB_COM_NT_CREATE_ANDX;
-
-               // desiredAccess
-               desiredAccess = ( flags >>> 16 ) & 0xFFFF;
-               desiredAccess |= FILE_READ_EA | FILE_READ_ATTRIBUTES;
-
-               // extFileAttributes
-               this.extFileAttributes = extFileAttributes;
-
-               // shareAccess
-               this.shareAccess = shareAccess;
-
-               // createDisposition
-               if(( flags & SmbFile.O_TRUNC ) == SmbFile.O_TRUNC ) {
-                       // truncate the file
-                       if(( flags & SmbFile.O_CREAT ) == SmbFile.O_CREAT ) {
-                               // create it if necessary
-                               createDisposition = FILE_OVERWRITE_IF;
-                       } else {
-                               createDisposition = FILE_OVERWRITE;
-                       }
-               } else {
-                       // don't truncate the file
-                       if(( flags & SmbFile.O_CREAT ) == SmbFile.O_CREAT ) {
-                               // create it if necessary
-                               if ((flags & SmbFile.O_EXCL ) == SmbFile.O_EXCL ) {
-                                       // fail if already exists
-                                       createDisposition = FILE_CREATE;
-                               } else {
-                                       createDisposition = FILE_OPEN_IF;
-                               }
-                       } else {
-                               createDisposition = FILE_OPEN;
-                       }
-               }
-
-               this.createOptions = createOptions | 0x0040;
-               impersonationLevel = 0x02; // As seen on NT :~)
-               securityFlags = (byte)0x03; // SECURITY_CONTEXT_TRACKING | SECURITY_EFFECTIVE_ONLY
-       }
-
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-
-               dst[dstIndex++] = (byte)0x00;
-               // name length without counting null termination
-               writeInt2( ( useUnicode ? path.length() * 2 : path.length() ), dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( flags, dst, dstIndex );
-               dstIndex += 4;
-               writeInt4( rootDirectoryFid, dst, dstIndex );
-               dstIndex += 4;
-               writeInt4( desiredAccess, dst, dstIndex );
-               dstIndex += 4;
-               writeInt8( allocationSize, dst, dstIndex );
-               dstIndex += 8;
-               writeInt4( extFileAttributes, dst, dstIndex );
-               dstIndex += 4;
-               writeInt4( shareAccess, dst, dstIndex );
-               dstIndex += 4;
-               writeInt4( createDisposition, dst, dstIndex );
-               dstIndex += 4;
-               writeInt4( createOptions, dst, dstIndex );
-               dstIndex += 4;
-               writeInt4( impersonationLevel, dst, dstIndex );
-               dstIndex += 4;
-               dst[dstIndex++] = securityFlags;
-
-               return dstIndex - start;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return writeString( path, dst, dstIndex );
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComNTCreateAndX[" +
-                       super.toString() +
-                       ",flags=0x" + Log.getHexString( flags, 2 ) +
-                       ",rootDirectoryFid=" + rootDirectoryFid +
-                       ",desiredAccess=0x" + Log.getHexString( desiredAccess, 4 ) +
-                       ",allocationSize=" + allocationSize +
-                       ",extFileAttributes=0x" + Log.getHexString( extFileAttributes, 4 ) +
-                       ",shareAccess=0x" + Log.getHexString( shareAccess, 4 ) +
-                       ",createDisposition=0x" + Log.getHexString( createDisposition, 4 ) +
-                       ",createOptions=0x" + Log.getHexString( createOptions, 8 ) +
-                       ",impersonationLevel=0x" + Log.getHexString( impersonationLevel, 4 ) +
-                       ",securityFlags=0x" + Log.getHexString( securityFlags, 2 ) +
-                       ",name=" + path + "]" );
-       }
+    // access mask encoding
+    static final int FILE_READ_DATA        = 0x00000001; // 1
+    static final int FILE_WRITE_DATA       = 0x00000002; // 2
+    static final int FILE_APPEND_DATA      = 0x00000004; // 3
+    static final int FILE_READ_EA          = 0x00000008; // 4
+    static final int FILE_WRITE_EA         = 0x00000010; // 5
+    static final int FILE_EXECUTE          = 0x00000020; // 6
+    static final int FILE_DELETE           = 0x00000040; // 7
+    static final int FILE_READ_ATTRIBUTES  = 0x00000080; // 8
+    static final int FILE_WRITE_ATTRIBUTES = 0x00000100; // 9
+    static final int DELETE                = 0x00010000; // 16
+    static final int READ_CONTROL          = 0x00020000; // 17
+    static final int WRITE_DAC             = 0x00040000; // 18
+    static final int WRITE_OWNER           = 0x00080000; // 19
+    static final int SYNCHRONIZE           = 0x00100000; // 20
+    static final int GENERIC_ALL           = 0x10000000; // 28
+    static final int GENERIC_EXECUTE       = 0x20000000; // 29
+    static final int GENERIC_WRITE         = 0x40000000; // 30
+    static final int GENERIC_READ          = 0x80000000; // 31
+
+    // share access specified in SmbFile
+
+    // create disposition
+
+    /* Creates a new file or supersedes the existing one
+     */
+
+    static final int FILE_SUPERSEDE    = 0x0;
+
+    /* Open the file or fail if it does not exist
+     * aka OPEN_EXISTING
+     */
+
+    static final int FILE_OPEN         = 0x1;
+
+    /* Create the file or fail if it does not exist
+     * aka CREATE_NEW
+     */
+
+    static final int FILE_CREATE       = 0x2;
+
+    /* Open the file or create it if it does not exist
+     * aka OPEN_ALWAYS
+     */
+
+    static final int FILE_OPEN_IF      = 0x3;
+
+    /* Open the file and overwrite it's contents or fail if it does not exist
+     * aka TRUNCATE_EXISTING
+     */
+
+    static final int FILE_OVERWRITE    = 0x4;
+
+    /* Open the file and overwrite it's contents or create it if it does not exist
+     * aka CREATE_ALWAYS (according to the wire when calling CreateFile)
+     */
+
+    static final int FILE_OVERWRITE_IF = 0x5;
+
+
+    // create options
+    static final int FILE_WRITE_THROUGH           = 0x00000002;
+    static final int FILE_SEQUENTIAL_ONLY         = 0x00000004;
+    static final int FILE_SYNCHRONOUS_IO_ALERT    = 0x00000010;
+    static final int FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020;
+
+    // security flags
+    static final int SECURITY_CONTEXT_TRACKING = 0x01;
+    static final int SECURITY_EFFECTIVE_ONLY   = 0x02;
+
+    private int flags,
+        rootDirectoryFid,
+        desiredAccess,
+        extFileAttributes,
+        shareAccess,
+        createDisposition,
+        createOptions,
+        impersonationLevel;
+    private long allocationSize;
+    private byte securityFlags;
+
+    SmbComNTCreateAndX( String name, int flags,
+                int shareAccess,
+                int extFileAttributes,
+                int createOptions,
+                ServerMessageBlock andx ) {
+        super( andx );
+        this.path = name;
+        command = SMB_COM_NT_CREATE_ANDX;
+
+        // desiredAccess
+        desiredAccess = ( flags >>> 16 ) & 0xFFFF;
+        desiredAccess |= FILE_READ_EA | FILE_READ_ATTRIBUTES;
+
+        // extFileAttributes
+        this.extFileAttributes = extFileAttributes;
+
+        // shareAccess
+        this.shareAccess = shareAccess;
+
+        // createDisposition
+        if(( flags & SmbFile.O_TRUNC ) == SmbFile.O_TRUNC ) {
+            // truncate the file
+            if(( flags & SmbFile.O_CREAT ) == SmbFile.O_CREAT ) {
+                // create it if necessary
+                createDisposition = FILE_OVERWRITE_IF;
+            } else {
+                createDisposition = FILE_OVERWRITE;
+            }
+        } else {
+            // don't truncate the file
+            if(( flags & SmbFile.O_CREAT ) == SmbFile.O_CREAT ) {
+                // create it if necessary
+                if ((flags & SmbFile.O_EXCL ) == SmbFile.O_EXCL ) {
+                    // fail if already exists
+                    createDisposition = FILE_CREATE;
+                } else {
+                    createDisposition = FILE_OPEN_IF;
+                }
+            } else {
+                createDisposition = FILE_OPEN;
+            }
+        }
+
+        if(( createOptions & 0x01 ) == 0 ) {
+            this.createOptions = createOptions | 0x0040;
+        } else {
+            this.createOptions = createOptions;
+        }
+        impersonationLevel = 0x02; // As seen on NT :~)
+        securityFlags = (byte)0x03; // SECURITY_CONTEXT_TRACKING | SECURITY_EFFECTIVE_ONLY
+    }
+
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+
+        dst[dstIndex++] = (byte)0x00;
+        // name length without counting null termination
+        writeInt2( ( useUnicode ? path.length() * 2 : path.length() ), dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( flags, dst, dstIndex );
+        dstIndex += 4;
+        writeInt4( rootDirectoryFid, dst, dstIndex );
+        dstIndex += 4;
+        writeInt4( desiredAccess, dst, dstIndex );
+        dstIndex += 4;
+        writeInt8( allocationSize, dst, dstIndex );
+        dstIndex += 8;
+        writeInt4( extFileAttributes, dst, dstIndex );
+        dstIndex += 4;
+        writeInt4( shareAccess, dst, dstIndex );
+        dstIndex += 4;
+        writeInt4( createDisposition, dst, dstIndex );
+        dstIndex += 4;
+        writeInt4( createOptions, dst, dstIndex );
+        dstIndex += 4;
+        writeInt4( impersonationLevel, dst, dstIndex );
+        dstIndex += 4;
+        dst[dstIndex++] = securityFlags;
+
+        return dstIndex - start;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return writeString( path, dst, dstIndex );
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComNTCreateAndX[" +
+            super.toString() +
+            ",flags=0x" + Hexdump.toHexString( flags, 2 ) +
+            ",rootDirectoryFid=" + rootDirectoryFid +
+            ",desiredAccess=0x" + Hexdump.toHexString( desiredAccess, 4 ) +
+            ",allocationSize=" + allocationSize +
+            ",extFileAttributes=0x" + Hexdump.toHexString( extFileAttributes, 4 ) +
+            ",shareAccess=0x" + Hexdump.toHexString( shareAccess, 4 ) +
+            ",createDisposition=0x" + Hexdump.toHexString( createDisposition, 4 ) +
+            ",createOptions=0x" + Hexdump.toHexString( createOptions, 8 ) +
+            ",impersonationLevel=0x" + Hexdump.toHexString( impersonationLevel, 4 ) +
+            ",securityFlags=0x" + Hexdump.toHexString( securityFlags, 2 ) +
+            ",name=" + path + "]" );
+    }
 }
index 5808eca..a264eed 100644 (file)
@@ -21,89 +21,89 @@ package jcifs.smb;
 import java.util.Date;
 import java.io.IOException;
 import java.io.InputStream;
+import jcifs.util.Hexdump;
 
 class SmbComNTCreateAndXResponse extends AndXServerMessageBlock {
 
-       static final int EXCLUSIVE_OPLOCK_GRANTED = 1;
-       static final int BATCH_OPLOCK_GRANTED     = 2;
-       static final int LEVEL_II_OPLOCK_GRANTED  = 3;
+    static final int EXCLUSIVE_OPLOCK_GRANTED = 1;
+    static final int BATCH_OPLOCK_GRANTED     = 2;
+    static final int LEVEL_II_OPLOCK_GRANTED  = 3;
 
-       byte oplockLevel;
-       int fid,
-               createAction,
-               extFileAttributes,
-               fileType,
-               deviceState;
-       long creationTime,
-               lastAccessTime,
-               lastWriteTime,
-               changeTime,
-               allocationSize,
-               endOfFile;
-       boolean directory;
+    byte oplockLevel;
+    int fid,
+        createAction,
+        extFileAttributes,
+        fileType,
+        deviceState;
+    long creationTime,
+        lastAccessTime,
+        lastWriteTime,
+        changeTime,
+        allocationSize,
+        endOfFile;
+    boolean directory;
 
-       SmbComNTCreateAndXResponse() {
-       }
+    SmbComNTCreateAndXResponse() {
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               int start = bufferIndex;
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        int start = bufferIndex;
 
-               oplockLevel = buffer[bufferIndex++];
-               fid = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               createAction = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-               creationTime = readTime( buffer, bufferIndex );
-               bufferIndex += 8;
-               lastAccessTime = readTime( buffer, bufferIndex );
-               bufferIndex += 8;
-               lastWriteTime = readTime( buffer, bufferIndex );
-               bufferIndex += 8;
-               changeTime = readTime( buffer, bufferIndex );
-               bufferIndex += 8;
-               extFileAttributes = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-/* file attributes? */
-bufferIndex += 4;
-               allocationSize = readLong( buffer, bufferIndex );
-               bufferIndex += 8;
-               endOfFile = readLong( buffer, bufferIndex );
-               bufferIndex += 8;
-               fileType = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               deviceState = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               directory = ( buffer[bufferIndex++] & 0xFF ) > 0;
+        oplockLevel = buffer[bufferIndex++];
+        fid = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        createAction = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+        creationTime = readTime( buffer, bufferIndex );
+        bufferIndex += 8;
+        lastAccessTime = readTime( buffer, bufferIndex );
+        bufferIndex += 8;
+        lastWriteTime = readTime( buffer, bufferIndex );
+        bufferIndex += 8;
+        changeTime = readTime( buffer, bufferIndex );
+        bufferIndex += 8;
+        extFileAttributes = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+        allocationSize = readInt8( buffer, bufferIndex );
+        bufferIndex += 8;
+        endOfFile = readInt8( buffer, bufferIndex );
+        bufferIndex += 8;
+        fileType = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        deviceState = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        directory = ( buffer[bufferIndex++] & 0xFF ) > 0;
 
-               return bufferIndex - start;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComNTCreateAndXResponse[" +
-                       super.toString() +
-                       ",oplockLevel=" + oplockLevel +
-                       ",fid=" + fid +
-                       ",createAction=0x" + Log.getHexString( createAction, 4 ) +
-                       ",creationTime=" + new Date( creationTime ) +
-                       ",lastAccessTime=" + new Date( lastAccessTime ) +
-                       ",lastWriteTime=" + new Date( lastWriteTime ) +
-                       ",changeTime=" + new Date( changeTime ) +
-                       ",extFileAttributes=0x" + Log.getHexString( extFileAttributes, 4 ) +
-                       ",allocationSize=" + allocationSize +
-                       ",endOfFile=" + endOfFile +
-                       ",fileType=" + fileType +
-                       ",deviceState=" + deviceState +
-                       ",directory=" + directory + "]" );
-       }
+        return bufferIndex - start;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComNTCreateAndXResponse[" +
+            super.toString() +
+            ",oplockLevel=" + oplockLevel +
+            ",fid=" + fid +
+            ",createAction=0x" + Hexdump.toHexString( createAction, 4 ) +
+            ",creationTime=" + new Date( creationTime ) +
+            ",lastAccessTime=" + new Date( lastAccessTime ) +
+            ",lastWriteTime=" + new Date( lastWriteTime ) +
+            ",changeTime=" + new Date( changeTime ) +
+            ",extFileAttributes=0x" + Hexdump.toHexString( extFileAttributes, 4 ) +
+            ",allocationSize=" + allocationSize +
+            ",endOfFile=" + endOfFile +
+            ",fileType=" + fileType +
+            ",deviceState=" + deviceState +
+            ",directory=" + directory + "]" );
+    }
 }
index 202a010..6eb41e3 100644 (file)
@@ -22,36 +22,36 @@ import java.io.UnsupportedEncodingException;
 
 class SmbComNegotiate extends ServerMessageBlock {
 
-       static final String DIALECTS = "\u0002NT LM 0.12\u0000";
+    private static final String DIALECTS = "\u0002NT LM 0.12\u0000";
 
-       SmbComNegotiate() {
-               command = SMB_COM_NEGOTIATE;
-       }
+    SmbComNegotiate() {
+        command = SMB_COM_NEGOTIATE;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               byte[] dialects;
-               try {
-                       dialects = DIALECTS.getBytes( "ASCII" );
-               } catch( UnsupportedEncodingException uee ) {
-                       return 0;
-               }
-               System.arraycopy( dialects, 0, dst, dstIndex, dialects.length );
-               return dialects.length;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComNegotiate[" +
-                       super.toString() +
-                       ",wordCount="   + wordCount +
-                       ",dialects=NT LM 0.12]" );
-       }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        byte[] dialects;
+        try {
+            dialects = DIALECTS.getBytes( "ASCII" );
+        } catch( UnsupportedEncodingException uee ) {
+            return 0;
+        }
+        System.arraycopy( dialects, 0, dst, dstIndex, dialects.length );
+        return dialects.length;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComNegotiate[" +
+            super.toString() +
+            ",wordCount="   + wordCount +
+            ",dialects=NT LM 0.12]" );
+    }
 }
 
index 0988df1..5126722 100644 (file)
@@ -20,131 +20,133 @@ package jcifs.smb;
 
 import java.util.Date;
 import java.io.UnsupportedEncodingException;
+import jcifs.util.Hexdump;
 
 class SmbComNegotiateResponse extends ServerMessageBlock {
 
-       int dialectIndex,
-               securityMode,
-               security,
-               maxMpxCount,
-               maxNumberVcs,
-               maxBufferSize,
-               maxRawSize,
-               sessionKey,
-               capabilities,
-               serverTimeZone,
-               encryptionKeyLength;
-       boolean encryptedPasswords,
-               signaturesEnabled,
-               signaturesRequired;
-       long serverTime;
-       byte[] encryptionKey;
-       String oemDomainName;
+    int dialectIndex,
+        securityMode,
+        security,
+        maxMpxCount,
+        maxNumberVcs,
+        maxBufferSize,
+        maxRawSize,
+        sessionKey,
+        capabilities,
+        serverTimeZone,
+        encryptionKeyLength;
+    boolean encryptedPasswords,
+        signaturesEnabled,
+        signaturesRequired;
+    long serverTime;
+    byte[] encryptionKey;
+    String oemDomainName;
 
-       SmbComNegotiateResponse() {
-       }
+    SmbComNegotiateResponse() {
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer,
-                                                                       int bufferIndex ) {
-               int start = bufferIndex;
-               dialectIndex        = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               if( dialectIndex > 10 ) {
-                       return bufferIndex - start;
-               }
-               securityMode        = buffer[bufferIndex++] & 0xFF;
-               security            = securityMode & 0x01;
-               encryptedPasswords  = ( securityMode & 0x02 ) == 0x02 ? true : false;
-               signaturesEnabled   = ( securityMode & 0x04 ) == 0x04 ? true : false;
-               signaturesRequired  = ( securityMode & 0x08 ) == 0x08 ? true : false;
-               maxMpxCount         = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               maxNumberVcs        = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               maxBufferSize       = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-               maxRawSize          = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-               sessionKey          = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-               capabilities        = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-               serverTime          = readTime( buffer, bufferIndex );
-               bufferIndex += 8;
-               serverTimeZone      = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               encryptionKeyLength = buffer[bufferIndex++] & 0xFF;
-               return bufferIndex - start;
-       }
-       int readBytesWireFormat( byte[] buffer,
-                                                                       int bufferIndex ) {
-               int start = bufferIndex;
-               encryptionKey = new byte[encryptionKeyLength];
-               System.arraycopy( buffer, bufferIndex,
-                                               encryptionKey, 0, encryptionKeyLength );
-               bufferIndex += encryptionKeyLength;
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer,
+                                    int bufferIndex ) {
+        int start = bufferIndex;
+        dialectIndex        = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        if( dialectIndex > 10 ) {
+            return bufferIndex - start;
+        }
+        securityMode        = buffer[bufferIndex++] & 0xFF;
+        security            = securityMode & 0x01;
+        encryptedPasswords  = ( securityMode & 0x02 ) == 0x02 ? true : false;
+        signaturesEnabled   = ( securityMode & 0x04 ) == 0x04 ? true : false;
+        signaturesRequired  = ( securityMode & 0x08 ) == 0x08 ? true : false;
+        maxMpxCount         = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        maxNumberVcs        = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        maxBufferSize       = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+        maxRawSize          = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+        sessionKey          = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+        capabilities        = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+        serverTime          = readTime( buffer, bufferIndex );
+        bufferIndex += 8;
+        serverTimeZone      = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        encryptionKeyLength = buffer[bufferIndex++] & 0xFF;
+        return bufferIndex - start;
+    }
+    int readBytesWireFormat( byte[] buffer,
+                                    int bufferIndex ) {
+        int start = bufferIndex;
+        encryptionKey = new byte[encryptionKeyLength];
+        System.arraycopy( buffer, bufferIndex,
+                        encryptionKey, 0, encryptionKeyLength );
+        bufferIndex += encryptionKeyLength;
 
-               if( byteCount > encryptionKeyLength ) {
-                       int len = 0;
-                       if(( flags2 & FLAGS2_UNICODE ) == FLAGS2_UNICODE ) {
-                               while( buffer[bufferIndex + len] != (byte)0x00 ||
-                                                                                       buffer[bufferIndex + len + 1] != (byte)0x00 ) {
-                                       len += 2;
-                                       if( len > 256 ) {
-                                               throw new RuntimeException( "zero termination not found" );
-                                       }
-                               }
-                               try {
-                                       oemDomainName = new String( buffer, bufferIndex, len, "UnicodeLittle" );
-                               } catch( UnsupportedEncodingException uee ) {
-                                       Log.printStackTrace( "smb exception", uee );
-                               }
-                       } else {
-                               while( buffer[bufferIndex + len] != (byte)0x00 ) {
-                                       len++;
-                                       if( len > 256 ) {
-                                               throw new RuntimeException( "zero termination not found" );
-                                       }
-                               }
-                               try {
-                                       oemDomainName = new String( buffer, bufferIndex, len, ServerMessageBlock.encoding );
-                               } catch( UnsupportedEncodingException uee ) {
-                               }
-                       }
-                       bufferIndex += len;
-               } else {
-                       oemDomainName = new String();
-               }
+        if( byteCount > encryptionKeyLength ) {
+            int len = 0;
+            if(( flags2 & FLAGS2_UNICODE ) == FLAGS2_UNICODE ) {
+                while( buffer[bufferIndex + len] != (byte)0x00 ||
+                                            buffer[bufferIndex + len + 1] != (byte)0x00 ) {
+                    len += 2;
+                    if( len > 256 ) {
+                        throw new RuntimeException( "zero termination not found" );
+                    }
+                }
+                try {
+                    oemDomainName = new String( buffer, bufferIndex, len, "UnicodeLittle" );
+                } catch( UnsupportedEncodingException uee ) {
+                    if( log.level > 1 )
+                        uee.printStackTrace( log );
+                }
+            } else {
+                while( buffer[bufferIndex + len] != (byte)0x00 ) {
+                    len++;
+                    if( len > 256 ) {
+                        throw new RuntimeException( "zero termination not found" );
+                    }
+                }
+                try {
+                    oemDomainName = new String( buffer, bufferIndex, len, ServerMessageBlock.OEM_ENCODING );
+                } catch( UnsupportedEncodingException uee ) {
+                }
+            }
+            bufferIndex += len;
+        } else {
+            oemDomainName = new String();
+        }
 
-               return bufferIndex - start;
-       }
-       public String toString() {
-               return new String( "SmbComNegotiateResponse[" +
-                       super.toString() +
-                       ",wordCount="           + wordCount +
-                       ",dialectIndex="        + dialectIndex +
-                       ",securityMode=0x"      + Log.getHexString( securityMode, 1 ) +
-                       ",security="            + ( security == SECURITY_SHARE ? "share" : "user" ) +
-                       ",encryptedPasswords="  + encryptedPasswords +
-                       ",maxMpxCount="         + maxMpxCount +
-                       ",maxNumberVcs="        + maxNumberVcs +
-                       ",maxBufferSize="       + maxBufferSize +
-                       ",maxRawSize="          + maxRawSize +
-                       ",sessionKey=0x"        + jcifs.util.Log.getHexString( sessionKey, 8 ) +
-                       ",capabilities=0x"      + jcifs.util.Log.getHexString( capabilities, 8 ) +
-                       ",serverTime="          + new Date( serverTime ) +
-                       ",serverTimeZone="      + serverTimeZone +
-                       ",encryptionKeyLength=" + encryptionKeyLength +
-                       ",byteCount="           + byteCount +
-                       ",encryptionKey=0x"     + Log.getHexString( encryptionKey,
-                                                                                               0,
-                                                                                               encryptionKeyLength * 2 ) +
-                       ",oemDomainName="       + oemDomainName + "]" );
-       }
+        return bufferIndex - start;
+    }
+    public String toString() {
+        return new String( "SmbComNegotiateResponse[" +
+            super.toString() +
+            ",wordCount="           + wordCount +
+            ",dialectIndex="        + dialectIndex +
+            ",securityMode=0x"      + Hexdump.toHexString( securityMode, 1 ) +
+            ",security="            + ( security == SECURITY_SHARE ? "share" : "user" ) +
+            ",encryptedPasswords="  + encryptedPasswords +
+            ",maxMpxCount="         + maxMpxCount +
+            ",maxNumberVcs="        + maxNumberVcs +
+            ",maxBufferSize="       + maxBufferSize +
+            ",maxRawSize="          + maxRawSize +
+            ",sessionKey=0x"        + Hexdump.toHexString( sessionKey, 8 ) +
+            ",capabilities=0x"      + Hexdump.toHexString( capabilities, 8 ) +
+            ",serverTime="          + new Date( serverTime ) +
+            ",serverTimeZone="      + serverTimeZone +
+            ",encryptionKeyLength=" + encryptionKeyLength +
+            ",byteCount="           + byteCount +
+            ",encryptionKey=0x"     + Hexdump.toHexString( encryptionKey,
+                                                0,
+                                                encryptionKeyLength * 2 ) +
+            ",oemDomainName="       + oemDomainName + "]" );
+    }
 }
index c02df96..88c8431 100644 (file)
 
 package jcifs.smb;
 
-import jcifs.Config;
 import java.util.Date;
 import java.io.IOException;
 import java.io.InputStream;
+import jcifs.Config;
+import jcifs.util.Hexdump;
 
 class SmbComOpenAndX extends AndXServerMessageBlock {
 
-       // flags (not the same as flags constructor argument)
-       static final int FLAGS_RETURN_ADDITIONAL_INFO = 0x01;
-       static final int FLAGS_REQUEST_OPLOCK         = 0x02;
-       static final int FLAGS_REQUEST_BATCH_OPLOCK   = 0x04;
-
-       // Access Mode Encoding for desiredAccess
-       static final int SHARING_COMPATIBILITY           = 0x00;
-       static final int SHARING_DENY_READ_WRITE_EXECUTE = 0x10;
-       static final int SHARING_DENY_WRITE              = 0x20;
-       static final int SHARING_DENY_READ_EXECUTE       = 0x30;
-       static final int SHARING_DENY_NONE               = 0x40;
-
-       static final int DO_NOT_CACHE  = 0x1000; // bit 12
-       static final int WRITE_THROUGH = 0x4000; // bit 14
-
-       static final int OPEN_FN_CREATE = 0x10;
-       static final int OPEN_FN_FAIL_IF_EXISTS = 0x00;
-       static final int OPEN_FN_OPEN = 0x01;
-       static final int OPEN_FN_TRUNC = 0x02;
-
-       static final int BATCH_LIMIT = Config.getInt( "jcifs.smb.client.OpenAndX.ReadAndX", 1 );
-
-       int flags,
-               desiredAccess,
-               searchAttributes,
-               fileAttributes,
-               creationTime,
-               openFunction,
-               allocationSize;
-
-       // flags is NOT the same as flags member
-
-       SmbComOpenAndX( String fileName, int flags, ServerMessageBlock andx ) {
-               super( andx );
-               this.path = fileName;
-               command = SMB_COM_OPEN_ANDX;
-
-               // desiredAccess
-               desiredAccess = ( flags >>> 16 ) & 0x3;
-               if( desiredAccess == 0x3 ) {
-                       desiredAccess = 0x2; /* Mmm, I thought 0x03 was RDWR */
-               }
-               desiredAccess |= SHARING_DENY_NONE;
-               desiredAccess &= ~0x1; // Win98 doesn't like GENERIC_READ ?! -- get Access Denied.
-
-               // searchAttributes
-               searchAttributes = ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM;
-
-               // fileAttributes
-               fileAttributes = 0;
-
-               // openFunction
-               if(( flags & SmbFile.O_TRUNC ) == SmbFile.O_TRUNC ) {
-                       // truncate the file
-                       if(( flags & SmbFile.O_CREAT ) == SmbFile.O_CREAT ) {
-                               // create it if necessary
-                               openFunction = OPEN_FN_TRUNC | OPEN_FN_CREATE;
-                       } else {
-                               openFunction = OPEN_FN_TRUNC;
-                       }
-               } else {
-                       // don't truncate the file
-                       if(( flags & SmbFile.O_CREAT ) == SmbFile.O_CREAT ) {
-                               // create it if necessary
-                               if(( flags & SmbFile.O_EXCL ) == SmbFile.O_EXCL ) {
-                                       // fail if already exists
-                                       openFunction = OPEN_FN_CREATE | OPEN_FN_FAIL_IF_EXISTS;
-                               } else {
-                                       openFunction = OPEN_FN_CREATE | OPEN_FN_OPEN;
-                               }
-                       } else {
-                               openFunction = OPEN_FN_OPEN;
-                       }
-               }
-       }
-
-       int getBatchLimit( byte command ) {
-               return command == SMB_COM_READ_ANDX ? BATCH_LIMIT : 0;
-       }
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-
-               writeInt2( flags, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( desiredAccess, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( searchAttributes, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( fileAttributes, dst, dstIndex );
-               dstIndex += 2;
-               creationTime = 0;
-               writeInt4( creationTime, dst, dstIndex );
-               dstIndex += 4;
-               writeInt2( openFunction, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( allocationSize, dst, dstIndex );
-               dstIndex += 4;
-               for( int i = 0; i < 8; i++ ) {
-                       dst[dstIndex++] = 0x00;
-               }
-
-               return dstIndex - start;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-
-               if( useUnicode ) {
-                       dst[dstIndex++] = (byte)'\0';
-               }
-               dstIndex += writeString( path, dst, dstIndex );
-
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComOpenAndX[" +
-                       super.toString() +
-                       ",flags=0x" + Log.getHexString( flags, 2 ) +
-                       ",desiredAccess=0x" + Log.getHexString( desiredAccess, 4 ) +
-                       ",searchAttributes=0x" + Log.getHexString( searchAttributes, 4 ) +
-                       ",fileAttributes=0x" + Log.getHexString( fileAttributes, 4 ) +
-                       ",creationTime=" + new Date( creationTime ) +
-                       ",openFunction=0x" + Log.getHexString( openFunction, 2 ) +
-                       ",allocationSize=" + allocationSize +
-                       ",fileName=" + path + "]" );
-       }
+    // flags (not the same as flags constructor argument)
+    private static final int FLAGS_RETURN_ADDITIONAL_INFO = 0x01;
+    private static final int FLAGS_REQUEST_OPLOCK         = 0x02;
+    private static final int FLAGS_REQUEST_BATCH_OPLOCK   = 0x04;
+
+    // Access Mode Encoding for desiredAccess
+    private static final int SHARING_COMPATIBILITY           = 0x00;
+    private static final int SHARING_DENY_READ_WRITE_EXECUTE = 0x10;
+    private static final int SHARING_DENY_WRITE              = 0x20;
+    private static final int SHARING_DENY_READ_EXECUTE       = 0x30;
+    private static final int SHARING_DENY_NONE               = 0x40;
+
+    private static final int DO_NOT_CACHE  = 0x1000; // bit 12
+    private static final int WRITE_THROUGH = 0x4000; // bit 14
+
+    private static final int OPEN_FN_CREATE = 0x10;
+    private static final int OPEN_FN_FAIL_IF_EXISTS = 0x00;
+    private static final int OPEN_FN_OPEN = 0x01;
+    private static final int OPEN_FN_TRUNC = 0x02;
+
+    private static final int BATCH_LIMIT = Config.getInt( "jcifs.smb.client.OpenAndX.ReadAndX", 1 );
+
+    int flags,
+        desiredAccess,
+        searchAttributes,
+        fileAttributes,
+        creationTime,
+        openFunction,
+        allocationSize;
+
+    // flags is NOT the same as flags member
+
+    SmbComOpenAndX( String fileName, int flags, ServerMessageBlock andx ) {
+        super( andx );
+        this.path = fileName;
+        command = SMB_COM_OPEN_ANDX;
+
+        // desiredAccess
+        desiredAccess = ( flags >>> 16 ) & 0x3;
+        if( desiredAccess == 0x3 ) {
+            desiredAccess = 0x2; /* Mmm, I thought 0x03 was RDWR */
+        }
+        desiredAccess |= SHARING_DENY_NONE;
+        desiredAccess &= ~0x1; // Win98 doesn't like GENERIC_READ ?! -- get Access Denied.
+
+        // searchAttributes
+        searchAttributes = ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM;
+
+        // fileAttributes
+        fileAttributes = 0;
+
+        // openFunction
+        if(( flags & SmbFile.O_TRUNC ) == SmbFile.O_TRUNC ) {
+            // truncate the file
+            if(( flags & SmbFile.O_CREAT ) == SmbFile.O_CREAT ) {
+                // create it if necessary
+                openFunction = OPEN_FN_TRUNC | OPEN_FN_CREATE;
+            } else {
+                openFunction = OPEN_FN_TRUNC;
+            }
+        } else {
+            // don't truncate the file
+            if(( flags & SmbFile.O_CREAT ) == SmbFile.O_CREAT ) {
+                // create it if necessary
+                if(( flags & SmbFile.O_EXCL ) == SmbFile.O_EXCL ) {
+                    // fail if already exists
+                    openFunction = OPEN_FN_CREATE | OPEN_FN_FAIL_IF_EXISTS;
+                } else {
+                    openFunction = OPEN_FN_CREATE | OPEN_FN_OPEN;
+                }
+            } else {
+                openFunction = OPEN_FN_OPEN;
+            }
+        }
+    }
+
+    int getBatchLimit( byte command ) {
+        return command == SMB_COM_READ_ANDX ? BATCH_LIMIT : 0;
+    }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+
+        writeInt2( flags, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( desiredAccess, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( searchAttributes, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( fileAttributes, dst, dstIndex );
+        dstIndex += 2;
+        creationTime = 0;
+        writeInt4( creationTime, dst, dstIndex );
+        dstIndex += 4;
+        writeInt2( openFunction, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( allocationSize, dst, dstIndex );
+        dstIndex += 4;
+        for( int i = 0; i < 8; i++ ) {
+            dst[dstIndex++] = 0x00;
+        }
+
+        return dstIndex - start;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+
+        if( useUnicode ) {
+            dst[dstIndex++] = (byte)'\0';
+        }
+        dstIndex += writeString( path, dst, dstIndex );
+
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComOpenAndX[" +
+            super.toString() +
+            ",flags=0x" + Hexdump.toHexString( flags, 2 ) +
+            ",desiredAccess=0x" + Hexdump.toHexString( desiredAccess, 4 ) +
+            ",searchAttributes=0x" + Hexdump.toHexString( searchAttributes, 4 ) +
+            ",fileAttributes=0x" + Hexdump.toHexString( fileAttributes, 4 ) +
+            ",creationTime=" + new Date( creationTime ) +
+            ",openFunction=0x" + Hexdump.toHexString( openFunction, 2 ) +
+            ",allocationSize=" + allocationSize +
+            ",fileName=" + path + "]" );
+    }
 }
index 727b6ad..3fd6123 100644 (file)
@@ -23,66 +23,67 @@ import java.io.InputStream;
 
 class SmbComOpenAndXResponse extends AndXServerMessageBlock {
 
-       int fid,
-               fileAttributes,
-               dataSize,
-               grantedAccess,
-               fileType,
-               deviceState,
-               action,
-               serverFid;
-       long lastWriteTime;
+    int fid,
+        fileAttributes,
+        dataSize,
+        grantedAccess,
+        fileType,
+        deviceState,
+        action,
+        serverFid;
+    long lastWriteTime;
 
-       SmbComOpenAndXResponse() {
-       }
+    SmbComOpenAndXResponse() {
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               int start = bufferIndex;
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        int start = bufferIndex;
 
-               fid = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               fileAttributes = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               lastWriteTime = readUTime( buffer, bufferIndex );
-               bufferIndex += 4;
-               dataSize = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-               grantedAccess = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               fileType = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               deviceState = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               action = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               serverFid = readInt4( buffer, bufferIndex );
-               bufferIndex += 6;
+        fid = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        fileAttributes = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        lastWriteTime = readUTime( buffer, bufferIndex );
+        bufferIndex += 4;
+        dataSize = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+        grantedAccess = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        fileType = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        deviceState = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        action = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        serverFid = readInt4( buffer, bufferIndex );
+        bufferIndex += 6;
 
-               return bufferIndex - start;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComOpenAndXResponse[" +
-                       super.toString() +
-                       ",fid=" + fid +
-                       ",fileAttributes=" + fileAttributes +
-                       ",lastWriteTime=" + lastWriteTime +
-                       ",dataSize=" + dataSize +
-                       ",grantedAccess=" + grantedAccess +
-                       ",fileType=" + fileType +
-                       ",deviceState=" + deviceState +
-                       ",action=" + action +
-                       ",serverFid=" + serverFid + "]" );
-       }
+        return bufferIndex - start;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComOpenAndXResponse[" +
+            super.toString() +
+            ",fid=" + fid +
+            ",fileAttributes=" + fileAttributes +
+            ",lastWriteTime=" + lastWriteTime +
+            ",dataSize=" + dataSize +
+            ",grantedAccess=" + grantedAccess +
+            ",fileType=" + fileType +
+            ",deviceState=" + deviceState +
+            ",action=" + action +
+            ",serverFid=" + serverFid + "]" );
+    }
 }
index f6b0615..ca4ea7e 100644 (file)
@@ -20,30 +20,30 @@ package jcifs.smb;
 
 class SmbComQueryInformation extends ServerMessageBlock {
 
-       SmbComQueryInformation( String filename ) {
-               path = filename;
-               command = SMB_COM_QUERY_INFORMATION;
-       }
+    SmbComQueryInformation( String filename ) {
+        path = filename;
+        command = SMB_COM_QUERY_INFORMATION;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-               dst[dstIndex++] = (byte)0x04;
-               dstIndex += writeString( path, dst, dstIndex );
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComQueryInformation[" +
-                       super.toString() +
-                       ",filename=" + path + "]" );
-       }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+        dst[dstIndex++] = (byte)0x04;
+        dstIndex += writeString( path, dst, dstIndex );
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComQueryInformation[" +
+            super.toString() +
+            ",filename=" + path + "]" );
+    }
 }
 
index 7a0a301..977b77b 100644 (file)
 package jcifs.smb;
 
 import java.util.Date;
+import jcifs.util.Hexdump;
 
 class SmbComQueryInformationResponse extends ServerMessageBlock implements Info {
 
-       int fileAttributes = 0x0000;
-       long lastWriteTime = 0L;
-       long serverTimeZoneOffset;
-       int fileSize = 0;
+    private int fileAttributes = 0x0000;
+    private long lastWriteTime = 0L;
+    private long serverTimeZoneOffset;
+    private int fileSize = 0;
 
-       SmbComQueryInformationResponse( long serverTimeZoneOffset ) {
-               this.serverTimeZoneOffset = serverTimeZoneOffset;
-               command = SMB_COM_QUERY_INFORMATION;
-       }
+    SmbComQueryInformationResponse( long serverTimeZoneOffset ) {
+        this.serverTimeZoneOffset = serverTimeZoneOffset;
+        command = SMB_COM_QUERY_INFORMATION;
+    }
 
-       public int getAttributes() {
-               return fileAttributes;
-       }
-       public long getCreateTime() {
-               return lastWriteTime + serverTimeZoneOffset;
-       }
-       public long getLastWriteTime() {
-               return lastWriteTime + serverTimeZoneOffset;
-       }
-       public long getSize() {
-               return fileSize;
-       }
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               if( wordCount == 0 ) {
-                       return 0;
-               }
-               fileAttributes = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               lastWriteTime = readUTime( buffer, bufferIndex );
-               bufferIndex += 4;
-               fileSize = readInt4( buffer, bufferIndex );
-               return 20;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComQueryInformationResponse[" +
-                       super.toString() +
-                       ",fileAttributes=0x" + Log.getHexString( fileAttributes, 4 ) +
-                       ",lastWriteTime=" + new Date( lastWriteTime ) +
-                       ",fileSize=" + fileSize + "]" );
-       }
+    public int getAttributes() {
+        return fileAttributes;
+    }
+    public long getCreateTime() {
+        return lastWriteTime + serverTimeZoneOffset;
+    }
+    public long getLastWriteTime() {
+        return lastWriteTime + serverTimeZoneOffset;
+    }
+    public long getSize() {
+        return fileSize;
+    }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        if( wordCount == 0 ) {
+            return 0;
+        }
+        fileAttributes = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        lastWriteTime = readUTime( buffer, bufferIndex );
+        bufferIndex += 4;
+        fileSize = readInt4( buffer, bufferIndex );
+        return 20;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComQueryInformationResponse[" +
+            super.toString() +
+            ",fileAttributes=0x" + Hexdump.toHexString( fileAttributes, 4 ) +
+            ",lastWriteTime=" + new Date( lastWriteTime ) +
+            ",fileSize=" + fileSize + "]" );
+    }
 }
 
index 6e93c6c..c231c68 100644 (file)
@@ -24,79 +24,80 @@ import java.io.IOException;
 
 class SmbComReadAndX extends AndXServerMessageBlock {
 
-       static final int BATCH_LIMIT = Config.getInt( "jcifs.smb.client.ReadAndX.Close", 1 );
+    private static final int BATCH_LIMIT = Config.getInt( "jcifs.smb.client.ReadAndX.Close", 1 );
 
-       long offset;
-       int fid,
-               maxCount,
-               minCount,
-               openTimeout,
-               remaining;
+    private long offset;
+    private int fid,
+        maxCount,
+        minCount,
+        openTimeout,
+        remaining;
 
-       SmbComReadAndX() {
-               super( null );
-               command = SMB_COM_READ_ANDX;
-               openTimeout = 0xFFFFFFFF;
-       }
-       SmbComReadAndX( int fid, long offset, int maxCount, ServerMessageBlock andx ) {
-               super( andx );
-               this.fid = fid;
-               this.offset = offset;
-               this.maxCount = minCount = maxCount;
-               command = SMB_COM_READ_ANDX;
-               openTimeout = 0xFFFFFFFF;
-       }
+    SmbComReadAndX() {
+        super( null );
+        command = SMB_COM_READ_ANDX;
+        openTimeout = 0xFFFFFFFF;
+    }
+    SmbComReadAndX( int fid, long offset, int maxCount, ServerMessageBlock andx ) {
+        super( andx );
+        this.fid = fid;
+        this.offset = offset;
+        this.maxCount = minCount = maxCount;
+        command = SMB_COM_READ_ANDX;
+        openTimeout = 0xFFFFFFFF;
+    }
 
-       void setParam( int fid, long offset, int maxCount ) {
-               this.fid = fid;
-               this.offset = offset;
-               this.maxCount = minCount = maxCount;
-       }
-       int getBatchLimit( byte command ) {
-               return command == SMB_COM_CLOSE ? BATCH_LIMIT : 0;
-       }
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    void setParam( int fid, long offset, int maxCount ) {
+        this.fid = fid;
+        this.offset = offset;
+        this.maxCount = minCount = maxCount;
+    }
+    int getBatchLimit( byte command ) {
+        return command == SMB_COM_CLOSE ? BATCH_LIMIT : 0;
+    }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               writeInt2( fid, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( offset, dst, dstIndex );
-               dstIndex += 4;
-               writeInt2( maxCount, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( minCount, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( openTimeout, dst, dstIndex );
-               dstIndex += 4;
-               writeInt2( remaining, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( offset >> 32, dst, dstIndex );
-               dstIndex += 4;
+        writeInt2( fid, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( offset, dst, dstIndex );
+        dstIndex += 4;
+        writeInt2( maxCount, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( minCount, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( openTimeout, dst, dstIndex );
+        dstIndex += 4;
+        writeInt2( remaining, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( offset >> 32, dst, dstIndex );
+        dstIndex += 4;
 
-               return dstIndex - start;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComReadAndX[" +
-                       super.toString() +
-                       ",fid=" + fid +
-                       ",offset=" + offset +
-                       ",maxCount=" + maxCount +
-                       ",minCount=" + minCount +
-                       ",openTimeout=" + openTimeout +
-                       ",remaining=" + remaining +
-                       ",offset=" + maxCount +
-                        "]" );
-       }
+        return dstIndex - start;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComReadAndX[" +
+            super.toString() +
+            ",fid=" + fid +
+            ",offset=" + offset +
+            ",maxCount=" + maxCount +
+            ",minCount=" + minCount +
+            ",openTimeout=" + openTimeout +
+            ",remaining=" + remaining +
+            ",offset=" + maxCount +
+             "]" );
+    }
 }
index 712e0fe..e8a7cdc 100644 (file)
@@ -23,57 +23,56 @@ import java.io.InputStream;
 
 class SmbComReadAndXResponse extends AndXServerMessageBlock {
 
-       byte[] b;
-       int dataCompactionMode,
-               dataLength,
-               dataOffset,
-               off;
+    private int dataCompactionMode, dataOffset;
 
-       SmbComReadAndXResponse() {
-       }
-       SmbComReadAndXResponse( byte[] b, int off ) {
-               this.b = b;
-               this.off = off;
-       }
+    byte[] b;
+    int dataLength, off;
 
-       void setParam( byte[] b, int off ) {
-               this.b = b;
-               this.off = off;
-       }
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               int start = bufferIndex;
+    SmbComReadAndXResponse() {
+    }
+    SmbComReadAndXResponse( byte[] b, int off ) {
+        this.b = b;
+        this.off = off;
+    }
 
-               bufferIndex += 2; // reserved
-               dataCompactionMode = readInt2( buffer, bufferIndex );
-               bufferIndex += 4; // 2 reserved
-               dataLength = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               dataOffset = readInt2( buffer, bufferIndex );
-               bufferIndex += 12; // 10 reserved
+    void setParam( byte[] b, int off ) {
+        this.b = b;
+        this.off = off;
+    }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        int start = bufferIndex;
 
-               return bufferIndex - start;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
+        bufferIndex += 2; // reserved
+        dataCompactionMode = readInt2( buffer, bufferIndex );
+        bufferIndex += 4; // 2 reserved
+        dataLength = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        dataOffset = readInt2( buffer, bufferIndex );
+        bufferIndex += 12; // 10 reserved
 
-               int pad = dataOffset - ( HEADER_LENGTH + 3 + wordCount * 2 );
-               in.skip( pad );
-               in.read( b, off, dataLength );
-               return pad + dataLength;
-       }
-       public String toString() {
-               return new String( "SmbComReadAndXResponse[" +
-                       super.toString() +
-                       ",dataCompactionMode=" + dataCompactionMode +
-                       ",dataLength=" + dataLength +
-                       ",dataOffset=" + dataOffset + "]" );
-       }
+        return bufferIndex - start;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        int pad = dataOffset - ( HEADER_LENGTH + 3 + wordCount * 2 );
+        in.read( buffer, bufferIndex, pad ); /* needed for signing */
+        in.read( b, off, dataLength );
+        return dataLength;
+    }
+    public String toString() {
+        return new String( "SmbComReadAndXResponse[" +
+            super.toString() +
+            ",dataCompactionMode=" + dataCompactionMode +
+            ",dataLength=" + dataLength +
+            ",dataOffset=" + dataOffset + "]" );
+    }
 }
index 7a53da2..5fa8914 100644 (file)
 
 package jcifs.smb;
 
+import jcifs.util.Hexdump;
+
 class SmbComRename extends ServerMessageBlock {
 
-       int searchAttributes;
-       String oldFileName;
-       String newFileName;
+    private int searchAttributes;
+    private String oldFileName;
+    private String newFileName;
 
-       SmbComRename( String oldFileName, String newFileName ) {
-               command = SMB_COM_RENAME;
-               this.oldFileName = oldFileName;
-               this.newFileName = newFileName;
-               searchAttributes = ATTR_HIDDEN | ATTR_SYSTEM | ATTR_DIRECTORY;
-       }
+    SmbComRename( String oldFileName, String newFileName ) {
+        command = SMB_COM_RENAME;
+        this.oldFileName = oldFileName;
+        this.newFileName = newFileName;
+        searchAttributes = ATTR_HIDDEN | ATTR_SYSTEM | ATTR_DIRECTORY;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               writeInt2( searchAttributes, dst, dstIndex );
-               return 2;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        writeInt2( searchAttributes, dst, dstIndex );
+        return 2;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               dst[dstIndex++] = (byte)0x04;
-               dstIndex += writeString( oldFileName, dst, dstIndex );
-               dst[dstIndex++] = (byte)0x04;
-               if( useUnicode ) {
-                       dst[dstIndex++] = (byte)'\0';
-               }
-               dstIndex += writeString( newFileName, dst, dstIndex );
+        dst[dstIndex++] = (byte)0x04;
+        dstIndex += writeString( oldFileName, dst, dstIndex );
+        dst[dstIndex++] = (byte)0x04;
+        if( useUnicode ) {
+            dst[dstIndex++] = (byte)'\0';
+        }
+        dstIndex += writeString( newFileName, dst, dstIndex );
 
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComRename[" +
-                       super.toString() +
-                       ",searchAttributes=0x" + Log.getHexString( searchAttributes, 4 ) +
-                       ",oldFileName=" + oldFileName +
-                       ",newFileName=" + newFileName + "]" );
-       }
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComRename[" +
+            super.toString() +
+            ",searchAttributes=0x" + Hexdump.toHexString( searchAttributes, 4 ) +
+            ",oldFileName=" + oldFileName +
+            ",newFileName=" + newFileName + "]" );
+    }
 }
index 90918e0..4cc0676 100644 (file)
@@ -24,149 +24,135 @@ import java.io.InputStream;
 
 class SmbComSessionSetupAndX extends AndXServerMessageBlock {
 
-       static final int BATCH_LIMIT =
-                       Config.getInt( "jcifs.smb.client.SessionSetupAndX.TreeConnectAndX", 1 );
-
-       byte[] accountPassword, unicodePassword;
-       int passwordLength, unicodePasswordLength;
-       int negotiatedMaxBufferSize,
-               negotiatedMaxMpxCount,
-               vcNumber,
-               sessionKey;
-       String accountName,
-               primaryDomain,
-               nativeOs,
-               nativeLanMan;
-
-       SmbSession session;
-
-       SmbComSessionSetupAndX( SmbSession session, ServerMessageBlock andx ) {
-               super( andx );
-               command = SMB_COM_SESSION_SETUP_ANDX;
-               this.session = session;
-       }
-
-       int getBatchLimit( byte command ) {
-               return command == SMB_COM_TREE_CONNECT_ANDX ? BATCH_LIMIT : 0;
-       }
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-
-               if( session.transport.server.security == SECURITY_USER &&
-                                               ( session.auth.hashesExternal ||
-                                               session.auth.password.length() > 0 )) {
-                       if( session.transport.server.encryptedPasswords ) {
-                               // encrypted
-                               accountPassword = session.auth.getAnsiHash( session.transport.server.encryptionKey );
-                               unicodePassword = session.auth.getUnicodeHash( session.transport.server.encryptionKey );
-                               passwordLength = unicodePasswordLength = 24;
-                               // fix for win9x clients
-                               if (unicodePassword.length == 0) unicodePasswordLength = 0;
-                       } else if( Config.getBoolean( "jcifs.smb.client.disablePlainTextPasswords", true )) {
-                               throw new RuntimeException( "Plain text passwords are disabled" );
-                       } else if( useUnicode ) {
-                               // plain text
-                               String password = session.auth.getPassword();
-                               accountPassword = new byte[0];
-                               passwordLength = 0;
-                               unicodePassword = new byte[(password.length() + 1) * 2];
-                               unicodePasswordLength = writeString( password, unicodePassword, 0 );
-                       } else {
-                               // plain text
-                               String password = session.auth.getPassword();
-                               accountPassword = new byte[(password.length() + 1) * 2];
-                               passwordLength = writeString( password, accountPassword, 0 );
-                               unicodePassword = new byte[0];
-                               unicodePasswordLength = 0;
-                       }
-               } else {
-                       // no password in session setup
-                       passwordLength = unicodePasswordLength = 0;
-               }
-
-               negotiatedMaxBufferSize = session.transport.negotiatedMaxBufferSize;
-               negotiatedMaxMpxCount = session.transport.negotiatedMaxMpxCount;
-               vcNumber = session.transport.client.vcNumber;
-               sessionKey = session.transport.client.sessionKey;
-
-               writeInt2( negotiatedMaxBufferSize, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( negotiatedMaxMpxCount, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( vcNumber, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( sessionKey, dst, dstIndex );
-               dstIndex += 4;
-               writeInt2( passwordLength, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( unicodePasswordLength, dst, dstIndex );
-               dstIndex += 2;
-               dst[dstIndex++] = (byte)0x00;
-               dst[dstIndex++] = (byte)0x00;
-               dst[dstIndex++] = (byte)0x00;
-               dst[dstIndex++] = (byte)0x00;
-               writeInt4( session.transport.client.capabilities, dst, dstIndex );
-               dstIndex += 4;
-
-               return dstIndex - start;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-
-               accountName = session.auth.username.toUpperCase();
-               primaryDomain = session.auth.domain.toUpperCase();
-               nativeOs = session.transport.client.nativeOs;
-               nativeLanMan = session.transport.client.nativeLanMan;
-
-               if( session.transport.server.security == SECURITY_USER &&
-                                               ( session.auth.hashesExternal ||
-                                               session.auth.password.length() > 0 )) {
-                       System.arraycopy( accountPassword, 0, dst, dstIndex, passwordLength );
-                       dstIndex += passwordLength;
-                       System.arraycopy( unicodePassword, 0, dst, dstIndex, unicodePasswordLength );
-                       dstIndex += unicodePasswordLength;
-               }
-               if( useUnicode ) {
-                       // at least NT 4 observed needing this only with unicode
-                       dst[dstIndex++] = (byte)'\0';
-               }
-
-               dstIndex += writeString( accountName, dst, dstIndex );
-               dstIndex += writeString( primaryDomain, dst, dstIndex );
-               dstIndex += writeString( nativeOs, dst, dstIndex );
-/*
-               // at least NT 4 observed with 2 zero bytes here
-               dst[dstIndex++] = (byte)0x00;
-               dst[dstIndex++] = (byte)0x00;
-This still isn't quite right.
-*/
-               dstIndex += writeString( nativeLanMan, dst, dstIndex );
-
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               String result = new String( "SmbComSessionSetupAndX[" +
-                       super.toString() +
-                       ",maxBufferSize=" + negotiatedMaxBufferSize +
-                       ",maxMpxCount=" + negotiatedMaxMpxCount +
-                       ",vcNumber=" + vcNumber +
-                       ",sessionKey=" + sessionKey +
-                       ",passwordLength=" + passwordLength +
-                       ",unicodePasswordLength=" + unicodePasswordLength +
-                       ",capabilities=" + session.transport.client.capabilities +
-                       ",accountName=" + accountName +
-                       ",primaryDomain=" + primaryDomain +
-                       ",nativeOs=" + nativeOs +
-                       ",nativeLanMan=" + nativeLanMan + "]" );
-               return result;
-       }
+    private static final int BATCH_LIMIT =
+            Config.getInt( "jcifs.smb.client.SessionSetupAndX.TreeConnectAndX", 1 );
+    private static final boolean DISABLE_PLAIN_TEXT_PASSWORDS =
+            Config.getBoolean( "jcifs.smb.client.disablePlainTextPasswords", true );
+
+    private byte[] accountPassword, unicodePassword;
+    private int passwordLength, unicodePasswordLength;
+    private int sessionKey;
+    private String accountName, primaryDomain;
+
+    SmbSession session;
+
+    SmbComSessionSetupAndX( SmbSession session, ServerMessageBlock andx ) {
+        super( andx );
+        command = SMB_COM_SESSION_SETUP_ANDX;
+        this.session = session;
+    }
+
+    int getBatchLimit( byte command ) {
+        return command == SMB_COM_TREE_CONNECT_ANDX ? BATCH_LIMIT : 0;
+    }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+
+        if( session.transport.server.security == SECURITY_USER &&
+                        ( session.auth.hashesExternal ||
+                        session.auth.password.length() > 0 )) {
+            if( session.transport.server.encryptedPasswords ) {
+                // encrypted
+                accountPassword = session.auth.getAnsiHash( session.transport.server.encryptionKey );
+                unicodePassword = session.auth.getUnicodeHash( session.transport.server.encryptionKey );
+                passwordLength = unicodePasswordLength = 24;
+                // fix for win9x clients
+                if (unicodePassword.length == 0) unicodePasswordLength = 0;
+            } else if( DISABLE_PLAIN_TEXT_PASSWORDS ) {
+                throw new RuntimeException( "Plain text passwords are disabled" );
+            } else if( useUnicode ) {
+                // plain text
+                String password = session.auth.getPassword();
+                accountPassword = new byte[0];
+                passwordLength = 0;
+                unicodePassword = new byte[(password.length() + 1) * 2];
+                unicodePasswordLength = writeString( password, unicodePassword, 0 );
+            } else {
+                // plain text
+                String password = session.auth.getPassword();
+                accountPassword = new byte[(password.length() + 1) * 2];
+                passwordLength = writeString( password, accountPassword, 0 );
+                unicodePassword = new byte[0];
+                unicodePasswordLength = 0;
+            }
+        } else {
+            // no password in session setup
+            passwordLength = unicodePasswordLength = 0;
+        }
+
+        sessionKey = session.transport.sessionKey;
+
+        writeInt2( session.transport.snd_buf_size, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( session.transport.maxMpxCount, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( session.transport.VC_NUMBER, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( sessionKey, dst, dstIndex );
+        dstIndex += 4;
+        writeInt2( passwordLength, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( unicodePasswordLength, dst, dstIndex );
+        dstIndex += 2;
+        dst[dstIndex++] = (byte)0x00;
+        dst[dstIndex++] = (byte)0x00;
+        dst[dstIndex++] = (byte)0x00;
+        dst[dstIndex++] = (byte)0x00;
+        writeInt4( session.transport.capabilities, dst, dstIndex );
+        dstIndex += 4;
+
+        return dstIndex - start;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+
+        accountName = session.auth.username.toUpperCase();
+        primaryDomain = session.auth.domain.toUpperCase();
+
+        if( session.transport.server.security == SECURITY_USER &&
+                        ( session.auth.hashesExternal ||
+                        session.auth.password.length() > 0 )) {
+            System.arraycopy( accountPassword, 0, dst, dstIndex, passwordLength );
+            dstIndex += passwordLength;
+            System.arraycopy( unicodePassword, 0, dst, dstIndex, unicodePasswordLength );
+            dstIndex += unicodePasswordLength;
+        }
+        if( useUnicode ) {
+            // at least NT 4 observed needing this only with unicode
+            dst[dstIndex++] = (byte)'\0';
+        }
+
+        dstIndex += writeString( accountName, dst, dstIndex );
+        dstIndex += writeString( primaryDomain, dst, dstIndex );
+        dstIndex += writeString( session.transport.NATIVE_OS, dst, dstIndex );
+        dstIndex += writeString( session.transport.NATIVE_LANMAN, dst, dstIndex );
+
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        String result = new String( "SmbComSessionSetupAndX[" +
+            super.toString() +
+            ",snd_buf_size=" + session.transport.snd_buf_size +
+            ",maxMpxCount=" + session.transport.maxMpxCount +
+            ",VC_NUMBER=" + session.transport.VC_NUMBER +
+            ",sessionKey=" + sessionKey +
+            ",passwordLength=" + passwordLength +
+            ",unicodePasswordLength=" + unicodePasswordLength +
+            ",capabilities=" + session.transport.capabilities +
+            ",accountName=" + accountName +
+            ",primaryDomain=" + primaryDomain +
+            ",NATIVE_OS=" + session.transport.NATIVE_OS +
+            ",NATIVE_LANMAN=" + session.transport.NATIVE_LANMAN + "]" );
+        return result;
+    }
 }
index b6efa9b..a379d8b 100644 (file)
@@ -22,74 +22,78 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
 
+import jcifs.util.Hexdump;
+
 class SmbComSessionSetupAndXResponse extends AndXServerMessageBlock {
 
-       boolean isLoggedInAsGuest;
-       String nativeOs = "";
-       String nativeLanMan = "";
-       String primaryDomain = "";
+    private boolean isLoggedInAsGuest;
+    private String nativeOs = "";
+    private String nativeLanMan = "";
+    private String primaryDomain = "";
 
-       SmbComSessionSetupAndXResponse( ServerMessageBlock andx ) {
-               super( andx );
-       }
+    SmbComSessionSetupAndXResponse( ServerMessageBlock andx ) {
+        super( andx );
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               isLoggedInAsGuest = ( buffer[bufferIndex] & 0x01 ) == 0x01 ? true : false;
-               return 2;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               int start = bufferIndex;
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        isLoggedInAsGuest = ( buffer[bufferIndex] & 0x01 ) == 0x01 ? true : false;
+        return 2;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        int start = bufferIndex;
 
-               nativeOs = readString( buffer, bufferIndex );
-               bufferIndex += stringWireLength( nativeOs, bufferIndex );
-               nativeLanMan = readString( buffer, bufferIndex );
-               bufferIndex += stringWireLength( nativeLanMan, bufferIndex );
+        nativeOs = readString( buffer, bufferIndex );
+        bufferIndex += stringWireLength( nativeOs, bufferIndex );
+        nativeLanMan = readString( buffer, bufferIndex );
+        bufferIndex += stringWireLength( nativeLanMan, bufferIndex );
 
-               if( useUnicode ) {
-                       int len;
+        if( useUnicode ) {
+            int len;
 
-                       if((( bufferIndex - headerStart ) % 2 ) != 0 ) {
-                               bufferIndex++;
-                       }
+            if((( bufferIndex - headerStart ) % 2 ) != 0 ) {
+                bufferIndex++;
+            }
 
-                       len = 0;
-                       while( buffer[bufferIndex + len] != (byte)0x00 ) {
-                               len += 2;
-                               if( len > 256 ) {
-jcifs.util.Log.printHexDump( System.err, buffer, 0, 256 );
-                                       throw new RuntimeException( "zero termination not found" );
-                               }
-                       }
-                       try {
-                               primaryDomain = new String( buffer, bufferIndex, len, "UnicodeLittle" );
-                       } catch( UnsupportedEncodingException uee ) {
-                               Log.printStackTrace( "smb exception", uee );
-                       }
-                       bufferIndex += len;
-               } else {
-                       primaryDomain = readString( buffer, bufferIndex );
-                       bufferIndex += stringWireLength( primaryDomain, bufferIndex );
-               }
+            len = 0;
+            while( buffer[bufferIndex + len] != (byte)0x00 ) {
+                len += 2;
+                if( len > 256 ) {
+Hexdump.hexdump( System.err, buffer, 0, 256 );
+                    throw new RuntimeException( "zero termination not found" );
+                }
+            }
+            try {
+                primaryDomain = new String( buffer, bufferIndex, len, "UnicodeLittle" );
+            } catch( UnsupportedEncodingException uee ) {
+                if( log.level > 1 )
+                    uee.printStackTrace( log );
+            }
+            bufferIndex += len;
+        } else {
+            primaryDomain = readString( buffer, bufferIndex );
+            bufferIndex += stringWireLength( primaryDomain, bufferIndex );
+        }
 
-               return bufferIndex - start;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               String result = new String( "SmbComSessionSetupAndXResponse[" +
-                       super.toString() +
-                       ",isLoggedInAsGuest=" + isLoggedInAsGuest +
-                       ",nativeOs=" + nativeOs +
-                       ",nativeLanMan=" + nativeLanMan +
-                       ",primaryDomain=" + primaryDomain + "]" );
-               return result;
-       }
+        return bufferIndex - start;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        String result = new String( "SmbComSessionSetupAndXResponse[" +
+            super.toString() +
+            ",isLoggedInAsGuest=" + isLoggedInAsGuest +
+            ",nativeOs=" + nativeOs +
+            ",nativeLanMan=" + nativeLanMan +
+            ",primaryDomain=" + primaryDomain + "]" );
+        return result;
+    }
 }
 
index 5dd62d0..cdc8db5 100644 (file)
@@ -20,243 +20,246 @@ package jcifs.smb;
 
 import java.util.Enumeration;
 import jcifs.Config;
+import jcifs.util.Hexdump;
 
 abstract class SmbComTransaction extends ServerMessageBlock implements Enumeration {
 
-       static final byte TRANS2_FIND_FIRST2            = (byte)0x01;
-       static final byte TRANS2_FIND_NEXT2             = (byte)0x02;
-       static final byte TRANS2_QUERY_FS_INFORMATION   = (byte)0x03;
-       static final byte TRANS2_QUERY_PATH_INFORMATION = (byte)0x05;
-       static final byte TRANS2_GET_DFS_REFERRAL       = (byte)0x10;
-       static final byte TRANS2_SET_FILE_INFORMATION   = (byte)0x08;
-
-       static final int NET_SHARE_ENUM   = 0x0000;
-       static final int NET_SERVER_ENUM2 = 0x0068;
-
-       static final byte TRANS_PEEK_NAMED_PIPE     = (byte)0x23;
-       static final byte TRANS_WAIT_NAMED_PIPE     = (byte)0x53;
-       static final byte TRANS_CALL_NAMED_PIPE     = (byte)0x54;
-       static final byte TRANS_TRANSACT_NAMED_PIPE = (byte)0x26;
-
-       // relative to headerStart
-       static final int PRIMARY_SETUP_OFFSET        = 61;
-       static final int SECONDARY_PARAMETER_OFFSET  = 51;
-
-       static final int DISCONNECT_TID      = 0x01;
-       static final int ONE_WAY_TRANSACTION = 0x02;
-
-       static final int PADDING_SIZE = 2;
-
-       static final int TRANSACTION_BUF_SIZE = 0xFFFF;
-
-       int totalParameterCount;
-       int totalDataCount;
-       int maxParameterCount;
-       int maxDataCount;
-       byte maxSetupCount;
-       int flags = 0x00;
-       int timeout = 0;
-       int parameterCount;
-       int parameterOffset;
-       int parameterDisplacement;
-       int dataCount;
-       int dataOffset;
-       int dataDisplacement;
-       int fid;
-       int setupCount = 1;
-       byte subCommand;
-       String name = "";
-       int pad = 0;
-       int pad1 = 0;
-       boolean hasMore = true;
-       boolean isPrimary = true;
-       int maxBufferSize; // set in SmbTransport.sendTransaction() before nextElement called
-
-       byte[] txn_buf;
-       int bufParameterOffset;
-       int bufDataOffset;
-
-       SmbComTransaction() {
-               maxParameterCount = 1024;
-               // subtract 512 just to be safe
-               maxDataCount = Config.getInt( "jcifs.smb.client.transaction_buf_size",
-                                       SmbComTransaction.TRANSACTION_BUF_SIZE ) - 512;
-       }
-
-       public void reset() {
-               isPrimary = hasMore = true; 
-       }
-       public void reset( int key, String lastName ) {
-               reset();
-       }
-       public boolean hasMoreElements() {
-               return hasMore;
-       }
-       public Object nextElement() {
-               if( isPrimary ) {
-                       isPrimary = false;
-
-                       parameterOffset = PRIMARY_SETUP_OFFSET + ( setupCount * 2 ) + 2;
-                       if( command == SMB_COM_TRANSACTION && isResponse() == false ) {
-                               parameterOffset += stringWireLength( name, parameterOffset );
-                       }
-                       pad = parameterOffset % PADDING_SIZE;
-                       pad = pad == 0 ? 0 : PADDING_SIZE - pad;
-                       parameterOffset += pad;
-
-                       totalParameterCount = writeParametersWireFormat( txn_buf, bufParameterOffset );
-                       bufDataOffset = totalParameterCount; // data comes right after data
-
-                       int available = maxBufferSize - parameterOffset;
-                       parameterCount = Math.min( totalParameterCount, available );
-                       available -= parameterCount;
-
-                       dataOffset = parameterOffset + parameterCount;
-                       pad1 = dataOffset % PADDING_SIZE;
-                       pad1 = pad1 == 0 ? 0 : PADDING_SIZE - pad1;
-                       dataOffset += pad1;
-
-                       totalDataCount = writeDataWireFormat( txn_buf, bufDataOffset );
-
-                       dataCount = Math.min( totalDataCount, available );
-               } else {
-                       command = SMB_COM_TRANSACTION_SECONDARY;
-                       // totalParameterCount and totalDataCount are set ok from primary
-
-                       parameterOffset = SECONDARY_PARAMETER_OFFSET;
-                       if(( totalParameterCount - parameterDisplacement ) > 0 ) {
-                               pad = parameterOffset % PADDING_SIZE;
-                               pad = pad == 0 ? 0 : PADDING_SIZE - pad;
-                               parameterOffset += pad;
-                       }
-
-                       // caclulate parameterDisplacement before calculating new parameterCount
-                       parameterDisplacement += parameterCount;
-
-                       int available = maxBufferSize - parameterOffset - pad;
-                       parameterCount = Math.min( totalParameterCount - parameterDisplacement, available);
-                       available -= parameterCount;
-
-                       dataOffset = parameterOffset + parameterCount;
-                       pad1 = dataOffset % PADDING_SIZE;
-                       pad1 = pad1 == 0 ? 0 : PADDING_SIZE - pad1;
-                       dataOffset += pad1;
-
-                       dataDisplacement += dataCount;
-
-                       available -= pad1;
-                       dataCount = Math.min( totalDataCount - dataDisplacement, available );
-               }
-               if(( parameterDisplacement + parameterCount ) >= totalParameterCount &&
-                                       ( dataDisplacement + dataCount ) >= totalDataCount ) {
-                       hasMore = false;
-               }
-               return this;
-       }
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-
-               writeInt2( totalParameterCount, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( totalDataCount, dst, dstIndex );
-               dstIndex += 2;
-               if( command != SMB_COM_TRANSACTION_SECONDARY ) {
-                       writeInt2( maxParameterCount, dst, dstIndex );
-                       dstIndex += 2;
-                       writeInt2( maxDataCount, dst, dstIndex );
-                       dstIndex += 2;
-                       dst[dstIndex++] = maxSetupCount;
-                       dst[dstIndex++] = (byte)0x00;           // Reserved1
-                       writeInt2( flags, dst, dstIndex );
-                       dstIndex += 2;
-                       writeInt4( timeout, dst, dstIndex );
-                       dstIndex += 4;
-                       dst[dstIndex++] = (byte)0x00;           // Reserved2
-                       dst[dstIndex++] = (byte)0x00;
-               }
-               writeInt2( parameterCount, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2(( parameterCount == 0 ? 0 : parameterOffset ), dst, dstIndex );
-               dstIndex += 2;
-               if( command == SMB_COM_TRANSACTION_SECONDARY ) {
-                       writeInt2( parameterDisplacement, dst, dstIndex );
-                       dstIndex += 2;
-               }
-               writeInt2( dataCount, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2(( dataCount == 0 ? 0 : dataOffset ), dst, dstIndex );
-               dstIndex += 2;
-               if( command == SMB_COM_TRANSACTION_SECONDARY ) {
-                       writeInt2( dataDisplacement, dst, dstIndex );
-                       dstIndex += 2;
-               } else {
-                       dst[dstIndex++] = (byte)setupCount;
-                       dst[dstIndex++] = (byte)0x00;           // Reserved3
-                       dstIndex += writeSetupWireFormat( dst, dstIndex );
-               }
-
-               return dstIndex - start;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-               int p = pad;
-
-               if( command == SMB_COM_TRANSACTION && isResponse() == false ) {
-                       dstIndex += writeString( name, dst, dstIndex );
-               }
-
-               if( parameterCount > 0 ) {
-                       while( p-- > 0 ) {
-                               dst[dstIndex++] = (byte)0x00;       // Pad
-                       }
-
-                       System.arraycopy( txn_buf, bufParameterOffset, dst, dstIndex, parameterCount );
-                       dstIndex += parameterCount;
-               }
-
-               if( dataCount > 0 ) {
-                       p = pad1;
-                       while( p-- > 0 ) {
-                               dst[dstIndex++] = (byte)0x00;       // Pad1
-                       }
-                       System.arraycopy( txn_buf, bufDataOffset, dst, dstIndex, dataCount );
-                       bufDataOffset += dataCount;
-                       dstIndex += dataCount;
-               }
-
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-
-       abstract int writeSetupWireFormat( byte[] dst, int dstIndex );
-       abstract int writeParametersWireFormat( byte[] dst, int dstIndex );
-       abstract int writeDataWireFormat( byte[] dst, int dstIndex );
-       abstract int readSetupWireFormat( byte[] buffer, int bufferIndex, int len );
-       abstract int readParametersWireFormat( byte[] buffer, int bufferIndex, int len );
-       abstract int readDataWireFormat( byte[] buffer, int bufferIndex, int len );
-
-       public String toString() {
-               return new String( super.toString() +
-                       ",totalParameterCount=" + totalParameterCount +
-                       ",totalDataCount=" + totalDataCount +
-                       ",maxParameterCount=" + maxParameterCount +
-                       ",maxDataCount=" + maxDataCount +
-                       ",maxSetupCount=" + (int)maxSetupCount +
-                       ",flags=0x" + Log.getHexString( flags, 2 ) +
-                       ",timeout=" + timeout +
-                       ",parameterCount=" + parameterCount +
-                       ",parameterOffset=" + parameterOffset +
-                       ",parameterDisplacement=" + parameterDisplacement +
-                       ",dataCount=" + dataCount +
-                       ",dataOffset=" + dataOffset +
-                       ",dataDisplacement=" + dataDisplacement +
-                       ",setupCount=" + setupCount +
-                       ",pad=" + pad +
-                       ",pad1=" + pad1 );
-       }
+    private static final int DEFAULT_MAX_DATA_COUNT =
+            Config.getInt( "jcifs.smb.client.transaction_buf_size",
+                    SmbComTransaction.TRANSACTION_BUF_SIZE ) - 512;
+
+    // relative to headerStart
+    private static final int PRIMARY_SETUP_OFFSET        = 61;
+    private static final int SECONDARY_PARAMETER_OFFSET  = 51;
+
+    private static final int DISCONNECT_TID      = 0x01;
+    private static final int ONE_WAY_TRANSACTION = 0x02;
+
+    private static final int PADDING_SIZE = 2;
+
+    private int flags = 0x00;
+    private int parameterCount;
+    private int parameterOffset;
+    private int parameterDisplacement;
+    private int dataCount;
+    private int dataOffset;
+    private int dataDisplacement;
+    private int fid;
+    private int pad = 0;
+    private int pad1 = 0;
+    private boolean hasMore = true;
+    private boolean isPrimary = true;
+    private int bufParameterOffset;
+    private int bufDataOffset;
+
+    static final int TRANSACTION_BUF_SIZE = 0xFFFF;
+
+    static final byte TRANS2_FIND_FIRST2            = (byte)0x01;
+    static final byte TRANS2_FIND_NEXT2             = (byte)0x02;
+    static final byte TRANS2_QUERY_FS_INFORMATION   = (byte)0x03;
+    static final byte TRANS2_QUERY_PATH_INFORMATION = (byte)0x05;
+    static final byte TRANS2_GET_DFS_REFERRAL       = (byte)0x10;
+    static final byte TRANS2_SET_FILE_INFORMATION   = (byte)0x08;
+
+    static final int NET_SHARE_ENUM   = 0x0000;
+    static final int NET_SERVER_ENUM2 = 0x0068;
+
+    static final byte TRANS_PEEK_NAMED_PIPE     = (byte)0x23;
+    static final byte TRANS_WAIT_NAMED_PIPE     = (byte)0x53;
+    static final byte TRANS_CALL_NAMED_PIPE     = (byte)0x54;
+    static final byte TRANS_TRANSACT_NAMED_PIPE = (byte)0x26;
+
+    int totalParameterCount;
+    int totalDataCount;
+    int maxParameterCount;
+    int maxDataCount = DEFAULT_MAX_DATA_COUNT;
+    byte maxSetupCount;
+    int timeout = 0;
+    int setupCount = 1;
+    byte subCommand;
+    String name = "";
+    int maxBufferSize; // set in SmbTransport.sendTransaction() before nextElement called
+
+    byte[] txn_buf;
+
+    SmbComTransaction() {
+        maxParameterCount = 1024;
+    }
+
+    void reset() {
+        isPrimary = hasMore = true; 
+    }
+    void reset( int key, String lastName ) {
+        reset();
+    }
+    public boolean hasMoreElements() {
+        return hasMore;
+    }
+    public Object nextElement() {
+        if( isPrimary ) {
+            isPrimary = false;
+
+            parameterOffset = PRIMARY_SETUP_OFFSET + ( setupCount * 2 ) + 2;
+            if( command == SMB_COM_TRANSACTION && isResponse() == false ) {
+                parameterOffset += stringWireLength( name, parameterOffset );
+            }
+            pad = parameterOffset % PADDING_SIZE;
+            pad = pad == 0 ? 0 : PADDING_SIZE - pad;
+            parameterOffset += pad;
+
+            totalParameterCount = writeParametersWireFormat( txn_buf, bufParameterOffset );
+            bufDataOffset = totalParameterCount; // data comes right after data
+
+            int available = maxBufferSize - parameterOffset;
+            parameterCount = Math.min( totalParameterCount, available );
+            available -= parameterCount;
+
+            dataOffset = parameterOffset + parameterCount;
+            pad1 = dataOffset % PADDING_SIZE;
+            pad1 = pad1 == 0 ? 0 : PADDING_SIZE - pad1;
+            dataOffset += pad1;
+
+            totalDataCount = writeDataWireFormat( txn_buf, bufDataOffset );
+
+            dataCount = Math.min( totalDataCount, available );
+        } else {
+            command = SMB_COM_TRANSACTION_SECONDARY;
+            // totalParameterCount and totalDataCount are set ok from primary
+
+            parameterOffset = SECONDARY_PARAMETER_OFFSET;
+            if(( totalParameterCount - parameterDisplacement ) > 0 ) {
+                pad = parameterOffset % PADDING_SIZE;
+                pad = pad == 0 ? 0 : PADDING_SIZE - pad;
+                parameterOffset += pad;
+            }
+
+            // caclulate parameterDisplacement before calculating new parameterCount
+            parameterDisplacement += parameterCount;
+
+            int available = maxBufferSize - parameterOffset - pad;
+            parameterCount = Math.min( totalParameterCount - parameterDisplacement, available);
+            available -= parameterCount;
+
+            dataOffset = parameterOffset + parameterCount;
+            pad1 = dataOffset % PADDING_SIZE;
+            pad1 = pad1 == 0 ? 0 : PADDING_SIZE - pad1;
+            dataOffset += pad1;
+
+            dataDisplacement += dataCount;
+
+            available -= pad1;
+            dataCount = Math.min( totalDataCount - dataDisplacement, available );
+        }
+        if(( parameterDisplacement + parameterCount ) >= totalParameterCount &&
+                    ( dataDisplacement + dataCount ) >= totalDataCount ) {
+            hasMore = false;
+        }
+        return this;
+    }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+
+        writeInt2( totalParameterCount, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( totalDataCount, dst, dstIndex );
+        dstIndex += 2;
+        if( command != SMB_COM_TRANSACTION_SECONDARY ) {
+            writeInt2( maxParameterCount, dst, dstIndex );
+            dstIndex += 2;
+            writeInt2( maxDataCount, dst, dstIndex );
+            dstIndex += 2;
+            dst[dstIndex++] = maxSetupCount;
+            dst[dstIndex++] = (byte)0x00;           // Reserved1
+            writeInt2( flags, dst, dstIndex );
+            dstIndex += 2;
+            writeInt4( timeout, dst, dstIndex );
+            dstIndex += 4;
+            dst[dstIndex++] = (byte)0x00;           // Reserved2
+            dst[dstIndex++] = (byte)0x00;
+        }
+        writeInt2( parameterCount, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2(( parameterCount == 0 ? 0 : parameterOffset ), dst, dstIndex );
+        dstIndex += 2;
+        if( command == SMB_COM_TRANSACTION_SECONDARY ) {
+            writeInt2( parameterDisplacement, dst, dstIndex );
+            dstIndex += 2;
+        }
+        writeInt2( dataCount, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2(( dataCount == 0 ? 0 : dataOffset ), dst, dstIndex );
+        dstIndex += 2;
+        if( command == SMB_COM_TRANSACTION_SECONDARY ) {
+            writeInt2( dataDisplacement, dst, dstIndex );
+            dstIndex += 2;
+        } else {
+            dst[dstIndex++] = (byte)setupCount;
+            dst[dstIndex++] = (byte)0x00;           // Reserved3
+            dstIndex += writeSetupWireFormat( dst, dstIndex );
+        }
+
+        return dstIndex - start;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+        int p = pad;
+
+        if( command == SMB_COM_TRANSACTION && isResponse() == false ) {
+            dstIndex += writeString( name, dst, dstIndex );
+        }
+
+        if( parameterCount > 0 ) {
+            while( p-- > 0 ) {
+                dst[dstIndex++] = (byte)0x00;       // Pad
+            }
+
+            System.arraycopy( txn_buf, bufParameterOffset, dst, dstIndex, parameterCount );
+            dstIndex += parameterCount;
+        }
+
+        if( dataCount > 0 ) {
+            p = pad1;
+            while( p-- > 0 ) {
+                dst[dstIndex++] = (byte)0x00;       // Pad1
+            }
+            System.arraycopy( txn_buf, bufDataOffset, dst, dstIndex, dataCount );
+            bufDataOffset += dataCount;
+            dstIndex += dataCount;
+        }
+
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+
+    abstract int writeSetupWireFormat( byte[] dst, int dstIndex );
+    abstract int writeParametersWireFormat( byte[] dst, int dstIndex );
+    abstract int writeDataWireFormat( byte[] dst, int dstIndex );
+    abstract int readSetupWireFormat( byte[] buffer, int bufferIndex, int len );
+    abstract int readParametersWireFormat( byte[] buffer, int bufferIndex, int len );
+    abstract int readDataWireFormat( byte[] buffer, int bufferIndex, int len );
+
+    public String toString() {
+        return new String( super.toString() +
+            ",totalParameterCount=" + totalParameterCount +
+            ",totalDataCount=" + totalDataCount +
+            ",maxParameterCount=" + maxParameterCount +
+            ",maxDataCount=" + maxDataCount +
+            ",maxSetupCount=" + (int)maxSetupCount +
+            ",flags=0x" + Hexdump.toHexString( flags, 2 ) +
+            ",timeout=" + timeout +
+            ",parameterCount=" + parameterCount +
+            ",parameterOffset=" + parameterOffset +
+            ",parameterDisplacement=" + parameterDisplacement +
+            ",dataCount=" + dataCount +
+            ",dataOffset=" + dataOffset +
+            ",dataDisplacement=" + dataDisplacement +
+            ",setupCount=" + setupCount +
+            ",pad=" + pad +
+            ",pad1=" + pad1 );
+    }
 }
index 279824c..db7f9db 100644 (file)
 package jcifs.smb;
 
 import java.util.Enumeration;
-import jcifs.Config;
 
 abstract class SmbComTransactionResponse extends ServerMessageBlock implements Enumeration {
 
-       // relative to headerStart
-       static final int SETUP_OFFSET        = 61;
-
-       static final int DISCONNECT_TID      = 0x01;
-       static final int ONE_WAY_TRANSACTION = 0x02;
-
-       int totalParameterCount;
-       int totalDataCount;
-       int parameterCount;
-       int parameterOffset;
-       int parameterDisplacement;
-       int dataCount;
-       int dataOffset;
-       int dataDisplacement;
-       int setupCount;
-       byte subCommand;
-       int pad;
-       int pad1;
-       boolean hasMore = true;
-       boolean isPrimary = true;
-       boolean parametersDone, dataDone;
-
-       byte[] txn_buf;
-       int bufParameterStart;
-       int bufDataStart;
-
-       /* for doNetEnum and doFindFirstNext */
-       int status;
-       int numEntries;
-       FileEntry[] results;
-
-       SmbComTransactionResponse() {
-               txn_buf = null;
-       }
-
-       public void reset() {
-               bufDataStart = 0;
-               isPrimary = hasMore = true; 
-               parametersDone = dataDone = false;
-       }
-       public boolean hasMoreElements() {
-               return hasMore;
-       }
-       public Object nextElement() {
-               if( isPrimary ) {
-                       isPrimary = false;
-               }
-               return this;
-       }
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               int start = bufferIndex;
-
-               totalParameterCount = readInt2( buffer, bufferIndex );
-               if( bufDataStart == 0 ) {
-                       bufDataStart = totalParameterCount;
-               }
-               bufferIndex += 2;
-               totalDataCount = readInt2( buffer, bufferIndex );
-               bufferIndex += 4; // Reserved
-               parameterCount = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               parameterOffset = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               parameterDisplacement = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               dataCount = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               dataOffset = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               dataDisplacement = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               setupCount = buffer[bufferIndex] & 0xFF;
-               bufferIndex += 2;
-               if( setupCount != 0 ) {
-                       Log.println( Log.WARNINGS, "smb transaction response",
-                                                               "setupCount is not zero: " + setupCount );
-               }
-
-               return bufferIndex - start;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               pad = pad1 = 0;
-               int n;
-
-               if( parameterCount > 0 ) {
-                       bufferIndex += pad = parameterOffset - ( bufferIndex - headerStart );
-                       System.arraycopy( buffer, bufferIndex, txn_buf,
-                                                       bufParameterStart + parameterDisplacement, parameterCount );
-                       bufferIndex += parameterCount;
-               }
-               if( dataCount > 0 ) {
-                       bufferIndex += pad1 = dataOffset - ( bufferIndex - headerStart );
-                       System.arraycopy( buffer, bufferIndex, txn_buf,
-                                                       bufDataStart + dataDisplacement, dataCount );
-                       bufferIndex += dataCount;
-               }
-
-               /* Check to see if the entire transaction has been
-                * read. If so call the read methods.
-                */
-
-               if( !parametersDone &&
-                               ( parameterDisplacement + parameterCount ) == totalParameterCount) {
-                       parametersDone = true;
-               }
-
-               if( !dataDone &&
-                               ( dataDisplacement + dataCount ) == totalDataCount) {
-                       dataDone = true;
-               }
-
-               if( parametersDone && dataDone ) {
-                       hasMore = false;
-                       readParametersWireFormat( txn_buf, bufParameterStart, totalParameterCount );
-                       readDataWireFormat( txn_buf, bufDataStart, totalDataCount );
-               }
-
-               return pad + parameterCount + pad1 + dataCount;
-       }
-
-       abstract int writeSetupWireFormat( byte[] dst, int dstIndex );
-       abstract int writeParametersWireFormat( byte[] dst, int dstIndex );
-       abstract int writeDataWireFormat( byte[] dst, int dstIndex );
-       abstract int readSetupWireFormat( byte[] buffer, int bufferIndex, int len );
-       abstract int readParametersWireFormat( byte[] buffer, int bufferIndex, int len );
-       abstract int readDataWireFormat( byte[] buffer, int bufferIndex, int len );
-
-       public String toString() {
-               return new String( super.toString() +
-                       ",totalParameterCount=" + totalParameterCount +
-                       ",totalDataCount=" + totalDataCount +
-                       ",parameterCount=" + parameterCount +
-                       ",parameterOffset=" + parameterOffset +
-                       ",parameterDisplacement=" + parameterDisplacement +
-                       ",dataCount=" + dataCount +
-                       ",dataOffset=" + dataOffset +
-                       ",dataDisplacement=" + dataDisplacement +
-                       ",setupCount=" + setupCount +
-                       ",pad=" + pad +
-                       ",pad1=" + pad1 );
-       }
+    // relative to headerStart
+    private static final int SETUP_OFFSET        = 61;
+
+    private static final int DISCONNECT_TID      = 0x01;
+    private static final int ONE_WAY_TRANSACTION = 0x02;
+
+    private int totalParameterCount;
+    private int totalDataCount;
+    private int parameterCount;
+    private int parameterOffset;
+    private int parameterDisplacement;
+    private int dataOffset;
+    private int dataDisplacement;
+    private int setupCount;
+    private int pad;
+    private int pad1;
+    private boolean parametersDone, dataDone;
+
+    private int bufParameterStart;
+    private int bufDataStart;
+
+    int dataCount;
+    byte subCommand;
+    boolean hasMore = true;
+    boolean isPrimary = true;
+    byte[] txn_buf;
+
+    /* for doNetEnum and doFindFirstNext */
+    int status;
+    int numEntries;
+    FileEntry[] results;
+
+    SmbComTransactionResponse() {
+        txn_buf = null;
+    }
+
+    public void reset() {
+        bufDataStart = 0;
+        isPrimary = hasMore = true; 
+        parametersDone = dataDone = false;
+    }
+    public boolean hasMoreElements() {
+        return hasMore;
+    }
+    public Object nextElement() {
+        if( isPrimary ) {
+            isPrimary = false;
+        }
+        return this;
+    }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        int start = bufferIndex;
+
+        totalParameterCount = readInt2( buffer, bufferIndex );
+        if( bufDataStart == 0 ) {
+            bufDataStart = totalParameterCount;
+        }
+        bufferIndex += 2;
+        totalDataCount = readInt2( buffer, bufferIndex );
+        bufferIndex += 4; // Reserved
+        parameterCount = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        parameterOffset = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        parameterDisplacement = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        dataCount = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        dataOffset = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        dataDisplacement = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        setupCount = buffer[bufferIndex] & 0xFF;
+        bufferIndex += 2;
+        if( setupCount != 0 ) {
+            if( log.level > 2 )
+                log.println( "setupCount is not zero: " + setupCount );
+        }
+
+        return bufferIndex - start;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        pad = pad1 = 0;
+        int n;
+
+        if( parameterCount > 0 ) {
+            bufferIndex += pad = parameterOffset - ( bufferIndex - headerStart );
+            System.arraycopy( buffer, bufferIndex, txn_buf,
+                            bufParameterStart + parameterDisplacement, parameterCount );
+            bufferIndex += parameterCount;
+        }
+        if( dataCount > 0 ) {
+            bufferIndex += pad1 = dataOffset - ( bufferIndex - headerStart );
+            System.arraycopy( buffer, bufferIndex, txn_buf,
+                            bufDataStart + dataDisplacement, dataCount );
+            bufferIndex += dataCount;
+        }
+
+        /* Check to see if the entire transaction has been
+         * read. If so call the read methods.
+         */
+
+        if( !parametersDone &&
+                ( parameterDisplacement + parameterCount ) == totalParameterCount) {
+            parametersDone = true;
+        }
+
+        if( !dataDone &&
+                ( dataDisplacement + dataCount ) == totalDataCount) {
+            dataDone = true;
+        }
+
+        if( parametersDone && dataDone ) {
+            hasMore = false;
+            readParametersWireFormat( txn_buf, bufParameterStart, totalParameterCount );
+            readDataWireFormat( txn_buf, bufDataStart, totalDataCount );
+        }
+
+        return pad + parameterCount + pad1 + dataCount;
+    }
+
+    abstract int writeSetupWireFormat( byte[] dst, int dstIndex );
+    abstract int writeParametersWireFormat( byte[] dst, int dstIndex );
+    abstract int writeDataWireFormat( byte[] dst, int dstIndex );
+    abstract int readSetupWireFormat( byte[] buffer, int bufferIndex, int len );
+    abstract int readParametersWireFormat( byte[] buffer, int bufferIndex, int len );
+    abstract int readDataWireFormat( byte[] buffer, int bufferIndex, int len );
+
+    public String toString() {
+        return new String( super.toString() +
+            ",totalParameterCount=" + totalParameterCount +
+            ",totalDataCount=" + totalDataCount +
+            ",parameterCount=" + parameterCount +
+            ",parameterOffset=" + parameterOffset +
+            ",parameterDisplacement=" + parameterDisplacement +
+            ",dataCount=" + dataCount +
+            ",dataOffset=" + dataOffset +
+            ",dataDisplacement=" + dataDisplacement +
+            ",setupCount=" + setupCount +
+            ",pad=" + pad +
+            ",pad1=" + pad1 );
+    }
 }
index 8a3bd6e..13ae5a5 100644 (file)
 package jcifs.smb;
 
 import jcifs.Config;
-import jcifs.util.PropertiesTree;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
+import jcifs.util.Hexdump;
 
 class SmbComTreeConnectAndX extends AndXServerMessageBlock {
 
-       SmbSession session;
-       boolean disconnectTid = false;
-       String path, service;
-       byte[] password;
-       int passwordLength;
-
-       /* batchLimits indecies
-        *
-        * 0 = SMB_COM_CHECK_DIRECTORY
-        * 2 = SMB_COM_CREATE_DIRECTORY
-        * 3 = SMB_COM_DELETE
-        * 4 = SMB_COM_DELETE_DIRECTORY
-        * 5 = SMB_COM_OPEN_ANDX
-        * 6 = SMB_COM_RENAME
-        * 7 = SMB_COM_TRANSACTION
-        * 8 = SMB_COM_QUERY_INFORMATION
-        */
-
-       /* All batch limits are single batch only until further notice
-        */
-
-       static byte[] batchLimits = {
-               1, 1, 1, 1, 1, 1, 1, 1, 0
-       };
-
-       static {
-               PropertiesTree pt = (PropertiesTree)Config.get( "jcifs.smb.client.TreeConnectAndX" );
-               String s;
-
-               if( pt != null ) {
-                       if(( s = pt.getProperty( "CheckDirectory" )) != null ) {
-                               batchLimits[0] = Byte.parseByte( s );
-                       }
-                       if(( s = pt.getProperty( "CreateDirectory" )) != null ) {
-                               batchLimits[2] = Byte.parseByte( s );
-                       }
-                       if(( s = pt.getProperty( "Delete" )) != null ) {
-                               batchLimits[3] = Byte.parseByte( s );
-                       }
-                       if(( s = pt.getProperty( "DeleteDirectory" )) != null ) {
-                               batchLimits[4] = Byte.parseByte( s );
-                       }
-                       if(( s = pt.getProperty( "OpenAndX" )) != null ) {
-                               batchLimits[5] = Byte.parseByte( s );
-                       }
-                       if(( s = pt.getProperty( "Rename" )) != null ) {
-                               batchLimits[6] = Byte.parseByte( s );
-                       }
-                       if(( s = pt.getProperty( "Transaction" )) != null ) {
-                               batchLimits[7] = Byte.parseByte( s );
-                       }
-                       if(( s = pt.getProperty( "QueryInformation" )) != null ) {
-                               batchLimits[8] = Byte.parseByte( s );
-                       }
-               }
-       }
-
-       SmbComTreeConnectAndX( SmbSession session, String path,
-                                                               String service, ServerMessageBlock andx ) {
-               super( andx );
-               this.session = session;
-               this.path = path;
-               this.service = service;
-               command = SMB_COM_TREE_CONNECT_ANDX;
-       }
-
-       int getBatchLimit( byte command ) {
-               int c = (int)( command & 0xFF );
-               // why isn't this just return batchLimits[c]?
-               switch( c ) {
-                       case SMB_COM_CHECK_DIRECTORY:
-                               return batchLimits[0];
-                       case SMB_COM_CREATE_DIRECTORY:
-                               return batchLimits[2];
-                       case SMB_COM_DELETE:
-                               return batchLimits[3];
-                       case SMB_COM_DELETE_DIRECTORY:
-                               return batchLimits[4];
-                       case SMB_COM_OPEN_ANDX:
-                               return batchLimits[5];
-                       case SMB_COM_RENAME:
-                               return batchLimits[6];
-                       case SMB_COM_TRANSACTION:
-                               return batchLimits[7];
-                       case SMB_COM_QUERY_INFORMATION:
-                               return batchLimits[8];
-               }
-               return 0;
-       }
-
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-
-               if( session.transport.server.security == SECURITY_SHARE &&
-                                               ( session.auth.hashesExternal ||
-                                               session.auth.password.length() > 0 )) {
-
-                       if( session.transport.server.encryptedPasswords ) {
-                               // encrypted
-                               password = session.auth.getAnsiHash( session.transport.server.encryptionKey );
-                               passwordLength = password.length;
-                       } else if( Config.getBoolean( "jcifs.smb.client.disablePlainTextPasswords", true )) {
-                               throw new RuntimeException( "Plain text passwords are disabled" );
-                       } else {
-                               // plain text
-                               password = new byte[(session.auth.password.length() + 1) * 2];
-                               passwordLength = writeString( session.auth.password, password, 0 );
-                       }
-               } else {
-                       // no password in tree connect
-                       passwordLength = 1;
-               }
-
-               dst[dstIndex++] = disconnectTid ? (byte)0x01 : (byte)0x00;
-               dst[dstIndex++] = (byte)0x00;
-               writeInt2( passwordLength, dst, dstIndex );
-               return 4;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-
-               if( session.transport.server.security == SECURITY_SHARE &&
-                                               ( session.auth.hashesExternal ||
-                                               session.auth.password.length() > 0 )) {
-                       System.arraycopy( password, 0, dst, dstIndex, passwordLength );
-                       dstIndex += passwordLength;
-               } else {
-                       // no password in tree connect
-                       dst[dstIndex++] = (byte)0x00;
-               }
-               dstIndex += writeString( path, dst, dstIndex );
-               try {
-                       System.arraycopy( service.getBytes( "ASCII" ), 0, dst, dstIndex, service.length() );
-               } catch( UnsupportedEncodingException uee ) {
-                       return 0;
-               }
-               dstIndex += service.length();
-               dst[dstIndex++] = (byte)'\0';
-
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               String result = new String( "SmbComTreeConnectAndX[" +
-                       super.toString() +
-                       ",disconnectTid=" + disconnectTid +
-                       ",passwordLength=" + passwordLength +
-                       ",password=" + Log.getHexString( password, passwordLength, 0 ) +
-                       ",path=" + path +
-                       ",service=" + service + "]" );
-               return result;
-       }
+    private static final boolean DISABLE_PLAIN_TEXT_PASSWORDS =
+            Config.getBoolean( "jcifs.smb.client.disablePlainTextPasswords", true );
+
+    private SmbSession session;
+    private boolean disconnectTid = false;
+    private String path, service;
+    private byte[] password;
+    private int passwordLength;
+
+    /* batchLimits indecies
+     *
+     * 0 = SMB_COM_CHECK_DIRECTORY
+     * 2 = SMB_COM_CREATE_DIRECTORY
+     * 3 = SMB_COM_DELETE
+     * 4 = SMB_COM_DELETE_DIRECTORY
+     * 5 = SMB_COM_OPEN_ANDX
+     * 6 = SMB_COM_RENAME
+     * 7 = SMB_COM_TRANSACTION
+     * 8 = SMB_COM_QUERY_INFORMATION
+     */
+
+    /* All batch limits are single batch only until further notice
+     */
+
+    private static byte[] batchLimits = {
+        1, 1, 1, 1, 1, 1, 1, 1, 0
+    };
+
+    static {
+        String s;
+
+        if(( s = Config.getProperty( "jcifs.smb.client.TreeConnectAndX.CheckDirectory" )) != null ) {
+            batchLimits[0] = Byte.parseByte( s );
+        }
+        if(( s = Config.getProperty( "jcifs.smb.client.TreeConnectAndX.CreateDirectory" )) != null ) {
+            batchLimits[2] = Byte.parseByte( s );
+        }
+        if(( s = Config.getProperty( "jcifs.smb.client.TreeConnectAndX.Delete" )) != null ) {
+            batchLimits[3] = Byte.parseByte( s );
+        }
+        if(( s = Config.getProperty( "jcifs.smb.client.TreeConnectAndX.DeleteDirectory" )) != null ) {
+            batchLimits[4] = Byte.parseByte( s );
+        }
+        if(( s = Config.getProperty( "jcifs.smb.client.TreeConnectAndX.OpenAndX" )) != null ) {
+            batchLimits[5] = Byte.parseByte( s );
+        }
+        if(( s = Config.getProperty( "jcifs.smb.client.TreeConnectAndX.Rename" )) != null ) {
+            batchLimits[6] = Byte.parseByte( s );
+        }
+        if(( s = Config.getProperty( "jcifs.smb.client.TreeConnectAndX.Transaction" )) != null ) {
+            batchLimits[7] = Byte.parseByte( s );
+        }
+        if(( s = Config.getProperty( "jcifs.smb.client.TreeConnectAndX.QueryInformation" )) != null ) {
+            batchLimits[8] = Byte.parseByte( s );
+        }
+    }
+
+    SmbComTreeConnectAndX( SmbSession session, String path,
+                                String service, ServerMessageBlock andx ) {
+        super( andx );
+        this.session = session;
+        this.path = path;
+        this.service = service;
+        command = SMB_COM_TREE_CONNECT_ANDX;
+    }
+
+    int getBatchLimit( byte command ) {
+        int c = (int)( command & 0xFF );
+        // why isn't this just return batchLimits[c]?
+        switch( c ) {
+            case SMB_COM_CHECK_DIRECTORY:
+                return batchLimits[0];
+            case SMB_COM_CREATE_DIRECTORY:
+                return batchLimits[2];
+            case SMB_COM_DELETE:
+                return batchLimits[3];
+            case SMB_COM_DELETE_DIRECTORY:
+                return batchLimits[4];
+            case SMB_COM_OPEN_ANDX:
+                return batchLimits[5];
+            case SMB_COM_RENAME:
+                return batchLimits[6];
+            case SMB_COM_TRANSACTION:
+                return batchLimits[7];
+            case SMB_COM_QUERY_INFORMATION:
+                return batchLimits[8];
+        }
+        return 0;
+    }
+
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+
+        if( session.transport.server.security == SECURITY_SHARE &&
+                        ( session.auth.hashesExternal ||
+                        session.auth.password.length() > 0 )) {
+
+            if( session.transport.server.encryptedPasswords ) {
+                // encrypted
+                password = session.auth.getAnsiHash( session.transport.server.encryptionKey );
+                passwordLength = password.length;
+            } else if( DISABLE_PLAIN_TEXT_PASSWORDS ) {
+                throw new RuntimeException( "Plain text passwords are disabled" );
+            } else {
+                // plain text
+                password = new byte[(session.auth.password.length() + 1) * 2];
+                passwordLength = writeString( session.auth.password, password, 0 );
+            }
+        } else {
+            // no password in tree connect
+            passwordLength = 1;
+        }
+
+        dst[dstIndex++] = disconnectTid ? (byte)0x01 : (byte)0x00;
+        dst[dstIndex++] = (byte)0x00;
+        writeInt2( passwordLength, dst, dstIndex );
+        return 4;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+
+        if( session.transport.server.security == SECURITY_SHARE &&
+                        ( session.auth.hashesExternal ||
+                        session.auth.password.length() > 0 )) {
+            System.arraycopy( password, 0, dst, dstIndex, passwordLength );
+            dstIndex += passwordLength;
+        } else {
+            // no password in tree connect
+            dst[dstIndex++] = (byte)0x00;
+        }
+        dstIndex += writeString( path, dst, dstIndex );
+        try {
+            System.arraycopy( service.getBytes( "ASCII" ), 0, dst, dstIndex, service.length() );
+        } catch( UnsupportedEncodingException uee ) {
+            return 0;
+        }
+        dstIndex += service.length();
+        dst[dstIndex++] = (byte)'\0';
+
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        String result = new String( "SmbComTreeConnectAndX[" +
+            super.toString() +
+            ",disconnectTid=" + disconnectTid +
+            ",passwordLength=" + passwordLength +
+            ",password=" + Hexdump.toHexString( password, passwordLength, 0 ) +
+            ",path=" + path +
+            ",service=" + service + "]" );
+        return result;
+    }
 }
 
index 1c970ed..5704c2d 100644 (file)
@@ -24,55 +24,57 @@ import java.io.UnsupportedEncodingException;
 
 class SmbComTreeConnectAndXResponse extends AndXServerMessageBlock {
 
-       static final int SMB_SUPPORT_SEARCH_BITS = 0x0001;
-       static final int SMB_SHARE_IS_IN_DFS     = 0x0002;
+    private static final int SMB_SUPPORT_SEARCH_BITS = 0x0001;
+    private static final int SMB_SHARE_IS_IN_DFS     = 0x0002;
 
-       boolean supportSearchBits, shareIsInDfs;
-       String service, nativeFileSystem = "";
+    boolean supportSearchBits, shareIsInDfs;
+    String service, nativeFileSystem = "";
 
-       SmbComTreeConnectAndXResponse( ServerMessageBlock andx ) {
-               super( andx );
-       }
+    SmbComTreeConnectAndXResponse( ServerMessageBlock andx ) {
+        super( andx );
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               supportSearchBits = ( buffer[bufferIndex] & SMB_SUPPORT_SEARCH_BITS ) == SMB_SUPPORT_SEARCH_BITS;
-               shareIsInDfs = ( buffer[bufferIndex] & SMB_SHARE_IS_IN_DFS ) == SMB_SHARE_IS_IN_DFS;
-               return 2;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               int start = bufferIndex;
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        supportSearchBits = ( buffer[bufferIndex] & SMB_SUPPORT_SEARCH_BITS ) == SMB_SUPPORT_SEARCH_BITS;
+        shareIsInDfs = ( buffer[bufferIndex] & SMB_SHARE_IS_IN_DFS ) == SMB_SHARE_IS_IN_DFS;
+        return 2;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        int start = bufferIndex;
 
-               int len = readStringLength( buffer, bufferIndex, 32 );
-               try {
-                       service = new String( buffer, bufferIndex, len, "ASCII" );
-               } catch( UnsupportedEncodingException uee ) {
-                       return 0;
-               }
-               bufferIndex += len + 1;
-               // win98 observed not returning nativeFileSystem
-               if( byteCount > bufferIndex - start ) {
-                       nativeFileSystem = readString( buffer, bufferIndex );
-                       bufferIndex += stringWireLength( nativeFileSystem, bufferIndex );
-               }
+        int len = readStringLength( buffer, bufferIndex, 32 );
+        try {
+            service = new String( buffer, bufferIndex, len, "ASCII" );
+        } catch( UnsupportedEncodingException uee ) {
+            return 0;
+        }
+        bufferIndex += len + 1;
+        // win98 observed not returning nativeFileSystem
+        if( byteCount > bufferIndex - start ) {
+            nativeFileSystem = readString( buffer, bufferIndex );
+            bufferIndex += stringWireLength( nativeFileSystem, bufferIndex );
+        }
 
-               return bufferIndex - start;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               String result = new String( "SmbComTreeConnectAndXResponse[" +
-                       super.toString() +
-                       ",supportSearchBits=" + supportSearchBits +
-                       ",shareIsInDfs=" + shareIsInDfs +
-                       ",service=" + service +
-                       ",nativeFileSystem=" + nativeFileSystem + "]" );
-               return result;
-       }
+        return bufferIndex - start;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        String result = new String( "SmbComTreeConnectAndXResponse[" +
+            super.toString() +
+            ",supportSearchBits=" + supportSearchBits +
+            ",shareIsInDfs=" + shareIsInDfs +
+            ",service=" + service +
+            ",nativeFileSystem=" + nativeFileSystem + "]" );
+        return result;
+    }
 }
+
index b1f8b0e..0c5148b 100644 (file)
@@ -20,24 +20,24 @@ package jcifs.smb;
 
 class SmbComTreeDisconnect extends ServerMessageBlock {
 
-       SmbComTreeDisconnect() {
-               command = SMB_COM_TREE_DISCONNECT;
-       }
+    SmbComTreeDisconnect() {
+        command = SMB_COM_TREE_DISCONNECT;
+    }
 
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComTreeDisconnect[" +
-                       super.toString() + "]" );
-       }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComTreeDisconnect[" +
+            super.toString() + "]" );
+    }
 }
index 12fd33f..f17eda7 100644 (file)
@@ -24,76 +24,76 @@ import java.io.InputStream;
 
 class SmbComWrite extends ServerMessageBlock {
 
-       int fid,
-               count,
-               offset,
-               remaining,
-               off;
-       byte[] b;
+    private int fid,
+        count,
+        offset,
+        remaining,
+        off;
+    private byte[] b;
 
-       SmbComWrite() {
-               super();
-               command = SMB_COM_WRITE;
-       }
-       SmbComWrite( int fid, int offset, int remaining, byte[] b, int off, int len ) {
-               this.fid = fid;
-               this.count = len;
-               this.offset = offset;
-               this.remaining = remaining;
-               this.b = b;
-               this.off = off;
-               command = SMB_COM_WRITE;
-       }
+    SmbComWrite() {
+        super();
+        command = SMB_COM_WRITE;
+    }
+    SmbComWrite( int fid, int offset, int remaining, byte[] b, int off, int len ) {
+        this.fid = fid;
+        this.count = len;
+        this.offset = offset;
+        this.remaining = remaining;
+        this.b = b;
+        this.off = off;
+        command = SMB_COM_WRITE;
+    }
 
-       void setParam( int fid, long offset, int remaining,
-                                       byte[] b, int off, int len ) {
-               this.fid = fid;
-               this.offset = (int)(offset & 0xFFFFFFFFL);
-               this.remaining = remaining;
-               this.b = b;
-               this.off = off;
-               count = len;
-       }
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    void setParam( int fid, long offset, int remaining,
+                    byte[] b, int off, int len ) {
+        this.fid = fid;
+        this.offset = (int)(offset & 0xFFFFFFFFL);
+        this.remaining = remaining;
+        this.b = b;
+        this.off = off;
+        count = len;
+    }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               writeInt2( fid, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( count, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( offset, dst, dstIndex );
-               dstIndex += 4;
-               writeInt2( remaining, dst, dstIndex );
-               dstIndex += 2;
+        writeInt2( fid, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( count, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( offset, dst, dstIndex );
+        dstIndex += 4;
+        writeInt2( remaining, dst, dstIndex );
+        dstIndex += 2;
 
-               return dstIndex - start;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+        return dstIndex - start;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               dst[dstIndex++] = (byte)0x01; /* BufferFormat */
-               writeInt2( count, dst, dstIndex ); /* DataLength? */
-               dstIndex += 2;
-               System.arraycopy( b, off, dst, dstIndex, count );
-               dstIndex += count;
+        dst[dstIndex++] = (byte)0x01; /* BufferFormat */
+        writeInt2( count, dst, dstIndex ); /* DataLength? */
+        dstIndex += 2;
+        System.arraycopy( b, off, dst, dstIndex, count );
+        dstIndex += count;
 
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComWrite[" +
-                       super.toString() +
-                       ",fid=" + fid +
-                       ",count=" + count +
-                       ",offset=" + offset +
-                       ",remaining=" + remaining + "]" );
-       }
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComWrite[" +
+            super.toString() +
+            ",fid=" + fid +
+            ",count=" + count +
+            ",offset=" + offset +
+            ",remaining=" + remaining + "]" );
+    }
 }
index 724503c..a64de35 100644 (file)
@@ -24,116 +24,117 @@ import java.io.InputStream;
 
 class SmbComWriteAndX extends AndXServerMessageBlock {
 
-       static final int READ_ANDX_BATCH_LIMIT =
-                                                       Config.getInt( "jcifs.smb.client.WriteAndX.ReadAndX", 1 );
-       static final int CLOSE_BATCH_LIMIT =
-                                                       Config.getInt( "jcifs.smb.client.WriteAndX.Close", 1 );
+    private static final int READ_ANDX_BATCH_LIMIT =
+                            Config.getInt( "jcifs.smb.client.WriteAndX.ReadAndX", 1 );
+    private static final int CLOSE_BATCH_LIMIT =
+                            Config.getInt( "jcifs.smb.client.WriteAndX.Close", 1 );
 
-       int fid,
-               writeMode,
-               remaining,
-               dataLength,
-               dataOffset,
-               off;
-       byte[] b;
-       long offset;
+    private int fid,
+        writeMode,
+        remaining,
+        dataLength,
+        dataOffset,
+        off;
+    private byte[] b;
+    private long offset;
 
-       SmbComWriteAndX() {
-               super( null );
-               command = SMB_COM_WRITE_ANDX;
-       }
-       SmbComWriteAndX( int fid, long offset, int remaining,
-                                       byte[] b, int off, int len, ServerMessageBlock andx ) {
-               super( andx );
-               this.fid = fid;
-               this.offset = offset;
-               this.remaining = remaining;
-               this.b = b;
-               this.off = off;
-               dataLength = len;
-               command = SMB_COM_WRITE_ANDX;
-       }
+    SmbComWriteAndX() {
+        super( null );
+        command = SMB_COM_WRITE_ANDX;
+    }
+    SmbComWriteAndX( int fid, long offset, int remaining,
+                    byte[] b, int off, int len, ServerMessageBlock andx ) {
+        super( andx );
+        this.fid = fid;
+        this.offset = offset;
+        this.remaining = remaining;
+        this.b = b;
+        this.off = off;
+        dataLength = len;
+        command = SMB_COM_WRITE_ANDX;
+    }
 
-       void setParam( int fid, long offset, int remaining,
-                                       byte[] b, int off, int len ) {
-               this.fid = fid;
-               this.offset = offset;
-               this.remaining = remaining;
-               this.b = b;
-               this.off = off;
-               dataLength = len;
-       }
-       int getBatchLimit( byte command ) {
-               if( command == SMB_COM_READ_ANDX ) {
-                       return READ_ANDX_BATCH_LIMIT;
-               }
-               if( command == SMB_COM_CLOSE ) {
-                       return CLOSE_BATCH_LIMIT;
-               }
-               return 0;
-       }
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    void setParam( int fid, long offset, int remaining,
+                    byte[] b, int off, int len ) {
+        this.fid = fid;
+        this.offset = offset;
+        this.remaining = remaining;
+        this.b = b;
+        this.off = off;
+        dataLength = len;
+    }
+    int getBatchLimit( byte command ) {
+        if( command == SMB_COM_READ_ANDX ) {
+            return READ_ANDX_BATCH_LIMIT;
+        }
+        if( command == SMB_COM_CLOSE ) {
+            return CLOSE_BATCH_LIMIT;
+        }
+        return 0;
+    }
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               dataOffset = dstIndex + 26; // 26 = off from here to pad
+        dataOffset = (dstIndex - headerStart) + 26; // 26 = off from here to pad
 /*
- *             pad = ( dataOffset - headerStart ) % 4;
- *             pad = pad == 0 ? 0 : 4 - pad;
- *             dataOffset += pad;
+ *      pad = ( dataOffset - headerStart ) % 4;
+ *      pad = pad == 0 ? 0 : 4 - pad;
+ *      dataOffset += pad;
  */
 
-               writeInt2( fid, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( offset, dst, dstIndex );
-               dstIndex += 4;
-               for( int i = 0; i < 4; i++ ) {
-                       dst[dstIndex++] = (byte)0x00;
-               }
-               writeInt2( writeMode, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( remaining, dst, dstIndex );
-               dstIndex += 2;
-               dst[dstIndex++] = (byte)0x00;
-               dst[dstIndex++] = (byte)0x00;
-               writeInt2( dataLength, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( dataOffset, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( offset >> 32, dst, dstIndex );
-               dstIndex += 4;
+        writeInt2( fid, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( offset, dst, dstIndex );
+        dstIndex += 4;
+        for( int i = 0; i < 4; i++ ) {
+            dst[dstIndex++] = (byte)0x00;
+        }
+        writeInt2( writeMode, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( remaining, dst, dstIndex );
+        dstIndex += 2;
+        dst[dstIndex++] = (byte)0x00;
+        dst[dstIndex++] = (byte)0x00;
+        writeInt2( dataLength, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( dataOffset, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( offset >> 32, dst, dstIndex );
+        dstIndex += 4;
 
-               return dstIndex - start;
-       }
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+        return dstIndex - start;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
 /* Netware doesn't like this
- *             while( pad-- > 0 ) {
- *                     dst[dstIndex++] = (byte)0x00;
- *             }
+ *      while( pad-- > 0 ) {
+ *          dst[dstIndex++] = (byte)0x00;
+ *      }
  */
-               System.arraycopy( b, off, dst, dstIndex, dataLength );
-               dstIndex += dataLength;
+        System.arraycopy( b, off, dst, dstIndex, dataLength );
+        dstIndex += dataLength;
 
-               return dstIndex - start;
-       }
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
-               return 0;
-       }
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
-               return 0;
-       }
-       public String toString() {
-               return new String( "SmbComWriteAndX[" +
-                       super.toString() +
-                       ",fid=" + fid +
-                       ",offset=" + offset +
-                       ",writeMode=" + writeMode +
-                       ",remaining=" + remaining +
-                       ",dataLength=" + dataLength +
-                       ",dataOffset=" + dataOffset + "]" );
-       }
+        return dstIndex - start;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComWriteAndX[" +
+            super.toString() +
+            ",fid=" + fid +
+            ",offset=" + offset +
+            ",writeMode=" + writeMode +
+            ",remaining=" + remaining +
+            ",dataLength=" + dataLength +
+            ",dataOffset=" + dataOffset + "]" );
+    }
 }
index c1219aa..db6d880 100644 (file)
@@ -1,52 +1,53 @@
-/* jcifs smb client library in Java\r
- * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>\r
- * \r
- * This library is free software; you can redistribute it and/or\r
- * modify it under the terms of the GNU Lesser General Public\r
- * License as published by the Free Software Foundation; either\r
- * version 2.1 of the License, or (at your option) any later version.\r
- * \r
- * This library is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
- * Lesser General Public License for more details.\r
- * \r
- * You should have received a copy of the GNU Lesser General Public\r
- * License along with this library; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
- */\r
-\r
-package jcifs.smb;\r
-\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-\r
-class SmbComWriteAndXResponse extends AndXServerMessageBlock {\r
-\r
-       long count;\r
-\r
-       SmbComWriteAndXResponse() {\r
-       }\r
-\r
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {\r
-               return 0;\r
-       }\r
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {\r
-               return 0;\r
-       }\r
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {\r
-               count = readInt2( buffer, bufferIndex ) & 0xFFFFL;\r
-               return 8;\r
-       }\r
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {\r
-               return 0;\r
-       }\r
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {\r
-               return 0;\r
-       }\r
-       public String toString() {\r
-               return new String( "SmbComWriteAndXResponse[" +\r
-                       super.toString() +\r
-                       ",count=" + count + "]" );\r
-       }\r
-}\r
+/* jcifs smb client library in Java
+ * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package jcifs.smb;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+class SmbComWriteAndXResponse extends AndXServerMessageBlock {
+
+    long count;
+
+    SmbComWriteAndXResponse() {
+    }
+
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        count = readInt2( buffer, bufferIndex ) & 0xFFFFL;
+        return 8;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount,
+                byte[] buffer, int bufferIndex ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComWriteAndXResponse[" +
+            super.toString() +
+            ",count=" + count + "]" );
+    }
+}
index 91fa552..e263395 100644 (file)
@@ -1,52 +1,52 @@
-/* jcifs smb client library in Java\r
- * Copyright (C) 2003  "Michael B. Allen" <jcifs at samba dot org>\r
- * \r
- * This library is free software; you can redistribute it and/or\r
- * modify it under the terms of the GNU Lesser General Public\r
- * License as published by the Free Software Foundation; either\r
- * version 2.1 of the License, or (at your option) any later version.\r
- * \r
- * This library is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
- * Lesser General Public License for more details.\r
- * \r
- * You should have received a copy of the GNU Lesser General Public\r
- * License along with this library; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
- */\r
-\r
-package jcifs.smb;\r
-\r
-import java.io.IOException;\r
-import java.io.InputStream;\r
-\r
-class SmbComWriteResponse extends ServerMessageBlock {\r
-\r
-       long count;\r
-\r
-       SmbComWriteResponse() {\r
-       }\r
-\r
-       int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {\r
-               return 0;\r
-       }\r
-       int writeBytesWireFormat( byte[] dst, int dstIndex ) {\r
-               return 0;\r
-       }\r
-       int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {\r
-               count = readInt2( buffer, bufferIndex ) & 0xFFFFL;\r
-               return 8;\r
-       }\r
-       int readBytesWireFormat( byte[] buffer, int bufferIndex ) {\r
-               return 0;\r
-       }\r
-       int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {\r
-               return 0;\r
-       }\r
-       public String toString() {\r
-               return new String( "SmbComWriteResponse[" +\r
-                       super.toString() +\r
-                       ",count=" + count + "]" );\r
-       }\r
-}\r
+/* jcifs smb client library in Java
+ * Copyright (C) 2003  "Michael B. Allen" <jcifs at samba dot org>
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package jcifs.smb;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+class SmbComWriteResponse extends ServerMessageBlock {
+
+    long count;
+
+    SmbComWriteResponse() {
+    }
+
+    int writeParameterWordsWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeBytesWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParameterWordsWireFormat( byte[] buffer, int bufferIndex ) {
+        count = readInt2( buffer, bufferIndex ) & 0xFFFFL;
+        return 8;
+    }
+    int readBytesWireFormat( byte[] buffer, int bufferIndex ) {
+        return 0;
+    }
+    int readBytesDirectWireFormat( InputStream in, int byteCount ) throws IOException {
+        return 0;
+    }
+    public String toString() {
+        return new String( "SmbComWriteResponse[" +
+            super.toString() +
+            ",count=" + count + "]" );
+    }
+}
index 0024fd3..bf9358e 100644 (file)
 package jcifs.smb;
 
 import java.io.IOException;
-import jcifs.UniAddress;
-
-/**
- * There are hundreds of error codes that may be returned by a CIFS server. Rather than represent each with it's own <code>Exception</code> class, this class represents all of them. For many of the popular error codes, constants and text messages like "The device is not ready" are provided.
-<p>
- * See <a href="../../../authhandler.html">jCIFS Exceptions and NtlmAuthenticator</a> for more information about <code>SmbException</code>.
- */
-
-public class SmbException extends IOException {
-
-       // error classes
-       public static final int SUCCESS = 0;
-       public static final int ERRDOS  = 0x01;
-       public static final int ERRSRV  = 0x02;
-       public static final int ERRHRD  = 0x03;
-       public static final int ERRCMD  = 0xFF;
-       public static final int ERRRAP  = 0x10;
-       public static final int ERRCLI  = 0x20;
-
-       // dos error codes
-/**
- *  Invalid function
- */
-       public static final int ERRbadfunc        = 1;
-/**
- * File not found
- */
-       public static final int ERRbadfile        = 2;
-/**
- * Directory invalid
- */
-       public static final int ERRbadpath        = 3;
-/**
- * Access denied
- */
-       public static final int ERRnoaccess   = 5;
-       public static final int ERRbadfid     = 6;
-/**
- * Not enough storage is available to process this command
- */
-       public static final int ERRnospace    = 8;
-/**
- * The file is being used by another process
- */
-       public static final int ERRbadshare   = 32;
-/**
- * A duplicate name exists on the network
- */
-       public static final int ERRdupname    = 52;
-/**
- * The network name cannot be found
- */
-       public static final int ERRbadnetname = 67;
-       public static final int ERRnomoreconn = 71;
-       public static final int ERRbadparm        = 87;
-/**
- * Cannot create a file when that file already exists
- */
-       public static final int ERRfilexists  = 80;
-/**
- * Too many Uids active on this session
- */
-       public static final int ERRtoomanyuids = 90;
-/**
- * The pipe has been ended
- */
-       public static final int ERRbrokenpipe = 109;
-/**
- * Invalid name
- */
-       public static final int ERRinvname        = 123;
-/**
- * The directory is not empty
- */
-       public static final int ERRnotempty   = 145;
-/**
- * File exists
- */
-       public static final int ERRexists     = 183;
-/**
- * All pipe instances are busy
- */
-       public static final int ERRpipebusy   = 231;
-/**
- * The pipe is being closed
- */
-       public static final int ERRnodata     = 232;
-/**
- * No process is on the other end of the pipe
- */
-       public static final int ERRnoproc     = 233;
-
-       // srv error codes
-/**
- * Non-specific error code
- */
-       public static final int ERRerror           = 1;
-/**
- * Bad password
- */
-       public static final int ERRbadpw           = 2;
-/**
- * Reserved (a.k.a. STATUS_PATH_NOT_COVERED)
- */
-       public static final int ERRreserved  = 3;
-/**
- * The client does not have the necessary access rights for the requested function
- */
-       public static final int ERRaccess          = 4;
-       public static final int ERRinvnid          = 5;
-       public static final int ERRinvnetname      = 6;
-       public static final int ERRbaduid          = 91;
-/**
- * The user account has expired
- */
-       public static final int ERRaccountExpired  = 2239;
-/**
- * The user is not allowed to access this server from this client
- */
-       public static final int ERRbadClient       = 2240;
-/**
- * The user is not permitted to access the server at this time
- */
-       public static final int ERRbadLogonTime    = 2241;
-/**
- * The password of the user has expired
- */
-       public static final int ERRpasswordExpired = 2242;
-
-/**
- * The list of servers for this workgroup is not currently available
- */
-       public static final int ERRnolisting = 6118;
-
-       // hrd error codes
-/**
- * Attempt to write on write-protected media
- */
-       public static final int ERRnowrite  = 19;
-/**
- * The device is not ready
- */
-       public static final int ERRnotready = 21;
-/**
- * General failure
- */
-       public static final int ERRgeneral = 31;
-
-       // RAP transaction status codes
-       public static final int NERR_Success                = 0;
-       public static final int ERROR_MORE_DATA             = 234;
-       public static final int NERR_ServerNotStarted       = 2114;
-       public static final int NERR_BasicTransactConfig    = 2141;
-
-       // cli error codes (defined for jCIFS)
-       public static final int ERRserverTimeout = 5000;
-       public static final int ERRbadDialect    = 5001;
-       public static final int ERRioe           = 5002;
-       public static final int ERRlistFiles     = 5003;
-       public static final int ERRunknownHost   = 5004;
-       public static final int ERRinappro       = 5005;
-       public static final int ERRunknownType   = 5006;
-       public static final int ERRdfs           = 5007;
-       public static final int ERRhashesExternal = 5008;
-       public static final int ERRimpossible    = 5009;
-
-       int errorClass;
-       int errorCode;
-
-       static String getErrorString( int errorClass, int errorCode ) {
-               String result = "";
-               switch( errorClass ) {
-                       case SUCCESS:
-                               result += "The operation completed successfully";
-                               break;
-                       case ERRDOS:
-                               switch( errorCode ) {
-                                       case ERRbadfunc:
-                                               result += "Invalid function";
-                                               break;
-                                       case ERRbadfile:
-                                               result += "File not found";
-                                               break;
-                                       case ERRbadpath:
-                                               result += "Directory invalid";
-                                               break;
-                                       case ERRnoaccess:
-                                               result += "Access denied";
-                                               break;
-                                       case ERRbadparm:
-                                               result += "Invalid parameter";
-                                               break;
-                                       case ERRinvname:
-                                               result += "Invalid name";
-                                               break;
-                                       case ERRnotempty:
-                                               result += "The directory is not empty";
-                                               break;
-                                       case ERRfilexists:
-                                               result += "Cannot create a file when that file already exists";
-                                               break;
-                                       case ERRbadfid:
-                                               result += "Invalid file handle";
-                                               break;
-                                       case ERRnospace:
-                                               result += "Not enough storage is available to process this command";
-                                               break;
-                                       case ERRbadshare:
-                                               result += "The file is being used by another process";
-                                               break;
-                                       case ERRdupname:
-                                               result += "A duplicate name exists on the network";
-                                               break;
-                                       case ERRnotready:
-                                               result += "The device is not ready";
-                                               break;
-                                       case ERRbadnetname:
-                                               result += "The network name cannot be found";
-                                               break;
-                                       case ERRexists:
-                                               result += "File exists";
-                                               break;
-                                       case ERRpipebusy:
-                                               result += "All pipe instances are busy";
-                                               break;
-                                       case ERRnodata:
-                                               result += "The pipe is being closed";
-                                               break;
-                                       case ERRnoproc:
-                                               result += "No process is on the other end of the pipe";
-                                               break;
-                                       case ERRbrokenpipe:
-                                               result += "The pipe has been ended";
-                                               break;
-                                       case ERRnomoreconn:
-                                               result += "No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept";
-                                               break;
-                                       default:
-                                               result += "No description available [ERRDOS/" + errorCode + "]";
-                               }
-                               break;
-                       case ERRSRV:
-                               switch( errorCode ) {
-                                       case ERRerror:
-                                               result += "Non-specific error code";
-                                               break;
-                                       case ERRbadpw:
-                                               result += "Bad password";
-                                               break;
-                                       case ERRreserved:
-                                               result += "Reserved";
-                                               break;
-                                       case ERRinvnid:
-                                               result += "The Tid specified was invalid";
-                                               break;
-                                       case ERRinvnetname:
-                                               result += "Invalid network name in tree connect, service not found";
-                                               break;
-                                       case ERRbaduid:
-                                               result += "The UID is not known as a valid user identifier on this session";
-                                               break;
-                                       case ERRaccess:
-                                               result += "The client does not have the necessary access rights for the requested function";
-                                               break;
-                                       case ERRaccountExpired:
-                                               result += "The user account has expired";
-                                               break;
-                                       case ERRbadClient:
-                                               result += "The user is not allowed to access this server from this client";
-                                               break;
-                                       case ERRbadLogonTime:
-                                               result += "The user is not permitted to access the server at this time";
-                                               break;
-                                       case ERRpasswordExpired:
-                                               result += "The password of the user has expired";
-                                               break;
-                                       case ERRtoomanyuids:
-                                               result += "Too many Uids active on this session";
-                                               break;
-                                       default:
-                                               result += "No description available [ERRSRV/" + errorCode + "]";
-                               }
-                               break;
-                       case ERRHRD:
-                               switch( errorCode ) {
-                                       case ERRnowrite:
-                                               result += "Attempt to write on write-protected media";
-                                               break;
-                                       case ERRnotready:
-                                               result += "The device is not ready";
-                                               break;
-                                       case ERRgeneral:
-                                               result += "General failure";
-                                               break;
-                                       default:
-                                               result += "No description available [ERRHRD/" + errorCode + "]";
-                               }
-                               break;
-                       case ERRCMD:
-                               result += "Command was not in the \"SMB\" format";
-                               break;
-                       case ERRRAP:
-                               // I don't think this should be here.
-                               // Should switch to NT status codes.
-                               switch( errorCode ) {
-                                       case NERR_Success:
-                                               result += "The operation completed successfully";
-                                               break;
-                                       case ERRnowrite:
-                                               NERR_ServerNotStarted:
-                                               result += "The Server service is not started";
-                                               break;
-                                       case NERR_BasicTransactConfig:
-                                               result += "The server is not configured for transactions";
-                                               break;
-                                       case ERRnolisting:
-                                               result += "The list of servers for this workgroup is not currently available";
-                                               break;
-                                       default:
-                                               result += "No description available [ERRRAP/" + errorCode + "]";
-                               }
-                               break;
-                       case ERRCLI:
-                               switch( errorCode ) {
-                                       case ERRserverTimeout:
-                                               result += "Timeout waiting for response from server.";
-                                               break;
-                                       case ERRbadDialect:
-                                               result += "Failed to negotiate dialect with server.";
-                                               break;
-                                       case ERRioe:
-                                               result += "An IO error occured.";
-                                               break;
-                                       case ERRlistFiles:
-                                               result += "The derived URL was malformed or a name service error occured during a listFiles() operation (this should not be possible, please report it to jcifs at samba dot org)";
-                                               break;
-                                       case ERRunknownHost:
-                                               result += "The hostname retrived from the Browser service is no longer valid";
-                                               break;
-                                       case ERRinappro:
-                                               result += "Inappropriate operation";
-                                               break;
-                                       case ERRunknownType:
-                                               result += "Unknown resource type";
-                                               break;
-                                       case ERRdfs:
-                                               result += "Invalid DFS operation";
-                                               break;
-                                       case ERRhashesExternal:
-                                               result += "The password hashes are external.";
-                                               break;
-                                       default:
-                                               result += "No description available [ERRCLI/" + errorCode + "]";
-                               }
-                               break;
-                       default:
-                               result += "unknown error class: " + errorClass;
-               }
-               return result;
-       }
-       static String getErrorString( int code ) {
-               if( code == 0 ) {
-                       return "0x00000000";
-               }
-               return getErrorString( code & 0xFF, ( code >> 16 ) & 0xFFFF );
-       }
-
-       SmbException() {
-       }
-       SmbException( int code ) {
-               super( getErrorString( code & 0xFF, ( code >> 16 ) & 0xFFFF ));
-               errorClass = code & 0xFF;
-               errorCode = ( code >> 16 ) & 0xFFFF;
-       }
-       SmbException( int errorClass, int errorCode ) {
-               super( getErrorString( errorClass, errorCode ));
-               this.errorClass = errorClass;
-               this.errorCode = errorCode;
-       }
-       SmbException( int errorClass, int errorCode, UniAddress addr ) {
-               super( getErrorString( errorClass, errorCode ) + " " + addr.toString() );
-               this.errorClass = errorClass;
-               this.errorCode = errorCode;
-       }
-       SmbException( int errorClass, int errorCode, String message ) {
-               super( message );
-               this.errorClass = errorClass;
-               this.errorCode = errorCode;
-       }
-       SmbException( int code, String message ) {
-               super( message );
-               errorClass = code & 0xFF;
-               errorCode = ( code >> 16 ) & 0xFFFF;
-       }
-
-       /**
-        * Retrieve the error class associated with this error.
-        */
-       public int getErrorClass() {
-               return errorClass;
-       }
-
-       /**
-        * Retrieve the error code associated with this error.
-        */
-       public int getErrorCode() {
-               return errorCode;
-       }
+import java.io.StringWriter;
+import java.io.PrintWriter;
+import jcifs.util.Hexdump;
+
+/**
+ * There are hundreds of error codes that may be returned by a CIFS
+ * server. Rather than represent each with it's own <code>Exception</code>
+ * class, this class represents all of them. For many of the popular
+ * error codes, constants and text messages like "The device is not ready"
+ * are provided.
+ * <p>
+ * The jCIFS client maps DOS error codes to NTSTATUS codes. This means that
+ * the user may recieve a different error from a legacy server than that of
+ * a newer varient such as Windows NT and above. If you should encounter
+ * such a case, please report it to jcifs at samba dot org and we will
+ * change the mapping.
+ */
+
+public class SmbException extends IOException implements NtStatus, DosError, WinError {
+
+    static String getMessageByCode( int errcode ) {
+        if(( errcode & 0xC0000000 ) == 0xC0000000 ) {
+            int min = 0;
+            int max = NT_STATUS_CODES.length;
+
+            while( max >= min ) {
+                int mid = (min + max) / 2;
+
+                if( errcode > NT_STATUS_CODES[mid] ) {
+                    min = mid + 1;
+                } else if( errcode < NT_STATUS_CODES[mid] ) {
+                    max = mid - 1;
+                } else {
+                    return NT_STATUS_MESSAGES[mid];
+                }
+            }
+        } else {
+            int min = 0;
+            int max = DOS_ERROR_CODES.length;
+
+            while( max >= min ) {
+                int mid = (min + max) / 2;
+
+                if( errcode > DOS_ERROR_CODES[mid][0] ) {
+                    min = mid + 1;
+                } else if( errcode < DOS_ERROR_CODES[mid][0] ) {
+                    max = mid - 1;
+                } else {
+                    return DOS_ERROR_MESSAGES[mid];
+                }
+            }
+        }
+
+        return "0x" + Hexdump.toHexString( errcode, 8 );
+    }
+    static int getStatusByCode( int errcode ) {
+        if(( errcode & 0xC0000000 ) == 0xC0000000 ) {
+            return errcode;
+        } else {
+            int min = 0;
+            int max = DOS_ERROR_CODES.length;
+
+            while( max >= min ) {
+                int mid = (min + max) / 2;
+
+                if( errcode > DOS_ERROR_CODES[mid][0] ) {
+                    min = mid + 1;
+                } else if( errcode < DOS_ERROR_CODES[mid][0] ) {
+                    max = mid - 1;
+                } else {
+                    return DOS_ERROR_CODES[mid][1];
+                }
+            }
+        }
+
+        return NT_STATUS_UNSUCCESSFUL;
+    }
+    static String getMessageByWinerrCode( int errcode ) {
+        int min = 0;
+        int max = WINERR_CODES.length;
+
+        while( max >= min ) {
+            int mid = (min + max) / 2;
+
+            if( errcode > WINERR_CODES[mid] ) {
+                min = mid + 1;
+            } else if( errcode < WINERR_CODES[mid] ) {
+                max = mid - 1;
+            } else {
+                return WINERR_MESSAGES[mid];
+            }
+        }
+
+        return errcode + "";
+    }
+
+
+    private int status;
+    private Throwable rootCause;
+
+    SmbException() {
+    }
+    SmbException( int errcode, Throwable rootCause ) {
+        super( getMessageByCode( errcode ));
+        status = getStatusByCode( errcode );
+        this.rootCause = rootCause;
+    }
+    SmbException( String msg ) {
+        super( msg );
+        status = NT_STATUS_UNSUCCESSFUL;
+    }
+    SmbException( String msg, Throwable rootCause ) {
+        super( msg );
+        this.rootCause = rootCause;
+        status = NT_STATUS_UNSUCCESSFUL;
+    }
+    SmbException( int errcode, boolean winerr ) {
+        super( winerr ? getMessageByWinerrCode( errcode ) : getMessageByCode( errcode ));
+        status = winerr ? errcode : getStatusByCode( errcode );
+    }
+
+    public int getNtStatus() {
+        return status;
+    }
+    public Throwable getRootCause() {
+        return rootCause;
+    }
+    public String toString() {
+        if( rootCause != null ) {
+            StringWriter sw = new StringWriter();
+            PrintWriter pw = new PrintWriter( sw );
+            rootCause.printStackTrace( pw );
+            return super.toString() + "\n" + sw;
+        } else {
+            return super.toString();
+        }
+    }
 }
+
index 0920ef4..4f83144 100644 (file)
@@ -26,7 +26,8 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.util.ArrayList;
-import jcifs.util.Config;
+import jcifs.Config;
+import jcifs.util.LogStream;
 import jcifs.UniAddress;
 import jcifs.netbios.NbtAddress;
 
@@ -173,75 +174,75 @@ When used in conjunction with the <code>list</code>
  * <b>First Parameter</b></td><td><b>Second Parameter</b></td><td><b>Result</b></td></tr>
  *
  * <tr><td width="20%"><code>
- *     smb://host/share/a/b/
+ *  smb://host/share/a/b/
  * </code></td><td width="20%"><code>
- *     c/d/
+ *  c/d/
  * </code></td><td><code>
- *     smb://host/share/a/b/c/d/
+ *  smb://host/share/a/b/c/d/
  * </code></td></tr>
  * 
  * <tr><td width="20%"><code>
- *     smb://host/share/foo/bar/
+ *  smb://host/share/foo/bar/
  * </code></td><td width="20%"><code>
- *     /share2/zig/zag
+ *  /share2/zig/zag
  * </code></td><td><code>
- *     smb://host/share2/zig/zag
+ *  smb://host/share2/zig/zag
  * </code></td></tr>
  * 
  * <tr><td width="20%"><code>
- *     smb://host/share/foo/bar/
+ *  smb://host/share/foo/bar/
  * </code></td><td width="20%"><code>
- *     ../zip/
+ *  ../zip/
  * </code></td><td><code>
- *     smb://host/share/foo/zip/
+ *  smb://host/share/foo/zip/
  * </code></td></tr>
  * 
  * <tr><td width="20%"><code>
- *     smb://host/share/zig/zag
+ *  smb://host/share/zig/zag
  * </code></td><td width="20%"><code>
- *     smb://foo/bar/
+ *  smb://foo/bar/
  * </code></td><td><code>
- *     smb://foo/bar/
+ *  smb://foo/bar/
  * </code></td></tr>
  * 
  * <tr><td width="20%"><code>
- *     smb://host/share/foo/
+ *  smb://host/share/foo/
  * </code></td><td width="20%"><code>
- *     ../.././.././../foo/
+ *  ../.././.././../foo/
  * </code></td><td><code>
- *     smb://host/foo/
+ *  smb://host/foo/
  * </code></td></tr>
  * 
  * <tr><td width="20%"><code>
- *     smb://host/share/zig/zag
+ *  smb://host/share/zig/zag
  * </code></td><td width="20%"><code>
- *     /
+ *  /
  * </code></td><td><code>
- *     smb://host/
+ *  smb://host/
  * </code></td></tr>
  * 
  * <tr><td width="20%"><code>
- *     smb://server/
+ *  smb://server/
  * </code></td><td width="20%"><code>
- *     ../
+ *  ../
  * </code></td><td><code>
- *     smb://server/
+ *  smb://server/
  * </code></td></tr>
  * 
  * <tr><td width="20%"><code>
- *     smb://
+ *  smb://
  * </code></td><td width="20%"><code>
- *     myworkgroup/
+ *  myworkgroup/
  * </code></td><td><code>
- *     smb://myworkgroup/
+ *  smb://myworkgroup/
  * </code></td></tr>
  * 
  * <tr><td width="20%"><code>
- *     smb://myworkgroup/
+ *  smb://myworkgroup/
  * </code></td><td width="20%"><code>
- *     angus/
+ *  angus/
  * </code></td><td><code>
- *     smb://myworkgroup/angus/ &lt;-- ILLEGAL<br>(But if you first create an <tt>SmbFile</tt> with 'smb://workgroup/' and use and use it as the first parameter to a constructor that accepts it with a second <tt>String</tt> parameter jCIFS will factor out the 'workgroup'.)
+ *  smb://myworkgroup/angus/ &lt;-- ILLEGAL<br>(But if you first create an <tt>SmbFile</tt> with 'smb://workgroup/' and use and use it as the first parameter to a constructor that accepts it with a second <tt>String</tt> parameter jCIFS will factor out the 'workgroup'.)
  * </code></td></tr>
  * 
  * </table>
@@ -255,125 +256,127 @@ When used in conjunction with the <code>list</code>
 
 public class SmbFile extends URLConnection {
 
-       // these are shifted for use in flags
-       static final int O_RDONLY = 0x010000;
-       static final int O_WRONLY = 0x020000;
-       static final int O_RDWR   = 0x030000;
-       static final int O_APPEND = 0x040000;
+    // these are shifted for use in flags
+    static final int O_RDONLY = 0x010000;
+    static final int O_WRONLY = 0x020000;
+    static final int O_RDWR   = 0x030000;
+    static final int O_APPEND = 0x040000;
 
-       // share access
+    // share access
 /**
  * When specified as the <tt>shareAccess</tt> constructor parameter, other SMB clients (including other threads macking calls into jCIFS) will not be permitted to access the target file and will receive "The file is being accessed by another process" message.
  */
-       public static final int FILE_NO_SHARE     = 0x00;
+    public static final int FILE_NO_SHARE     = 0x00;
 /**
  * When specified as the <tt>shareAccess</tt> constructor parameter, other SMB clients will be permitted to read from the target file while this file is open. This constant may be logically OR'd with other share access flags.
  */
-       public static final int FILE_SHARE_READ   = 0x01;
+    public static final int FILE_SHARE_READ   = 0x01;
 /**
  * When specified as the <tt>shareAccess</tt> constructor parameter, other SMB clients will be permitted to write to the target file while this file is open. This constant may be logically OR'd with other share access flags.
  */
-       public static final int FILE_SHARE_WRITE  = 0x02;
+    public static final int FILE_SHARE_WRITE  = 0x02;
 /**
  * When specified as the <tt>shareAccess</tt> constructor parameter, other SMB clients will be permitted to delete the target file while this file is open. This constant may be logically OR'd with other share access flags.
  */
-       public static final int FILE_SHARE_DELETE = 0x04;
-
-       // Open Function Encoding
-       // create if the file does not exist
-       static final int O_CREAT  = 0x0010;
-       // fail if the file exists
-       static final int O_EXCL   = 0x0001;
-       // truncate if the file exists
-       static final int O_TRUNC  = 0x0002;
-
-       // file attribute encoding
-       public static final int ATTR_READONLY   = 0x01;
-       public static final int ATTR_HIDDEN     = 0x02;
-       public static final int ATTR_SYSTEM     = 0x04;
-       public static final int ATTR_VOLUME     = 0x08;
-       public static final int ATTR_DIRECTORY  = 0x10;
-       public static final int ATTR_ARCHIVE    = 0x20;
-
-       // extended file attribute encoding(others same as above)
-       static final int ATTR_COMPRESSED       = 0x800;
-       static final int ATTR_NORMAL           = 0x080;
-       static final int ATTR_TEMPORARY        = 0x100;
-
-       static final int ATTR_GET_MASK = 0x3F;
-       static final int ATTR_SET_MASK = 0x27;
-
-       static final int DEFAULT_ATTR_EXPIRATION_PERIOD = 5000;
-
-       static final int HASH_DOT     = ".".hashCode();
-       static final int HASH_DOT_DOT = "..".hashCode();
-
-       static long attrExpirationPeriod;
-
-       static {
-               try {
-                       Class.forName( "jcifs.Config" );
-               } catch( ClassNotFoundException cnfe ) {
-                       cnfe.printStackTrace();
-               }
-               attrExpirationPeriod = Config.getLong( "jcifs.smb.client.attrExpirationPeriod", DEFAULT_ATTR_EXPIRATION_PERIOD );
-       }
-
-       /**
-        * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
-        * represents is a regular file or directory.
-        */
-       public static final int TYPE_FILESYSTEM = 0x01;
-       /**
-        * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
-        * represents is a workgroup.
-        */
-       public static final int TYPE_WORKGROUP = 0x02;
-       /**
-        * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
-        * represents is a server.
-        */
-       public static final int TYPE_SERVER = 0x04;
-       /**
-        * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
-        * represents is a share.
-        */
-       public static final int TYPE_SHARE = 0x08;
-       /**
-        * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
-        * represents is a named pipe.
-        */
-       public static final int TYPE_NAMED_PIPE = 0x10;
-       /**
-        * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
-        * represents is a printer.
-        */
-       public static final int TYPE_PRINTER = 0x20;
-       /**
-        * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
-        * represents is a communications device.
-        */
-       public static final int TYPE_COMM = 0x40;
-
-
-       SmbTree tree = null;             // Initially null; may be !tree.treeConnected
-       String canon;                    // Initially null; set by getUncPath; dir must end with '/'
-       String unc;                      // Initially null; set by getUncPath; never ends with '/'
-       String share;                    // Can be null
-       int fid;                         // Initially 0; set by open()
-       int type;
-       long createTime;
-       long lastModified;
-       int attributes;
-       long attrExpiration;
-       long size;
-       long sizeExpiration;
-       NtlmPasswordAuthentication auth; // Cannot be null
-       boolean opened;
-       boolean isExists;
-       int shareAccess = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
-       SmbComBlankResponse blank_resp = new SmbComBlankResponse();
-       DfsReferral dfsReferral = null;  // Only used by getDfsPath()
+    public static final int FILE_SHARE_DELETE = 0x04;
+
+    // Open Function Encoding
+    // create if the file does not exist
+    static final int O_CREAT  = 0x0010;
+    // fail if the file exists
+    static final int O_EXCL   = 0x0001;
+    // truncate if the file exists
+    static final int O_TRUNC  = 0x0002;
+
+    // file attribute encoding
+    public static final int ATTR_READONLY   = 0x01;
+    public static final int ATTR_HIDDEN     = 0x02;
+    public static final int ATTR_SYSTEM     = 0x04;
+    public static final int ATTR_VOLUME     = 0x08;
+    public static final int ATTR_DIRECTORY  = 0x10;
+    public static final int ATTR_ARCHIVE    = 0x20;
+
+    // extended file attribute encoding(others same as above)
+    static final int ATTR_COMPRESSED       = 0x800;
+    static final int ATTR_NORMAL           = 0x080;
+    static final int ATTR_TEMPORARY        = 0x100;
+
+    static final int ATTR_GET_MASK = 0x3F;
+    static final int ATTR_SET_MASK = 0x27;
+
+    static final int DEFAULT_ATTR_EXPIRATION_PERIOD = 5000;
+
+    static final int HASH_DOT     = ".".hashCode();
+    static final int HASH_DOT_DOT = "..".hashCode();
+
+    static LogStream log = LogStream.getInstance();
+    static long attrExpirationPeriod;
+
+    static {
+        try {
+            Class.forName( "jcifs.Config" );
+        } catch( ClassNotFoundException cnfe ) {
+            cnfe.printStackTrace();
+        }
+        attrExpirationPeriod = Config.getLong( "jcifs.smb.client.attrExpirationPeriod", DEFAULT_ATTR_EXPIRATION_PERIOD );
+    }
+
+    /**
+     * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
+     * represents is a regular file or directory.
+     */
+    public static final int TYPE_FILESYSTEM = 0x01;
+    /**
+     * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
+     * represents is a workgroup.
+     */
+    public static final int TYPE_WORKGROUP = 0x02;
+    /**
+     * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
+     * represents is a server.
+     */
+    public static final int TYPE_SERVER = 0x04;
+    /**
+     * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
+     * represents is a share.
+     */
+    public static final int TYPE_SHARE = 0x08;
+    /**
+     * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
+     * represents is a named pipe.
+     */
+    public static final int TYPE_NAMED_PIPE = 0x10;
+    /**
+     * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
+     * represents is a printer.
+     */
+    public static final int TYPE_PRINTER = 0x20;
+    /**
+     * Returned by {@link #getType()} if the resource this <tt>SmbFile</tt>
+     * represents is a communications device.
+     */
+    public static final int TYPE_COMM = 0x40;
+
+
+    private String canon;            // Initially null; set by getUncPath; dir must end with '/'
+    private String share;            // Can be null
+    private long createTime;
+    private long lastModified;
+    private int attributes;
+    private long attrExpiration;
+    private long size;
+    private long sizeExpiration;
+    private NtlmPasswordAuthentication auth; // Cannot be null
+    private boolean isExists;
+    private int shareAccess = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
+    private SmbComBlankResponse blank_resp = null;
+    private DfsReferral dfsReferral = null;  // Only used by getDfsPath()
+
+    SmbTree tree = null;             // Initially null; may be !tree.treeConnected
+    String unc;                      // Initially null; set by getUncPath; never ends with '/'
+    int fid;                         // Initially 0; set by open()
+    int type;
+    boolean opened;
 
 /** 
  * Constructs an SmbFile representing a resource on an SMB network such as
@@ -385,9 +388,9 @@ public class SmbFile extends URLConnection {
  *          do not follow the prescribed syntax
  */
 
-       public SmbFile( String url ) throws MalformedURLException {
-               this( new URL( null, url, Handler.SMB_HANDLER ));
-       }
+    public SmbFile( String url ) throws MalformedURLException {
+        this( new URL( null, url, Handler.SMB_HANDLER ));
+    }
 
 /**
  * Constructs an SmbFile representing a resource on an SMB network such
@@ -404,11 +407,11 @@ public class SmbFile extends URLConnection {
  *          If the server or workgroup of the <tt>context</tt> file cannot be determined
  */
 
-       public SmbFile( SmbFile context, String name ) throws MalformedURLException, UnknownHostException {
-               this( context.isWorkgroup0() ?
-                       new URL( null, "smb://" + name, Handler.SMB_HANDLER ) :
-                       new URL( context.url, name, Handler.SMB_HANDLER ), context.auth );
-       }
+    public SmbFile( SmbFile context, String name ) throws MalformedURLException, UnknownHostException {
+        this( context.isWorkgroup0() ?
+            new URL( null, "smb://" + name, Handler.SMB_HANDLER ) :
+            new URL( context.url, name, Handler.SMB_HANDLER ), context.auth );
+    }
 
 /**
  * Constructs an SmbFile representing a resource on an SMB network such
@@ -423,9 +426,9 @@ public class SmbFile extends URLConnection {
  *          do not follow the prescribed syntax
  */
 
-       public SmbFile( String context, String name ) throws MalformedURLException {
-               this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER ));
-       }
+    public SmbFile( String context, String name ) throws MalformedURLException {
+        this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER ));
+    }
 
 /**
  * Constructs an SmbFile representing a resource on an SMB network such
@@ -437,10 +440,10 @@ The second parameter may be constructed explicitly or retreived with <tt>HttpSer
  * @throws  MalformedURLException
  *          If the <code>url</code> parameter does not follow the prescribed syntax
  */
-       public SmbFile( String url, NtlmPasswordAuthentication auth )
-                                       throws MalformedURLException {
-               this( new URL( null, url, Handler.SMB_HANDLER ), auth );
-       }
+    public SmbFile( String url, NtlmPasswordAuthentication auth )
+                    throws MalformedURLException {
+        this( new URL( null, url, Handler.SMB_HANDLER ), auth );
+    }
 /**
  * Constructs an SmbFile representing a file on an SMB network.
 The second parameter may be constructed explicitly or retreived with <tt>HttpServletRequest.getUserPrincipal()</tt> if NTLM HTTP authentication has been successfully negotiated.
@@ -452,14 +455,14 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @throws  MalformedURLException
  *          If the <code>url</code> parameter does not follow the prescribed syntax
  */
-       public SmbFile( String url, NtlmPasswordAuthentication auth, int shareAccess )
-                                       throws MalformedURLException {
-               this( new URL( null, url, Handler.SMB_HANDLER ), auth );
-               if ((shareAccess & ~(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)) != 0) {
-                       throw new RuntimeException( "Illegal shareAccess parameter" );
-               }
-               this.shareAccess = shareAccess;
-       }
+    public SmbFile( String url, NtlmPasswordAuthentication auth, int shareAccess )
+                    throws MalformedURLException {
+        this( new URL( null, url, Handler.SMB_HANDLER ), auth );
+        if ((shareAccess & ~(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)) != 0) {
+            throw new RuntimeException( "Illegal shareAccess parameter" );
+        }
+        this.shareAccess = shareAccess;
+    }
 /**
  * Constructs an SmbFile representing a resource on an SMB network such
  * as a file or directory. The second parameter is a relative path from
@@ -474,10 +477,10 @@ The third parameter may be constructed explicitly or retreived with <tt>HttpServ
  *          If the <code>context</code> and <code>name</code> parameters
  *          do not follow the prescribed syntax
  */
-       public SmbFile( String context, String name, NtlmPasswordAuthentication auth )
-                                       throws MalformedURLException {
-               this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER ), auth );
-       }
+    public SmbFile( String context, String name, NtlmPasswordAuthentication auth )
+                    throws MalformedURLException {
+        this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER ), auth );
+    }
 /**
  * Constructs an SmbFile representing a resource on an SMB network such
  * as a file or directory. The second parameter is a relative path from
@@ -494,23 +497,23 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  *          If the <code>context</code> and <code>name</code> parameters
  *          do not follow the prescribed syntax
  */
-       public SmbFile( String context, String name, NtlmPasswordAuthentication auth, int shareAccess )
-                                       throws MalformedURLException {
-               this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER ), auth );
-               if ((shareAccess & ~(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)) != 0) {
-                       throw new RuntimeException( "Illegal shareAccess parameter" );
-               }
-               this.shareAccess = shareAccess;
-       }
+    public SmbFile( String context, String name, NtlmPasswordAuthentication auth, int shareAccess )
+                    throws MalformedURLException {
+        this( new URL( new URL( null, context, Handler.SMB_HANDLER ), name, Handler.SMB_HANDLER ), auth );
+        if ((shareAccess & ~(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)) != 0) {
+            throw new RuntimeException( "Illegal shareAccess parameter" );
+        }
+        this.shareAccess = shareAccess;
+    }
 /**
  * Constructs an SmbFile representing a resource on an SMB network such
  * as a file or directory from a <tt>URL</tt> object.
  *
  * @param   url The URL of the target resource
  */
-       public SmbFile( URL url ) {
-               this( url, new NtlmPasswordAuthentication( url.getUserInfo() ));
-       }
+    public SmbFile( URL url ) {
+        this( url, new NtlmPasswordAuthentication( url.getUserInfo() ));
+    }
 /**
  * Constructs an SmbFile representing a resource on an SMB network such
  * as a file or directory from a <tt>URL</tt> object and an <tt>NtlmPasswordAuthentication object which may be constructed explicitly or retreived with <tt>HttpServletRequest.getUserPrincipal()</tt> if NTLM HTTP authentication has been successfully negotiated.
@@ -518,237 +521,248 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @param   url The URL of the target resource
  * @param   auth The credentials the client should use for authentication
  */
-       public SmbFile( URL url, NtlmPasswordAuthentication auth ) {
-               super( url );
-               this.auth = auth == null ? new NtlmPasswordAuthentication( url.getUserInfo() ) : auth;
-
-               getUncPath0();
-       }
-       SmbFile( SmbFile context, String name, int type,
-                               int attributes, long createTime, long lastModified, long size )
-                               throws MalformedURLException, UnknownHostException {
-               this( new URL( context.url, name + (( attributes & ATTR_DIRECTORY ) > 0 ? "/" : "" )));
-               if( context.share != null ) {
-                       this.tree = context.tree;
-               }
-               int last = name.length() - 1;
-               if( name.charAt( last ) == '/' ) {
-                       name = name.substring( 0, last );
-               }
-               if( context.share == null ) {
-                       this.unc = "\\";
-               } else if( context.unc.equals( "\\" )) {
-                       this.unc = '\\' + name;
-               } else {
-                       this.unc = context.unc + '\\' + name;
-               }
-               this.type = type;
-               this.attributes = attributes;
-               this.createTime = createTime;
-               this.lastModified = lastModified;
-               this.size = size;
-               isExists = true;
-
-               attrExpiration = sizeExpiration =
-                               System.currentTimeMillis() + attrExpirationPeriod;
-       }
-       void sendTransaction( SmbComTransaction request,
-                                       SmbComTransactionResponse response ) throws SmbException {
-               for( ;; ) {
-                       connect0();
-                       if( tree.inDfs ) {
-                               DfsReferral dr = tree.session.transport.lookupReferral( unc );
-                               if( dr != null ) {
-                                       UniAddress addr;
-                                       SmbTransport trans;
-
-                                       try {
-                                               addr = UniAddress.getByName( dr.server );
-                                       } catch( UnknownHostException uhe ) {
-                                               throw new SmbException( SmbException.ERRCLI, SmbException.ERRdfs, "unknown host: " + dr.server );
-                                       }
-
-                                       trans = SmbTransport.getSmbTransport( addr, 0 );
-                                       tree = trans.getSmbSession( auth ).getSmbTree( dr.share, null );
-                                       unc = request.path = dr.nodepath + unc.substring( dr.path.length() );
-                                       dfsReferral = dr; /* for getDfsPath */
-                               }
-                       }
-                       if( tree.inDfs ) {
-                               request.flags2 |= ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS;
-                       } else {
-                               request.flags2 &= ~ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS;
-                       }
-                       try {
-                               tree.sendTransaction( request, response );
-                               break;
-                       } catch( DfsReferral dr ) {
-                               if( dr.resolveHashes ) {
-                                       throw dr;
-                               }
-                               request.reset();
-                       }
-               }
-       }
-       void send( ServerMessageBlock request,
-                                       ServerMessageBlock response ) throws SmbException {
-               for( ;; ) {
-                       connect0();
-                       if( tree.inDfs ) {
-                               DfsReferral dr = tree.session.transport.lookupReferral( unc );
-                               if( dr != null ) {
-                                       UniAddress addr;
-                                       SmbTransport trans;
-
-                                       try {
-                                               addr = UniAddress.getByName( dr.server );
-                                       } catch( UnknownHostException uhe ) {
-                                               throw new SmbException( SmbException.ERRCLI, SmbException.ERRdfs, "unknown host: " + dr.server );
-                                       }
-
-                                       trans = SmbTransport.getSmbTransport( addr, 0 );
-                                       tree = trans.getSmbSession( auth ).getSmbTree( dr.share, null );
-                                       unc = request.path = dr.nodepath + unc.substring( dr.path.length() );
-                                       dfsReferral = dr; /* for getDfsPath */
-                               }
-                               request.flags2 |= ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS;
-                       } else {
-                               request.flags2 &= ~ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS;
-                       }
-                       try {
-                               tree.send( request, response );
-                               break;
-                       } catch( DfsReferral dr ) {
-                               if( dr.resolveHashes ) {
-                                       throw dr;
-                               }
-                       }
-               }
-       }
-
-       UniAddress getAddress() throws UnknownHostException {
-               String host = url.getHost();
-               String path = url.getPath();
-
-               if( host.length() == 0 ) {
-                       return UniAddress.getByName( NbtAddress.getByName(
-                                       NbtAddress.MASTER_BROWSER_NAME, 0x01, null).getHostAddress() );
-               } else if( path.length() == 0 || path.equals( "/" )) {
-                       return UniAddress.getByName( host, true );
-               } else {
-                       return UniAddress.getByName( host );
-               }
-       }
-       void connect0() throws SmbException {
-               try {
-                       connect();
-               } catch( UnknownHostException uhe ) {
-                       throw new SmbException( SmbException.ERRCLI,
-                                                       SmbException.ERRunknownHost,
-                                                       "Unknown host: " + uhe.getMessage() );
-               } catch( SmbException se ) {
-                       throw se;
-               } catch( IOException ioe ) {
-                       throw new SmbException( SmbException.ERRCLI,
-                                                       SmbException.ERRioe,
-                                                       ioe.getMessage() );
-               }
-       }
-       public void connect() throws IOException {
-               SmbTransport trans;
-               SmbSession ssn;
-               UniAddress addr;
-
-               if( isConnected() ) {
-                       return;
-               }
-
-               getUncPath0();
-               addr = getAddress();
-
-               trans = SmbTransport.getSmbTransport( addr, url.getPort() );
-               ssn = trans.getSmbSession( auth );
-               tree = ssn.getSmbTree( share, null );
-
-               try {
-                       tree.treeConnect( null, null );
-               } catch( SmbAuthException sae ) {
-                       NtlmPasswordAuthentication a;
-
-                       if( share == null ) { // IPC$ - try "anonymous" credentials
-                               trans = SmbTransport.getSmbTransport( addr, url.getPort() );
-                               ssn = trans.getSmbSession( NtlmPasswordAuthentication.NULL );
-                               tree = ssn.getSmbTree( null, null );
-                               tree.treeConnect( null, null );
-                       } else if(( a = NtlmAuthenticator.requestNtlmPasswordAuthentication( url.toString(), sae )) != null ) {
-                               auth = a;
-                               trans = SmbTransport.getSmbTransport( addr, url.getPort() );
-                               ssn = trans.getSmbSession( auth );
-                               tree = ssn.getSmbTree( share, null );
-                               tree.treeConnect( null, null );
-                       } else {
-                               throw sae;
-                       }
-               }
-       }
-       boolean isConnected() {
-               return (connected = tree != null && tree.treeConnected);
-       }
-       int open0( int flags, int attrs, int options ) throws SmbException {
-               int f;
-
-               connect0();
-
-               Log.println( Log.WARNINGS, "smb open warning: ", unc );
-
-               /*
-                * Open AndX Request / Response
-                */
-               if( tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS )) {
-                       SmbComNTCreateAndXResponse response = new SmbComNTCreateAndXResponse();
-                       send( new SmbComNTCreateAndX( unc, flags, shareAccess, attrs, options, null ), response );
-                       f = response.fid;
-                       attributes = response.extFileAttributes & 0x3F;
-                       attrExpiration = System.currentTimeMillis() + attrExpirationPeriod;
-                       isExists = true;
-               } else {
-                       SmbComOpenAndXResponse response = new SmbComOpenAndXResponse();
-                       send( new SmbComOpenAndX( unc, flags, null ), response );
-                       f = response.fid;
-               }
-
-               return f;
-       }
-       void open( int flags, int attrs, int options ) throws SmbException {
-               if( isOpen() ) {
-                       return;
-               }
-               fid = open0( flags, attrs, options );
-               opened = true;
-       }
-       boolean isOpen() {
-               return opened && isConnected();
-       }
-       void close( int f, long lastWriteTime ) throws SmbException {
-
-               Log.println( Log.WARNINGS, "smb close warning", " fid=" + f );
-
-               /*
-                * Close Request / Response
-                */
-
-               send( new SmbComClose( f, lastWriteTime ), blank_resp );
-       }
-       void close( long lastWriteTime ) throws SmbException {
-               if( isOpen() == false ) {
-                       return;
-               }
-               close( fid, lastWriteTime );
-               opened = false;
-       }
-       void close() throws SmbException {
-               close( 0L );
-       }
+    public SmbFile( URL url, NtlmPasswordAuthentication auth ) {
+        super( url );
+        this.auth = auth == null ? new NtlmPasswordAuthentication( url.getUserInfo() ) : auth;
+
+        getUncPath0();
+    }
+    SmbFile( SmbFile context, String name, int type,
+                int attributes, long createTime, long lastModified, long size )
+                throws MalformedURLException, UnknownHostException {
+        this( context.isWorkgroup0() ?
+            new URL( null, "smb://" + name + "/", Handler.SMB_HANDLER ) :
+            new URL( context.url, name + (( attributes & ATTR_DIRECTORY ) > 0 ? "/" : "" )));
+
+        if( context.share != null ) {
+            this.tree = context.tree;
+        }
+        int last = name.length() - 1;
+        if( name.charAt( last ) == '/' ) {
+            name = name.substring( 0, last );
+        }
+        if( context.share == null ) {
+            this.unc = "\\";
+        } else if( context.unc.equals( "\\" )) {
+            this.unc = '\\' + name;
+        } else {
+            this.unc = context.unc + '\\' + name;
+        }
+        this.type = type == TYPE_WORKGROUP ? 0 : type;
+        this.attributes = attributes;
+        this.createTime = createTime;
+        this.lastModified = lastModified;
+        this.size = size;
+        isExists = true;
+
+        attrExpiration = sizeExpiration =
+                System.currentTimeMillis() + attrExpirationPeriod;
+    }
+
+    private SmbComBlankResponse blank_resp() {
+        if( blank_resp == null ) {
+            blank_resp = new SmbComBlankResponse();
+        }
+        return blank_resp;
+    }
+    void sendTransaction( SmbComTransaction request,
+                    SmbComTransactionResponse response ) throws SmbException {
+        for( ;; ) {
+            connect0();
+            if( tree.inDfs ) {
+                DfsReferral dr = tree.session.transport.lookupReferral( unc );
+                if( dr != null ) {
+                    UniAddress addr;
+                    SmbTransport trans;
+
+                    try {
+                        addr = UniAddress.getByName( dr.server );
+                    } catch( UnknownHostException uhe ) {
+                        throw new SmbException( dr.server, uhe );
+                    }
+
+                    trans = SmbTransport.getSmbTransport( addr, 0 );
+                    tree = trans.getSmbSession( auth ).getSmbTree( dr.share, null );
+                    unc = dr.nodepath + unc.substring( dr.path.length() );
+                    if( request.path.charAt( request.path.length() - 1 ) == '\\' ) {
+                        request.path = unc + '\\';
+                    } else {
+                        request.path = unc;
+                    }
+                    dfsReferral = dr; /* for getDfsPath */
+                }
+            }
+            if( tree.inDfs ) {
+                request.flags2 |= ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS;
+            } else {
+                request.flags2 &= ~ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS;
+            }
+            try {
+                tree.sendTransaction( request, response );
+                break;
+            } catch( DfsReferral dr ) {
+                if( dr.resolveHashes ) {
+                    throw dr;
+                }
+                request.reset();
+            }
+        }
+    }
+    void send( ServerMessageBlock request,
+                    ServerMessageBlock response ) throws SmbException {
+        for( ;; ) {
+            connect0();
+            if( tree.inDfs ) {
+                DfsReferral dr = tree.session.transport.lookupReferral( unc );
+                if( dr != null ) {
+                    UniAddress addr;
+                    SmbTransport trans;
+
+                    try {
+                        addr = UniAddress.getByName( dr.server );
+                    } catch( UnknownHostException uhe ) {
+                        throw new SmbException( dr.server, uhe );
+                    }
+
+                    trans = SmbTransport.getSmbTransport( addr, 0 );
+                    tree = trans.getSmbSession( auth ).getSmbTree( dr.share, null );
+                    unc = request.path = dr.nodepath + unc.substring( dr.path.length() );
+                    dfsReferral = dr; /* for getDfsPath */
+                }
+                request.flags2 |= ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS;
+            } else {
+                request.flags2 &= ~ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS;
+            }
+            try {
+                tree.send( request, response );
+                break;
+            } catch( DfsReferral dr ) {
+                if( dr.resolveHashes ) {
+                    throw dr;
+                }
+            }
+        }
+    }
+
+    UniAddress getAddress() throws UnknownHostException {
+        String host = url.getHost();
+        String path = url.getPath();
+
+        if( host.length() == 0 ) {
+            return UniAddress.getByName( NbtAddress.getByName(
+                    NbtAddress.MASTER_BROWSER_NAME, 0x01, null).getHostAddress() );
+        } else if( path.length() == 0 || path.equals( "/" )) {
+            return UniAddress.getByName( host, true );
+        } else {
+            return UniAddress.getByName( host );
+        }
+    }
+    void connect0() throws SmbException {
+        try {
+            connect();
+        } catch( UnknownHostException uhe ) {
+            throw new SmbException( "Failed to connect to server", uhe );
+        } catch( SmbException se ) {
+            throw se;
+        } catch( IOException ioe ) {
+            throw new SmbException( "Failed to connect to server", ioe );
+        }
+    }
+    public void connect() throws IOException {
+        SmbTransport trans;
+        SmbSession ssn;
+        UniAddress addr;
+
+        if( isConnected() ) {
+            return;
+        }
+
+        getUncPath0();
+        addr = getAddress();
+
+        trans = SmbTransport.getSmbTransport( addr, url.getPort() );
+        ssn = trans.getSmbSession( auth );
+        tree = ssn.getSmbTree( share, null );
+
+        try {
+            tree.treeConnect( null, null );
+        } catch( SmbAuthException sae ) {
+            NtlmPasswordAuthentication a;
+
+            if( share == null ) { // IPC$ - try "anonymous" credentials
+                ssn = trans.getSmbSession( NtlmPasswordAuthentication.NULL );
+                tree = ssn.getSmbTree( null, null );
+                tree.treeConnect( null, null );
+            } else if(( a = NtlmAuthenticator.requestNtlmPasswordAuthentication( url.toString(), sae )) != null ) {
+                auth = a;
+                ssn = trans.getSmbSession( auth );
+                tree = ssn.getSmbTree( share, null );
+                tree.treeConnect( null, null );
+            } else {
+                throw sae;
+            }
+        }
+    }
+    boolean isConnected() {
+        return (connected = tree != null && tree.treeConnected);
+    }
+    int open0( int flags, int attrs, int options ) throws SmbException {
+        int f;
+
+        connect0();
+
+        if( log.level > 2 )
+            log.println( "open0: " + unc );
+
+        /*
+         * Open AndX Request / Response
+         */
+        if( tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS )) {
+            SmbComNTCreateAndXResponse response = new SmbComNTCreateAndXResponse();
+            send( new SmbComNTCreateAndX( unc, flags, shareAccess, attrs, options, null ), response );
+            f = response.fid;
+            attributes = response.extFileAttributes & ATTR_GET_MASK;
+            attrExpiration = System.currentTimeMillis() + attrExpirationPeriod;
+            isExists = true;
+        } else {
+            SmbComOpenAndXResponse response = new SmbComOpenAndXResponse();
+            send( new SmbComOpenAndX( unc, flags, null ), response );
+            f = response.fid;
+        }
+
+        return f;
+    }
+    void open( int flags, int attrs, int options ) throws SmbException {
+        if( isOpen() ) {
+            return;
+        }
+        fid = open0( flags, attrs, options );
+        opened = true;
+    }
+    boolean isOpen() {
+        return opened && isConnected();
+    }
+    void close( int f, long lastWriteTime ) throws SmbException {
+
+        if( log.level > 2 )
+            log.println( "close: " + f );
+
+        /*
+         * Close Request / Response
+         */
+
+        send( new SmbComClose( f, lastWriteTime ), blank_resp() );
+    }
+    void close( long lastWriteTime ) throws SmbException {
+        if( isOpen() == false ) {
+            return;
+        }
+        close( fid, lastWriteTime );
+        opened = false;
+    }
+    void close() throws SmbException {
+        close( 0L );
+    }
 
 /**
  * Returns the last component of the target URL. This will
@@ -766,22 +780,22 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  *          itself.
  */
 
-       public String getName() {
-               getUncPath0();
-               if( canon.length() > 1 ) {
-                       int i = canon.length() - 2;
-                       while( canon.charAt( i ) != '/' ) {
-                               i--;
-                       }
-                       return canon.substring( i + 1 );
-               } else if( share != null ) {
-                       return share + '/';
-               } else if( url.getHost().length() > 0 ) {
-                       return url.getHost() + '/';
-               } else {
-                       return "smb://";
-               }
-       }
+    public String getName() {
+        getUncPath0();
+        if( canon.length() > 1 ) {
+            int i = canon.length() - 2;
+            while( canon.charAt( i ) != '/' ) {
+                i--;
+            }
+            return canon.substring( i + 1 );
+        } else if( share != null ) {
+            return share + '/';
+        } else if( url.getHost().length() > 0 ) {
+            return url.getHost() + '/';
+        } else {
+            return "smb://";
+        }
+    }
 
 /**
  * Everything but the last component of the URL representing this SMB
@@ -793,33 +807,33 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  *           hierarchy which incedentally is also <code>smb://</code>.
  */
 
-       public String getParent() {
-               String str = url.getAuthority();
+    public String getParent() {
+        String str = url.getAuthority();
 
-               if( str.length() > 0 ) {
-                       StringBuffer sb = new StringBuffer( "smb://" );
+        if( str.length() > 0 ) {
+            StringBuffer sb = new StringBuffer( "smb://" );
 
-                       sb.append( str );
+            sb.append( str );
 
-                       getUncPath0();
-                       if( canon.length() > 1 ) {
-                               sb.append( canon );
-                       } else {
-                               sb.append( '/' );
-                       }
+            getUncPath0();
+            if( canon.length() > 1 ) {
+                sb.append( canon );
+            } else {
+                sb.append( '/' );
+            }
 
-                       str = sb.toString();
+            str = sb.toString();
 
-                       int i = str.length() - 2;
-                       while( str.charAt( i ) != '/' ) {
-                               i--;
-                       }
+            int i = str.length() - 2;
+            while( str.charAt( i ) != '/' ) {
+                i--;
+            }
 
-                       return str.substring( 0, i + 1 );
-               }
+            return str.substring( 0, i + 1 );
+        }
 
-               return "smb://";
-       }
+        return "smb://";
+    }
 
 /**
  * Returns the full uncanonicalized URL of this SMB resource. An
@@ -829,90 +843,90 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @return  The uncanonicalized full URL of this SMB resource.
  */
 
-       public String getPath() {
-               return url.toString();
-       }
-
-       String getUncPath0() {
-               if( unc == null ) {
-                       char[] in = url.getPath().toCharArray();
-                       char[] out = new char[in.length];
-                       int i, o, state, s;
-
-                       state = 0;
-                       o = 0;
-                       for( i = 0; i < in.length; i++ ) {
-                               switch( state ) {
-                                       case 0:
-                                               if( in[i] != '/' ) {
-                                                       return null;
-                                               }
-                                               out[o++] = in[i];
-                                               state = 1;
-                                               break;
-                                       case 1:
-                                               if( in[i] == '/' ) {
-                                                       break;
-                                               } else if( in[i] == '.' &&
-                                                                       (( i + 1 ) >= in.length || in[i + 1] == '/' )) {
-                                                       i++;
-                                                       break;
-                                               } else if(( i + 1 ) < in.length &&
-                                                                       in[i] == '.' &&
-                                                                       in[i + 1] == '.' &&
-                                                                       (( i + 2 ) >= in.length || in[i + 2] == '/' )) {
-                                                       i += 2;
-                                                       if( o == 1 ) break;
-                                                       do {
-                                                               o--;
-                                                       } while( o > 1 && out[o - 1] != '/' );
-                                                       break;
-                                               }
-                                               state = 2;
-                                       case 2:
-                                               if( in[i] == '/' ) {
-                                                       state = 1;
-                                               }
-                                               out[o++] = in[i];
-                                               break;
-                               }
-                       }
-
-                       canon = new String( out, 0, o );
-
-                       if( o > 1 ) {
-                               o--;
-                               i = canon.indexOf( '/', 1 );
-                               if( i < 0 ) {
-                                       share = canon.substring( 1 );
-                                       unc = "\\";
-                               } else if( i == o ) {
-                                       share = canon.substring( 1, i );
-                                       unc = "\\";
-                               } else {
-                                       share = canon.substring( 1, i );
-                                       unc = canon.substring( i, out[o] == '/' ? o : o + 1 );
-                                       unc = unc.replace( '/', '\\' );
-                               }
-                       } else {
-                               share = null;
-                               unc = "\\";
-                       }
-               }
-               return unc;
-       }
+    public String getPath() {
+        return url.toString();
+    }
+
+    String getUncPath0() {
+        if( unc == null ) {
+            char[] in = url.getPath().toCharArray();
+            char[] out = new char[in.length];
+            int i, o, state, s;
+
+            state = 0;
+            o = 0;
+            for( i = 0; i < in.length; i++ ) {
+                switch( state ) {
+                    case 0:
+                        if( in[i] != '/' ) {
+                            return null;
+                        }
+                        out[o++] = in[i];
+                        state = 1;
+                        break;
+                    case 1:
+                        if( in[i] == '/' ) {
+                            break;
+                        } else if( in[i] == '.' &&
+                                    (( i + 1 ) >= in.length || in[i + 1] == '/' )) {
+                            i++;
+                            break;
+                        } else if(( i + 1 ) < in.length &&
+                                    in[i] == '.' &&
+                                    in[i + 1] == '.' &&
+                                    (( i + 2 ) >= in.length || in[i + 2] == '/' )) {
+                            i += 2;
+                            if( o == 1 ) break;
+                            do {
+                                o--;
+                            } while( o > 1 && out[o - 1] != '/' );
+                            break;
+                        }
+                        state = 2;
+                    case 2:
+                        if( in[i] == '/' ) {
+                            state = 1;
+                        }
+                        out[o++] = in[i];
+                        break;
+                }
+            }
+
+            canon = new String( out, 0, o );
+
+            if( o > 1 ) {
+                o--;
+                i = canon.indexOf( '/', 1 );
+                if( i < 0 ) {
+                    share = canon.substring( 1 );
+                    unc = "\\";
+                } else if( i == o ) {
+                    share = canon.substring( 1, i );
+                    unc = "\\";
+                } else {
+                    share = canon.substring( 1, i );
+                    unc = canon.substring( i, out[o] == '/' ? o : o + 1 );
+                    unc = unc.replace( '/', '\\' );
+                }
+            } else {
+                share = null;
+                unc = "\\";
+            }
+        }
+        return unc;
+    }
 /**
  * Retuns the Windows UNC style path with backslashs intead of forward slashes.
  *
  * @return  The UNC path.
  */
-       public String getUncPath() {
-               getUncPath0();
-               if( share == null ) {
-                       return "\\\\" + url.getHost();
-               }
-               return "\\\\" + url.getHost() + canon.replace( '/', '\\' );
-       }
+    public String getUncPath() {
+        getUncPath0();
+        if( share == null ) {
+            return "\\\\" + url.getHost();
+        }
+        return "\\\\" + url.getHost() + canon.replace( '/', '\\' );
+    }
 /**
  * Returns the full URL of this SMB resource with '.' and '..' components
  * factored out. An <code>SmbFile</code> constructed with the result of
@@ -922,14 +936,14 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @return  The canonicalized URL of this SMB resource.
  */
 
-       public String getCanonicalPath() {
-               String str = url.getAuthority();
-               getUncPath0();
-               if( str.length() > 0 ) {
-                       return "smb://" + url.getAuthority() + canon;
-               }
-               return "smb://";
-       }
+    public String getCanonicalPath() {
+        String str = url.getAuthority();
+        getUncPath0();
+        if( str.length() > 0 ) {
+            return "smb://" + url.getAuthority() + canon;
+        }
+        return "smb://";
+    }
 
 /**
  * Retrieves the share associated with this SMB resource. In
@@ -940,9 +954,9 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @return  The share component or <code>null</code> if there is no share
  */
 
-       public String getShare() {
-               return share;
-       }
+    public String getShare() {
+        return share;
+    }
 
 /** 
  * Retrieve the hostname of the server for this SMB resource. If this
@@ -954,127 +968,123 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  *          <code>SmbFile</code> refers to the root <code>smb://</code> resource.
  */ 
 
-       public String getServer() {
-               String str = url.getHost();
-               if( str.length() == 0 ) {
-                       return null;
-               }
-               return str;
-       }
+    public String getServer() {
+        String str = url.getHost();
+        if( str.length() == 0 ) {
+            return null;
+        }
+        return str;
+    }
 
 /**
  * Returns type of of object this <tt>SmbFile</tt> represents.
  * @return <tt>TYPE_FILESYSTEM, TYPE_WORKGROUP, TYPE_SERVER, TYPE_SHARE,
  * TYPE_PRINTER, TYPE_NAMED_PIPE</tt>, or <tt>TYPE_COMM</tt>.
  */
-       public int getType() throws SmbException {
-               if( type == 0 ) {
-                       if( getUncPath0().length() > 1 ) {
-                               type = TYPE_FILESYSTEM;
-                       } else if( share != null ) {
-                               // treeConnect good enough to test service type
-                               connect0();
-                               if( share.equals( "IPC$" )) {
-                                       type = TYPE_NAMED_PIPE;
-                               } else if( tree.service.equals( "LPT1:" )) {
-                                       type = TYPE_PRINTER;
-                               } else if( tree.service.equals( "COMM" )) {
-                                       type = TYPE_COMM;
-                               } else {
-                                       type = TYPE_SHARE;
-                               }
-                       } else if( url.getAuthority().length() == 0 ) {
-                               type = TYPE_WORKGROUP;
-                       } else {
-                               UniAddress addr;
-                               try {
-                                       addr = getAddress();
-                               } catch( UnknownHostException uhe ) {
-                                       throw new SmbException( SmbException.ERRCLI,
-                                                                       SmbException.ERRunknownHost,
-                                                                       "Unknown host: " + uhe.getMessage() );
-                               }
-                               if( addr.getAddress() instanceof NbtAddress ) {
-                                       int code = ((NbtAddress)addr.getAddress()).getNameType();
-                                       if( code == 0x1d || code == 0x1b ) {
-                                               type = TYPE_WORKGROUP;
-                                               return type;
-                                       }
-                               }
-                               type = TYPE_SERVER;
-                       }
-               }
-               return type;
-       }
-       boolean isWorkgroup0() throws UnknownHostException {
-               if( type == TYPE_WORKGROUP || url.getHost().length() == 0 ) {
-                       type = TYPE_WORKGROUP;
-                       return true;
-               } else {
-                       getUncPath0();
-                       if( share == null ) {
-                               UniAddress addr = getAddress();
-                               if( addr.getAddress() instanceof NbtAddress ) {
-                                       int code = ((NbtAddress)addr.getAddress()).getNameType();
-                                       if( code == 0x1d || code == 0x1b ) {
-                                               type = TYPE_WORKGROUP;
-                                               return true;
-                                       }
-                               }
-                               type = TYPE_SERVER;
-                       }
-               }
-               return false;
-       }
-
-       Info queryPath( String path, int infoLevel ) throws SmbException {
-               SmbTransport trans;
-
-               connect0();
-
-               Log.println( Log.WARNINGS, "smb query path warning",
-                                                       " querying path=" + path );
-
-               /* normally we'd check the negotiatedCapabilities for CAP_NT_SMBS
-                * however I can't seem to get a good last modified time from
-                * SMB_COM_QUERY_INFORMATION so if NT_SMBs are requested
-                * by the server than in this case that's what it will get
-                * regardless of what jcifs.smb.client.useNTSmbs is set
-                * to(overrides negotiatedCapabilities).
-                */
-
-               /* We really should do the referral before this in case
-                * the redirected target has different capabilities. But
-                * the way we have been doing that is to call exists() which
-                * calls this method so another technique will be necessary
-                * to support DFS referral _to_ Win95/98/ME.
-                */
-
-               if( tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS )) {
-
-                       /*
-                        * Trans2 Query Path Information Request / Response
-                        */
-
-                       Trans2QueryPathInformationResponse response =
-                                       new Trans2QueryPathInformationResponse( infoLevel );
-                       sendTransaction( new Trans2QueryPathInformation( path,
-                                       infoLevel ), response );
-
-                       return response.info;
-               } else {
-
-                       /*
-                        * Query Information Request / Response
-                        */
-
-                       SmbComQueryInformationResponse response =
-                                       new SmbComQueryInformationResponse(
-                                       tree.session.transport.server.serverTimeZone * 1000 * 60L );
-                       send( new SmbComQueryInformation( path ), response );
-                       return response;
-               }
-       }
+    public int getType() throws SmbException {
+        if( type == 0 ) {
+            if( getUncPath0().length() > 1 ) {
+                type = TYPE_FILESYSTEM;
+            } else if( share != null ) {
+                // treeConnect good enough to test service type
+                connect0();
+                if( share.equals( "IPC$" )) {
+                    type = TYPE_NAMED_PIPE;
+                } else if( tree.service.equals( "LPT1:" )) {
+                    type = TYPE_PRINTER;
+                } else if( tree.service.equals( "COMM" )) {
+                    type = TYPE_COMM;
+                } else {
+                    type = TYPE_SHARE;
+                }
+            } else if( url.getAuthority().length() == 0 ) {
+                type = TYPE_WORKGROUP;
+            } else {
+                UniAddress addr;
+                try {
+                    addr = getAddress();
+                } catch( UnknownHostException uhe ) {
+                    throw new SmbException( url.toString(), uhe );
+                }
+                if( addr.getAddress() instanceof NbtAddress ) {
+                    int code = ((NbtAddress)addr.getAddress()).getNameType();
+                    if( code == 0x1d || code == 0x1b ) {
+                        type = TYPE_WORKGROUP;
+                        return type;
+                    }
+                }
+                type = TYPE_SERVER;
+            }
+        }
+        return type;
+    }
+    boolean isWorkgroup0() throws UnknownHostException {
+        if( type == TYPE_WORKGROUP || url.getHost().length() == 0 ) {
+            type = TYPE_WORKGROUP;
+            return true;
+        } else {
+            getUncPath0();
+            if( share == null ) {
+                UniAddress addr = getAddress();
+                if( addr.getAddress() instanceof NbtAddress ) {
+                    int code = ((NbtAddress)addr.getAddress()).getNameType();
+                    if( code == 0x1d || code == 0x1b ) {
+                        type = TYPE_WORKGROUP;
+                        return true;
+                    }
+                }
+                type = TYPE_SERVER;
+            }
+        }
+        return false;
+    }
+
+    Info queryPath( String path, int infoLevel ) throws SmbException {
+        connect0();
+
+        if( log.level > 2 )
+            log.println( "queryPath: " + path );
+
+        /* normally we'd check the negotiatedCapabilities for CAP_NT_SMBS
+         * however I can't seem to get a good last modified time from
+         * SMB_COM_QUERY_INFORMATION so if NT_SMBs are requested
+         * by the server than in this case that's what it will get
+         * regardless of what jcifs.smb.client.useNTSmbs is set
+         * to(overrides negotiatedCapabilities).
+         */
+
+        /* We really should do the referral before this in case
+         * the redirected target has different capabilities. But
+         * the way we have been doing that is to call exists() which
+         * calls this method so another technique will be necessary
+         * to support DFS referral _to_ Win95/98/ME.
+         */
+
+        if( tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS )) {
+
+            /*
+             * Trans2 Query Path Information Request / Response
+             */
+
+            Trans2QueryPathInformationResponse response =
+                    new Trans2QueryPathInformationResponse( infoLevel );
+            sendTransaction( new Trans2QueryPathInformation( path,
+                    infoLevel ), response );
+
+            return response.info;
+        } else {
+
+            /*
+             * Query Information Request / Response
+             */
+
+            SmbComQueryInformationResponse response =
+                    new SmbComQueryInformationResponse(
+                    tree.session.transport.server.serverTimeZone * 1000 * 60L );
+            send( new SmbComQueryInformation( path ), response );
+            return response;
+        }
+    }
 
 /**
  * Tests to see if the SMB resource exists. If the resource refers
@@ -1090,56 +1100,58 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  *         <code>false</code> otherwise
  */
 
-       public boolean exists() throws SmbException {
-
-               if( attrExpiration > System.currentTimeMillis() ) {
-                       return isExists;
-               }
-
-               attributes = ATTR_READONLY | ATTR_DIRECTORY;
-               createTime = 0L;
-               lastModified = 0L;
-               isExists = false;
-
-               try {
-                       if( url.getHost().length() == 0 ) {
-                       } else if( share == null ) {
-                               if( getType() == TYPE_WORKGROUP ) {
-                                       UniAddress.getByName( url.getHost(), true );
-                               } else {
-                                       UniAddress.getByName( url.getHost() ).getHostName();
-                               }
-                       } else if( getUncPath0().length() == 1 ||
-                                                                               share.equalsIgnoreCase( "IPC$" )) {
-                               connect0(); // treeConnect is good enough
-                       } else {
-                               Info info = queryPath( getUncPath0(),
-                                       Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO );
-                               attributes = info.getAttributes();
-                               createTime = info.getCreateTime();
-                               lastModified = info.getLastWriteTime();
-                       }
-
-                       /* If any of the above fail, isExists will not be set true
-                        */
-
-                       isExists = true;
-
-               } catch( UnknownHostException uhe ) {
-               } catch( SmbException se ) {
-                       if( se.errorClass == SmbException.ERRDOS &&
-                                                       ( se.errorCode == SmbException.ERRbadfile ||
-                                                       se.errorCode == SmbException.ERRbadnetname ||
-                                                       se.errorCode == SmbException.ERRbadpath )) {
-                       } else {
-                               throw se;
-                       }
-               }
-
-               attrExpiration = System.currentTimeMillis() + attrExpirationPeriod;
-
-               return isExists;
-       }
+    public boolean exists() throws SmbException {
+
+        if( attrExpiration > System.currentTimeMillis() ) {
+            return isExists;
+        }
+
+        attributes = ATTR_READONLY | ATTR_DIRECTORY;
+        createTime = 0L;
+        lastModified = 0L;
+        isExists = false;
+
+        try {
+            if( url.getHost().length() == 0 ) {
+            } else if( share == null ) {
+                if( getType() == TYPE_WORKGROUP ) {
+                    UniAddress.getByName( url.getHost(), true );
+                } else {
+                    UniAddress.getByName( url.getHost() ).getHostName();
+                }
+            } else if( getUncPath0().length() == 1 ||
+                                        share.equalsIgnoreCase( "IPC$" )) {
+                connect0(); // treeConnect is good enough
+            } else {
+                Info info = queryPath( getUncPath0(),
+                    Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO );
+                attributes = info.getAttributes();
+                createTime = info.getCreateTime();
+                lastModified = info.getLastWriteTime();
+            }
+
+            /* If any of the above fail, isExists will not be set true
+             */
+
+            isExists = true;
+
+        } catch( UnknownHostException uhe ) {
+        } catch( SmbException se ) {
+            switch (se.getNtStatus()) {
+                case NtStatus.NT_STATUS_NO_SUCH_FILE:
+                case NtStatus.NT_STATUS_OBJECT_NAME_INVALID:
+                case NtStatus.NT_STATUS_OBJECT_NAME_NOT_FOUND:
+                case NtStatus.NT_STATUS_OBJECT_PATH_NOT_FOUND:
+                    break;
+                default:
+                    throw se;
+            }
+        }
+
+        attrExpiration = System.currentTimeMillis() + attrExpirationPeriod;
+
+        return isExists;
+    }
 
 /**
  * Tests to see if the file this <code>SmbFile</code> represents can be
@@ -1149,12 +1161,12 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @return <code>true</code> if the file is read-only
  */
 
-       public boolean canRead() throws SmbException {
-               if( getType() == TYPE_NAMED_PIPE ) { // try opening the pipe for reading?
-                       return true;
-               }
-               return exists(); // try opening and catch sharing violation?
-       }
+    public boolean canRead() throws SmbException {
+        if( getType() == TYPE_NAMED_PIPE ) { // try opening the pipe for reading?
+            return true;
+        }
+        return exists(); // try opening and catch sharing violation?
+    }
 
 /**
  * Tests to see if the file this <code>SmbFile</code> represents
@@ -1167,12 +1179,12 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  *          read-only
  */
 
-       public boolean canWrite() throws SmbException {
-               if( getType() == TYPE_NAMED_PIPE ) { // try opening the pipe for writing?
-                       return true;
-               }
-               return exists() && ( attributes & ATTR_READONLY ) == 0;
-       }
+    public boolean canWrite() throws SmbException {
+        if( getType() == TYPE_NAMED_PIPE ) { // try opening the pipe for writing?
+            return true;
+        }
+        return exists() && ( attributes & ATTR_READONLY ) == 0;
+    }
 
 /**
  * Tests to see if the file this <code>SmbFile</code> represents is a directory.
@@ -1180,13 +1192,13 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @return <code>true</code> if this <code>SmbFile</code> is a directory
  */
 
-       public boolean isDirectory() throws SmbException {
-               if( getUncPath0().length() == 1 ) {
-                       return true;
-               }
-               if (!exists()) return false;
-               return ( attributes & ATTR_DIRECTORY ) == ATTR_DIRECTORY;
-       }
+    public boolean isDirectory() throws SmbException {
+        if( getUncPath0().length() == 1 ) {
+            return true;
+        }
+        if (!exists()) return false;
+        return ( attributes & ATTR_DIRECTORY ) == ATTR_DIRECTORY;
+    }
 
 /**
  * Tests to see if the file this <code>SmbFile</code> represents is not a directory.
@@ -1194,13 +1206,13 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @return <code>true</code> if this <code>SmbFile</code> is not a directory
  */
 
-       public boolean isFile() throws SmbException {
-               if( getUncPath0().length() == 1 ) {
-                       return false;
-               }
-               exists();
-               return ( attributes & ATTR_DIRECTORY ) == 0;
-       }
+    public boolean isFile() throws SmbException {
+        if( getUncPath0().length() == 1 ) {
+            return false;
+        }
+        exists();
+        return ( attributes & ATTR_DIRECTORY ) == 0;
+    }
 
 /**
  * Tests to see if the file this SmbFile represents is marked as hidden.
@@ -1208,33 +1220,33 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @return <code>true</code> if the <code>SmbFile</code> is marked as being hidden
  */
 
-       public boolean isHidden() throws SmbException {
-               if( share == null ) {
-                       return false;
-               } else if( getUncPath0().length() == 1 ) {
-                       if( share.endsWith( "$" )) {
-                               return true;
-                       }
-                       return false;
-               }
-               exists();
-               return ( attributes & ATTR_HIDDEN ) == ATTR_HIDDEN;
-       }
+    public boolean isHidden() throws SmbException {
+        if( share == null ) {
+            return false;
+        } else if( getUncPath0().length() == 1 ) {
+            if( share.endsWith( "$" )) {
+                return true;
+            }
+            return false;
+        }
+        exists();
+        return ( attributes & ATTR_HIDDEN ) == ATTR_HIDDEN;
+    }
 
 /**
  * Retrieves the DFS path or <tt>null</tt> if the path specified does not fall within a DFS volume.
  */
 
-       public String getDfsPath() throws SmbException {
-               connect0();
-               if( tree.inDfs ) {
-                       exists();
-               }
-               if( dfsReferral == null ) {
-                       return null;
-               }
-               return "smb:/" + (new String( dfsReferral.node + unc )).replace( '\\', '/' );
-       }
+    public String getDfsPath() throws SmbException {
+        connect0();
+        if( tree.inDfs ) {
+            exists();
+        }
+        if( dfsReferral == null ) {
+            return null;
+        }
+        return "smb:/" + (new String( dfsReferral.node + unc )).replace( '\\', '/' );
+    }
 
 /**
  * Retrieve the time this <code>SmbFile</code> was created. The value returned is suitable
@@ -1249,13 +1261,13 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  *         1970 as a <code>long</code> value
  */
 
-       public long createTime() throws SmbException {
-               if( getUncPath0().length() > 1 ) {
-                       exists();
-                       return createTime;
-               }
-               return 0L;
-       }
+    public long createTime() throws SmbException {
+        if( getUncPath0().length() > 1 ) {
+            exists();
+            return createTime;
+        }
+        return 0L;
+    }
 /**
  * Retrieve the last time the file represented by this
  * <code>SmbFile</code> was modified. The value returned is suitable
@@ -1267,13 +1279,13 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  *         1970 as a <code>long</code> value
  */
 
-       public long lastModified() throws SmbException {
-               if( getUncPath0().length() > 1 ) {
-                       exists();
-                       return lastModified;
-               }
-               return 0L;
-       }
+    public long lastModified() throws SmbException {
+        if( getUncPath0().length() > 1 ) {
+            exists();
+            return lastModified;
+        }
+        return 0L;
+    }
 
 /**
  * List the contents of this SMB resource. The list returned by this
@@ -1297,12 +1309,12 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * resource URL
  */
 
-       public String[] list() throws SmbException {
-               return list( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null );
-       }
-       public String[] list( SmbFilenameFilter filter ) throws SmbException {
-               return list( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, filter, null );
-       }
+    public String[] list() throws SmbException {
+        return list( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null );
+    }
+    public String[] list( SmbFilenameFilter filter ) throws SmbException {
+        return list( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, filter, null );
+    }
 
 /**
  * List the contents of this SMB resource as an array of
@@ -1330,9 +1342,9 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * of the resource URL
  */
 
-       public SmbFile[] listFiles() throws SmbException {
-               return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null );
-       }
+    public SmbFile[] listFiles() throws SmbException {
+        return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null );
+    }
 
 /**
  * The CIFS protocol provides for DOS "wildcards" to be used as
@@ -1363,196 +1375,189 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * of the resource URL
  */
 
-       public SmbFile[] listFiles( String wildcard ) throws SmbException {
-               return listFiles( wildcard, ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null );
-       }
-       public SmbFile[] listFiles( SmbFilenameFilter filter ) throws SmbException {
-               return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, filter, null );
-       }
-       public SmbFile[] listFiles( SmbFileFilter filter ) throws SmbException {
-               return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, filter );
-       }
-       String[] list( String wildcard, int searchAttributes,
-                               SmbFilenameFilter fnf, SmbFileFilter ff ) throws SmbException {
-               ArrayList list = new ArrayList();
-
-               try {
-                       if( url.getHost().length() == 0 || share == null ) {
-                               doNetEnum( list, false, wildcard, searchAttributes, fnf, ff );
-                       } else {
-                               doFindFirstNext( list, false, wildcard, searchAttributes, fnf, ff );
-                       }
-               } catch( UnknownHostException uhe ) {
-                       throw new SmbException( SmbException.ERRCLI,
-                                       SmbException.ERRunknownHost, url.toString() );
-               } catch( MalformedURLException mue ) {
-                       throw new SmbException( SmbException.ERRCLI,
-                                       SmbException.ERRlistFiles, url.toString() );
-               }
-
-               return (String[])list.toArray(new String[list.size()]);
-       }
-       SmbFile[] listFiles( String wildcard, int searchAttributes,
-                               SmbFilenameFilter fnf, SmbFileFilter ff ) throws SmbException {
-               ArrayList list = new ArrayList();
-
-               if( ff != null && ff instanceof DosFileFilter ) {
-                       DosFileFilter dff = (DosFileFilter)ff;
-                       if( dff.wildcard != null ) {
-                               wildcard = dff.wildcard;
-                       }
-                       searchAttributes = dff.attributes;
-               }
-
-               try {
-                       if( url.getHost().length() == 0 || share == null ) {
-                               doNetEnum( list, true, wildcard, searchAttributes, fnf, ff );
-                       } else {
-                               doFindFirstNext( list, true, wildcard, searchAttributes, fnf, ff );
-                       }
-               } catch( UnknownHostException uhe ) {
-                       throw new SmbException( SmbException.ERRCLI,
-                                       SmbException.ERRunknownHost, url.toString() );
-               } catch( MalformedURLException mue ) {
-                       throw new SmbException( SmbException.ERRCLI,
-                                       SmbException.ERRlistFiles, url.toString() );
-               }
-
-               return (SmbFile[])list.toArray(new SmbFile[list.size()]);
-       }
-       void doNetEnum( ArrayList list,
-                               boolean files,
-                               String wildcard,
-                               int searchAttributes,
-                               SmbFilenameFilter fnf,
-                               SmbFileFilter ff ) throws SmbException, UnknownHostException, MalformedURLException {
-               SmbComTransaction req;
-               SmbComTransactionResponse resp;
-               int listType = url.getAuthority().length() == 0 ? 0 : getType();
-
-               if( url.toString().lastIndexOf( '/' ) != ( url.toString().length() - 1 )) {
-                       throw new SmbException( SmbException.ERRCLI,
-                                       SmbException.ERRlistFiles, url.toString() + " directory must end with '/'" );
-               }
-
-               switch( listType ) {
-                       case 0:
-                               connect0();
-                               req = new NetServerEnum2( tree.session.transport.server.oemDomainName,
-                                               NetServerEnum2.SV_TYPE_DOMAIN_ENUM );
-                               resp = new NetServerEnum2Response();
-                               break;
-                       case TYPE_WORKGROUP:
-                               req = new NetServerEnum2( url.getHost(), NetServerEnum2.SV_TYPE_ALL );
-                               resp = new NetServerEnum2Response();
-                               break;
-                       case TYPE_SERVER:
-                               req = new NetShareEnum();
-                               resp = new NetShareEnumResponse();
-                               break;
-                       default:
-                               throw new SmbException( SmbException.ERRCLI,
-                                               SmbException.ERRlistFiles, "invalid list operation: " + url.toString() );
-               }
-
-               sendTransaction( req, resp );
-
-               if( resp.status != SmbException.NERR_Success &&
-                               resp.status != SmbException.ERROR_MORE_DATA ) {
-                       throw new SmbException( SmbException.ERRRAP, resp.status, resp.toString() );
-               }
-
-               for( int i = 0; i < resp.numEntries; i++ ) {
-                       FileEntry e = resp.results[i];
-                       String name = e.getName();
-                       if( fnf != null && fnf.accept( this, name ) == false ) {
-                               continue;
-                       }
-                       if( name.length() > 0 ) {
-                               SmbFile f = new SmbFile( this, name,
-                                                       listType == 0 ? TYPE_WORKGROUP : listType,
-                                                       ATTR_READONLY | ATTR_DIRECTORY, 0L, 0L, 0L );
-                               if( ff != null && ff.accept( f ) == false ) {
-                                       continue;
-                               }
-                               if( files ) {
-                                       list.add( f );
-                               } else {
-                                       list.add( name );
-                               }
-                       }
-               }
-       }
-       void doFindFirstNext( ArrayList list,
-                               boolean files,
-                               String wildcard,
-                               int searchAttributes,
-                               SmbFilenameFilter fnf,
-                               SmbFileFilter ff ) throws SmbException, UnknownHostException, MalformedURLException {
-               SmbComTransaction req;
-               Trans2FindFirst2Response resp;
-               int sid;
-               String path = getUncPath0();
-
-               if( url.toString().lastIndexOf( '/' ) != ( url.toString().length() - 1 )) {
-                       throw new SmbException( SmbException.ERRCLI,
-                                       SmbException.ERRlistFiles, url.toString() + " directory must end with '/'" );
-               }
-
-               req = new Trans2FindFirst2( path, wildcard, searchAttributes );
-               resp = new Trans2FindFirst2Response();
-
-               Log.println( Log.WARNINGS, "smb find warning",
-                                       " find with path=" + req.path );
-
-               sendTransaction( req, resp );
-
-               sid = resp.sid;
-               req = new Trans2FindNext2( sid, resp.resumeKey, resp.lastName );
-
-               /* The only difference between first2 and next2 responses is subCommand
-                * so let's recycle the response object.
-                */
-               resp.subCommand = SmbComTransaction.TRANS2_FIND_NEXT2;
-
-               for( ;; ) {
-                       for( int i = 0; i < resp.numEntries; i++ ) {
-                               FileEntry e = resp.results[i];
-                               String name = e.getName();
-                               if( name.length() < 3 ) {
-                                       int h = name.hashCode();
-                                       if( h == HASH_DOT || h == HASH_DOT_DOT ) {
-                                               continue;
-                                       }
-                               }
-                               if( fnf != null && fnf.accept( this, name ) == false ) {
-                                       continue;
-                               }
-                               if( name.length() > 0 ) {
-                                       SmbFile f = new SmbFile( this, name, TYPE_FILESYSTEM,
-                                                       e.getAttributes(), e.createTime(), e.lastModified(), e.length() );
-                                       if( ff != null && ff.accept( f ) == false ) {
-                                               continue;
-                                       }
-                                       if( files ) {
-                                               list.add( f );
-                                       } else {
-                                               list.add( name );
-                                       }
-                               }
-                       }
-
-                       if( resp.isEndOfSearch || resp.numEntries == 0 ) {
-                               break;
-                       }
-
-                       req.reset( resp.resumeKey, resp.lastName );
-                       resp.reset();
-                       sendTransaction( req, resp );
-               }
-
-               send( new SmbComFindClose2( sid ), blank_resp );
-       }
+    public SmbFile[] listFiles( String wildcard ) throws SmbException {
+        return listFiles( wildcard, ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null );
+    }
+    public SmbFile[] listFiles( SmbFilenameFilter filter ) throws SmbException {
+        return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, filter, null );
+    }
+    public SmbFile[] listFiles( SmbFileFilter filter ) throws SmbException {
+        return listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, filter );
+    }
+    String[] list( String wildcard, int searchAttributes,
+                SmbFilenameFilter fnf, SmbFileFilter ff ) throws SmbException {
+        ArrayList list = new ArrayList();
+
+        try {
+            if( url.getHost().length() == 0 || share == null ) {
+                doNetEnum( list, false, wildcard, searchAttributes, fnf, ff );
+            } else {
+                doFindFirstNext( list, false, wildcard, searchAttributes, fnf, ff );
+            }
+        } catch( UnknownHostException uhe ) {
+            throw new SmbException( url.toString(), uhe );
+        } catch( MalformedURLException mue ) {
+            throw new SmbException( url.toString(), mue );
+        }
+
+        return (String[])list.toArray(new String[list.size()]);
+    }
+    SmbFile[] listFiles( String wildcard, int searchAttributes,
+                SmbFilenameFilter fnf, SmbFileFilter ff ) throws SmbException {
+        ArrayList list = new ArrayList();
+
+        if( ff != null && ff instanceof DosFileFilter ) {
+            DosFileFilter dff = (DosFileFilter)ff;
+            if( dff.wildcard != null ) {
+                wildcard = dff.wildcard;
+            }
+            searchAttributes = dff.attributes;
+        }
+
+        try {
+            if( url.getHost().length() == 0 || share == null ) {
+                doNetEnum( list, true, wildcard, searchAttributes, fnf, ff );
+            } else {
+                doFindFirstNext( list, true, wildcard, searchAttributes, fnf, ff );
+            }
+        } catch( UnknownHostException uhe ) {
+            throw new SmbException( url.toString(), uhe );
+        } catch( MalformedURLException mue ) {
+            throw new SmbException( url.toString(), mue );
+        }
+
+        return (SmbFile[])list.toArray(new SmbFile[list.size()]);
+    }
+    void doNetEnum( ArrayList list,
+                boolean files,
+                String wildcard,
+                int searchAttributes,
+                SmbFilenameFilter fnf,
+                SmbFileFilter ff ) throws SmbException, UnknownHostException, MalformedURLException {
+        SmbComTransaction req;
+        SmbComTransactionResponse resp;
+        int listType = url.getAuthority().length() == 0 ? 0 : getType();
+
+        if( url.toString().lastIndexOf( '/' ) != ( url.toString().length() - 1 )) {
+            throw new SmbException( url.toString() + " directory must end with '/'" );
+        }
+
+        switch( listType ) {
+            case 0:
+                connect0();
+                req = new NetServerEnum2( tree.session.transport.server.oemDomainName,
+                        NetServerEnum2.SV_TYPE_DOMAIN_ENUM );
+                resp = new NetServerEnum2Response();
+                break;
+            case TYPE_WORKGROUP:
+                req = new NetServerEnum2( url.getHost(), NetServerEnum2.SV_TYPE_ALL );
+                resp = new NetServerEnum2Response();
+                break;
+            case TYPE_SERVER:
+                req = new NetShareEnum();
+                resp = new NetShareEnumResponse();
+                break;
+            default:
+                throw new SmbException( "The requested list operations is invalid: " + url.toString() );
+        }
+
+        sendTransaction( req, resp );
+
+        if( resp.status != SmbException.ERROR_SUCCESS &&
+                resp.status != SmbException.ERROR_MORE_DATA ) {
+            throw new SmbException( resp.status, true );
+        }
+
+        for( int i = 0; i < resp.numEntries; i++ ) {
+            FileEntry e = resp.results[i];
+            String name = e.getName();
+            if( fnf != null && fnf.accept( this, name ) == false ) {
+                continue;
+            }
+            if( name.length() > 0 ) {
+                SmbFile f = new SmbFile( this, name,
+                            listType == 0 ? TYPE_WORKGROUP : listType,
+                            ATTR_READONLY | ATTR_DIRECTORY, 0L, 0L, 0L );
+                if( ff != null && ff.accept( f ) == false ) {
+                    continue;
+                }
+                if( files ) {
+                    list.add( f );
+                } else {
+                    list.add( name );
+                }
+            }
+        }
+    }
+    void doFindFirstNext( ArrayList list,
+                boolean files,
+                String wildcard,
+                int searchAttributes,
+                SmbFilenameFilter fnf,
+                SmbFileFilter ff ) throws SmbException, UnknownHostException, MalformedURLException {
+        SmbComTransaction req;
+        Trans2FindFirst2Response resp;
+        int sid;
+        String path = getUncPath0();
+
+        if( url.toString().lastIndexOf( '/' ) != ( url.toString().length() - 1 )) {
+            throw new SmbException( url.toString() + " directory must end with '/'" );
+        }
+
+        req = new Trans2FindFirst2( path, wildcard, searchAttributes );
+        resp = new Trans2FindFirst2Response();
+
+        if( log.level > 2 )
+            log.println( "doFindFirstNext: " + req.path );
+
+        sendTransaction( req, resp );
+
+        sid = resp.sid;
+        req = new Trans2FindNext2( sid, resp.resumeKey, resp.lastName );
+
+        /* The only difference between first2 and next2 responses is subCommand
+         * so let's recycle the response object.
+         */
+        resp.subCommand = SmbComTransaction.TRANS2_FIND_NEXT2;
+
+        for( ;; ) {
+            for( int i = 0; i < resp.numEntries; i++ ) {
+                FileEntry e = resp.results[i];
+                String name = e.getName();
+                if( name.length() < 3 ) {
+                    int h = name.hashCode();
+                    if( h == HASH_DOT || h == HASH_DOT_DOT ) {
+                        continue;
+                    }
+                }
+                if( fnf != null && fnf.accept( this, name ) == false ) {
+                    continue;
+                }
+                if( name.length() > 0 ) {
+                    SmbFile f = new SmbFile( this, name, TYPE_FILESYSTEM,
+                            e.getAttributes(), e.createTime(), e.lastModified(), e.length() );
+                    if( ff != null && ff.accept( f ) == false ) {
+                        continue;
+                    }
+                    if( files ) {
+                        list.add( f );
+                    } else {
+                        list.add( name );
+                    }
+                }
+            }
+
+            if( resp.isEndOfSearch || resp.numEntries == 0 ) {
+                break;
+            }
+
+            req.reset( resp.resumeKey, resp.lastName );
+            resp.reset();
+            sendTransaction( req, resp );
+        }
+
+        send( new SmbComFindClose2( sid ), blank_resp() );
+    }
 
 /**
  * Changes the name of the file this <code>SmbFile</code> represents to the name
@@ -1567,220 +1572,209 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  *         If the <code>dest</code> argument is <code>null</code>
  */
 
-       public void renameTo( SmbFile dest ) throws SmbException {
-               if( getUncPath0().length() == 1 || dest.getUncPath0().length() == 1 ) {
-                       throw new SmbException( SmbException.ERRDOS,
-                                       SmbException.ERRnoaccess,
-                                       "Cannot rename shares, servers, workgroups, or domains" );
-               }
-               connect0();
-               dest.connect0();
-
-               if( tree.inDfs ) { /* This ensures that each path is
-                               * resolved independantly to deal with the case where files
-                               * have the same base path but ultimately turn out to be
-                               * on different servers because of DFS. It also eliminates
-                               * manipulating the SMB path which is problematic because
-                               * there are really two that would need to be prefixed
-                               * with host and share as DFS requires.
-                               */
-                       exists();
-                       dest.exists();
-               }
-               if( tree != dest.tree ) {
-                       throw new SmbException( SmbException.ERRDOS,
-                                       SmbException.ERRnoaccess,
-                                       "Cannot rename file to a different share" );
-               }
-
-               Log.println( Log.WARNINGS, "smb rename warning",
-                               " oldFileName=" + unc +
-                               ",newFileName=" + dest.unc );
-
-               attrExpiration = sizeExpiration = 0;
-               dest.attrExpiration = 0;
-
-               /*
-                * Rename Request / Response
-                */
-
-               send( new SmbComRename( unc, dest.unc ), blank_resp );
-       }
-
-       class WriterThread extends Thread {
-               byte[] b;
-               int n, off;
-               boolean ready = true;
-               SmbFile dest;
-               SmbException e = null;
-               boolean useNTSmbs;
-               SmbComWriteAndX reqx;
-               SmbComWrite req;
-               ServerMessageBlock resp;
-
-               WriterThread() throws SmbException {
-                       super( "JCIFS-WriterThread" );
-                       useNTSmbs = tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS );
-                       if( useNTSmbs ) {
-                               reqx = new SmbComWriteAndX();
-                               resp = new SmbComWriteAndXResponse();
-                       } else {
-                               req = new SmbComWrite();
-                               resp = new SmbComWriteResponse();
-                       }
-               }
-
-               synchronized void write( byte[] b, int n, SmbFile dest, int off ) {
-                       this.b = b;
-                       this.n = n;
-                       this.dest = dest;
-                       this.off = off;
-                       ready = false;
-                       notify();
-               }
-
-               public void run() {
-                       synchronized( this ) {
-                               try {
-                                       for( ;; ) {
-                                               ready = true;
-                                               while( ready ) {
-                                                       wait();
-                                               }
-                                               if( n == -1 ) {
-                                                       return;
-                                               }
-                                               if( useNTSmbs ) {
-                                                       reqx.setParam( dest.fid, off, n, b, 0, n );
-                                                       dest.send( reqx, resp );
-                                               } else {
-                                                       req.setParam( dest.fid, off, n, b, 0, n );
-                                                       dest.send( req, resp );
-                                               }
-                                               notify();
-                                       }
-                               } catch( SmbException e ) {
-                                       this.e = e;
-                               } catch( Exception x ) {
-                                       this.e = new SmbException( SmbException.ERRCLI,
-                                                       SmbException.ERRioe, x.getMessage() );
-                               }
-                               notify();
-                       }
-               }
-       }
-       void copyTo0( SmbFile dest, byte[][] b, int bsize, WriterThread w,
-                       SmbComReadAndX req, SmbComReadAndXResponse resp ) throws SmbException {
-               int i;
-
-               if( attrExpiration < System.currentTimeMillis() ) {
-                       attributes = ATTR_READONLY | ATTR_DIRECTORY;
-                       createTime = 0L;
-                       lastModified = 0L;
-                       isExists = false;
-
-                       Info info = queryPath( getUncPath0(),
-                                       Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO );
-                       attributes = info.getAttributes();
-                       createTime = info.getCreateTime();
-                       lastModified = info.getLastWriteTime();
-
-                       /* If any of the above fails, isExists will not be set true
-                        */
-
-                       isExists = true;
-                       attrExpiration = System.currentTimeMillis() + attrExpirationPeriod;
-               }
-
-               if( isDirectory() ) {
-                       SmbFile[] files;
-                       SmbFile ndest;
-
-                       try {
-                               dest.mkdir();
-                       } catch( SmbException se ) {
-                               if( se.getErrorCode() != SmbException.ERRnoaccess &&
-                                               se.getErrorCode() != SmbException.ERRexists ) {
-                                       throw se;
-                               }
-                       }
-
-                       files = listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null );
-                       try {
-                               for( i = 0; i < files.length; i++ ) {
-                                       ndest = new SmbFile( dest,
-                                                                       files[i].getName(),
-                                                                       files[i].type,
-                                                                       files[i].attributes,
-                                                                       files[i].createTime,
-                                                                       files[i].lastModified,
-                                                                       files[i].size );
-                                       files[i].copyTo0( ndest, b, bsize, w, req, resp );
-                               }
-                       } catch( UnknownHostException uhe ) {
-                               throw new SmbException( SmbException.ERRCLI,
-                                               SmbException.ERRunknownHost, url.toString() );
-                       } catch( MalformedURLException mue ) {
-                               throw new SmbException( SmbException.ERRCLI,
-                                               SmbException.ERRlistFiles, url.toString() );
-                       }
-               } else {
-                       int off;
-                       long mtime;
-
-                       open( SmbFile.O_RDONLY, ATTR_NORMAL, 0 );
-                       try {
-                               dest.open( SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_TRUNC |
-                                               SmbComNTCreateAndX.FILE_WRITE_ATTRIBUTES << 16, attributes, 0 );
-                       } catch( SmbAuthException sae ) {
-                               if(( dest.attributes & ATTR_READONLY ) != 0 ) {
-                                                                                       /* Remove READONLY and try again
-                                                                                        */
-                                       dest.setPathInformation( dest.attributes & ~ATTR_READONLY, 0L, 0L );
-                                       dest.open( SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_TRUNC |
-                                                       SmbComNTCreateAndX.FILE_WRITE_ATTRIBUTES << 16, attributes, 0 );
-                               } else {
-                                       throw sae;
-                               }
-                       }
-
-                       i = off = 0;
-                       for( ;; ) {
-                               req.setParam( fid, off, bsize );
-                               resp.setParam( b[i], 0 );
-                               send( req, resp );
-
-                               synchronized( w ) {
-                                       while( !w.ready ) {
-                                               try {
-                                                       w.wait();
-                                               } catch( InterruptedException ie ) {
-                                                       throw new SmbException( SmbException.ERRCLI,
-                                                                       SmbException.ERRioe, ie.getMessage() );
-                                               }
-                                       }
-                                       if( w.e != null ) {
-                                               throw w.e;
-                                       }
-                                       if( resp.dataLength <= 0 ) {
-                                               break;
-                                       }
-                                       w.write( b[i], resp.dataLength, dest, off );
-                               }
-
-                               i = i == 1 ? 0 : 1;
-                               off += resp.dataLength;
-                       }
-
-                       mtime = lastModified - tree.session.transport.server.serverTimeZone * 60 * 1000;
-                                       /* It doesn't look like the createTime should be adjusted (shrug)
-                                        */
-                       dest.sendTransaction( new Trans2SetFileInformation( dest.fid, attributes, createTime, mtime ),
-                                       new Trans2SetFileInformationResponse() );
-                       dest.close( mtime );
-                       close();
-               }
-       }
+    public void renameTo( SmbFile dest ) throws SmbException {
+        if( getUncPath0().length() == 1 || dest.getUncPath0().length() == 1 ) {
+            throw new SmbException( "Invalid operation for workgroups, servers, or shares" );
+        }
+        connect0();
+        dest.connect0();
+
+        if( tree.inDfs ) { /* This ensures that each path is
+                * resolved independantly to deal with the case where files
+                * have the same base path but ultimately turn out to be
+                * on different servers because of DFS. It also eliminates
+                * manipulating the SMB path which is problematic because
+                * there are really two that would need to be prefixed
+                * with host and share as DFS requires.
+                */
+            exists();
+            dest.exists();
+        }
+        if( tree != dest.tree ) {
+            throw new SmbException( "Invalid operation for workgroups, servers, or shares" );
+        }
+
+        if( log.level > 2 )
+            log.println( "renameTo: " + unc + " -> " + dest.unc );
+
+        attrExpiration = sizeExpiration = 0;
+        dest.attrExpiration = 0;
+
+        /*
+         * Rename Request / Response
+         */
+
+        send( new SmbComRename( unc, dest.unc ), blank_resp() );
+    }
+
+    class WriterThread extends Thread {
+        byte[] b;
+        int n, off;
+        boolean ready = true;
+        SmbFile dest;
+        SmbException e = null;
+        boolean useNTSmbs;
+        SmbComWriteAndX reqx;
+        SmbComWrite req;
+        ServerMessageBlock resp;
+
+        WriterThread() throws SmbException {
+            super( "JCIFS-WriterThread" );
+            useNTSmbs = tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS );
+            if( useNTSmbs ) {
+                reqx = new SmbComWriteAndX();
+                resp = new SmbComWriteAndXResponse();
+            } else {
+                req = new SmbComWrite();
+                resp = new SmbComWriteResponse();
+            }
+        }
+
+        synchronized void write( byte[] b, int n, SmbFile dest, int off ) {
+            this.b = b;
+            this.n = n;
+            this.dest = dest;
+            this.off = off;
+            ready = false;
+            notify();
+        }
+
+        public void run() {
+            synchronized( this ) {
+                try {
+                    for( ;; ) {
+                        ready = true;
+                        while( ready ) {
+                            wait();
+                        }
+                        if( n == -1 ) {
+                            return;
+                        }
+                        if( useNTSmbs ) {
+                            reqx.setParam( dest.fid, off, n, b, 0, n );
+                            dest.send( reqx, resp );
+                        } else {
+                            req.setParam( dest.fid, off, n, b, 0, n );
+                            dest.send( req, resp );
+                        }
+                        notify();
+                    }
+                } catch( SmbException e ) {
+                    this.e = e;
+                } catch( Exception x ) {
+                    this.e = new SmbException( "WriterThread", x );
+                }
+                notify();
+            }
+        }
+    }
+    void copyTo0( SmbFile dest, byte[][] b, int bsize, WriterThread w,
+            SmbComReadAndX req, SmbComReadAndXResponse resp ) throws SmbException {
+        int i;
+
+        if( attrExpiration < System.currentTimeMillis() ) {
+            attributes = ATTR_READONLY | ATTR_DIRECTORY;
+            createTime = 0L;
+            lastModified = 0L;
+            isExists = false;
+
+            Info info = queryPath( getUncPath0(),
+                    Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO );
+            attributes = info.getAttributes();
+            createTime = info.getCreateTime();
+            lastModified = info.getLastWriteTime();
+
+            /* If any of the above fails, isExists will not be set true
+             */
+
+            isExists = true;
+            attrExpiration = System.currentTimeMillis() + attrExpirationPeriod;
+        }
+
+        if( isDirectory() ) {
+            SmbFile[] files;
+            SmbFile ndest;
+
+            try {
+                dest.mkdir();
+                dest.setPathInformation( attributes, createTime, lastModified );
+            } catch( SmbException se ) {
+                if( se.getNtStatus() != NtStatus.NT_STATUS_ACCESS_DENIED &&
+                        se.getNtStatus() != NtStatus.NT_STATUS_OBJECT_NAME_COLLISION ) {
+                    throw se;
+                }
+            }
+
+            files = listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null );
+            try {
+                for( i = 0; i < files.length; i++ ) {
+                    ndest = new SmbFile( dest,
+                                    files[i].getName(),
+                                    files[i].type,
+                                    files[i].attributes,
+                                    files[i].createTime,
+                                    files[i].lastModified,
+                                    files[i].size );
+                    files[i].copyTo0( ndest, b, bsize, w, req, resp );
+                }
+            } catch( UnknownHostException uhe ) {
+                throw new SmbException( url.toString(), uhe );
+            } catch( MalformedURLException mue ) {
+                throw new SmbException( url.toString(), mue );
+            }
+        } else {
+            int off;
+
+            open( SmbFile.O_RDONLY, ATTR_NORMAL, 0 );
+            try {
+                dest.open( SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_TRUNC |
+                        SmbComNTCreateAndX.FILE_WRITE_ATTRIBUTES << 16, attributes, 0 );
+            } catch( SmbAuthException sae ) {
+                if(( dest.attributes & ATTR_READONLY ) != 0 ) {
+                                            /* Remove READONLY and try again
+                                             */
+                    dest.setPathInformation( dest.attributes & ~ATTR_READONLY, 0L, 0L );
+                    dest.open( SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_TRUNC |
+                            SmbComNTCreateAndX.FILE_WRITE_ATTRIBUTES << 16, attributes, 0 );
+                } else {
+                    throw sae;
+                }
+            }
+
+            i = off = 0;
+            for( ;; ) {
+                req.setParam( fid, off, bsize );
+                resp.setParam( b[i], 0 );
+                send( req, resp );
+
+                synchronized( w ) {
+                    while( !w.ready ) {
+                        try {
+                            w.wait();
+                        } catch( InterruptedException ie ) {
+                            throw new SmbException( dest.url.toString(), ie );
+                        }
+                    }
+                    if( w.e != null ) {
+                        throw w.e;
+                    }
+                    if( resp.dataLength <= 0 ) {
+                        break;
+                    }
+                    w.write( b[i], resp.dataLength, dest, off );
+                }
+
+                i = i == 1 ? 0 : 1;
+                off += resp.dataLength;
+            }
+
+            dest.sendTransaction( new Trans2SetFileInformation(
+                    dest.fid, attributes, createTime, lastModified ),
+                    new Trans2SetFileInformationResponse() );
+            dest.close( 0L );
+            close();
+        }
+    }
 /**
  * This method will copy the file or directory and it's subcontents
  * represented by this <tt>SmbFile</tt> to the location specified by the
@@ -1789,54 +1783,50 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * file attibutes such as ACLs but regular attributes and create and
  * last write times will be preserved.
  */
-       public void copyTo( SmbFile dest ) throws SmbException {
-               SmbComReadAndX req;
-               SmbComReadAndXResponse resp;
-               WriterThread w;
-               int bsize;
-               byte[][] b;
-
-               /* Should be able to copy an entire share actually
-                */
-               if( share == null || dest.share == null) {
-                       throw new SmbException( SmbException.ERRDOS,
-                                                                       SmbException.ERRnoaccess,
-                                                                       "Cannot copyTo workgroups, servers, or shares" );
-               }
-
-               req = new SmbComReadAndX();
-               resp = new SmbComReadAndXResponse();
-
-               connect0();
-               dest.connect0();
-
-               if( tree.inDfs ) {
-                               /* At this point the maxBufferSize values are from the server
-                                * exporting the volumes, not the one that we will actually
-                                * end up performing IO with. If the server hosting the
-                                * actual files has a smaller maxBufSize this could be
-                                * incorrect. To handle this properly it is necessary
-                                * to redirect the tree to the target server first before
-                                * establishing buffer size. These exists() calls facilitate
-                                * that.
-                                */
-                       exists();
-                       dest.exists();
-               }
-
-               w = new WriterThread();
-               w.setDaemon( true );
-               w.start();
-
-               bsize = Math.min( Math.min( tree.session.transport.rcv_buf_size - 70,
-                                       dest.tree.session.transport.server.maxBufferSize - 70 ),
-                                       Math.min( tree.session.transport.snd_buf_size - 70,
-                                       dest.tree.session.transport.server.maxBufferSize - 70 ));
-               b = new byte[2][bsize];
-
-               copyTo0( dest, b, bsize, w, req, resp );
-               w.write( null, -1, null, 0 );
-       }
+    public void copyTo( SmbFile dest ) throws SmbException {
+        SmbComReadAndX req;
+        SmbComReadAndXResponse resp;
+        WriterThread w;
+        int bsize;
+        byte[][] b;
+
+        /* Should be able to copy an entire share actually
+         */
+        if( share == null || dest.share == null) {
+            throw new SmbException( "Invalid operation for workgroups, servers, or shares" );
+        }
+
+        req = new SmbComReadAndX();
+        resp = new SmbComReadAndXResponse();
+
+        connect0();
+        dest.connect0();
+
+        if( tree.inDfs ) {
+                /* At this point the maxBufferSize values are from the server
+                 * exporting the volumes, not the one that we will actually
+                 * end up performing IO with. If the server hosting the
+                 * actual files has a smaller maxBufSize this could be
+                 * incorrect. To handle this properly it is necessary
+                 * to redirect the tree to the target server first before
+                 * establishing buffer size. These exists() calls facilitate
+                 * that.
+                 */
+            exists();
+            dest.exists();
+        }
+
+        w = new WriterThread();
+        w.setDaemon( true );
+        w.start();
+
+        bsize = Math.min( tree.session.transport.rcv_buf_size - 70,
+                        tree.session.transport.snd_buf_size - 70 );
+        b = new byte[2][bsize];
+
+        copyTo0( dest, b, bsize, w, req, resp );
+        w.write( null, -1, null, 0 );
+    }
 
 /**
  * This method will delete the file or directory specified by this
@@ -1847,69 +1837,64 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @throws SmbException
  */
 
-       public void delete() throws SmbException {
-               if( tree == null || tree.inDfs ) {
-                       exists();      /* This is necessary to ensure we
+    public void delete() throws SmbException {
+        if( tree == null || tree.inDfs ) {
+            exists();      /* This is necessary to ensure we
                             * pass a path adjusted for DFS */
-               }
-               getUncPath0();
-               delete( unc );
-       }
-       void delete( String fileName ) throws SmbException {
-               if( getUncPath0().length() == 1 ) {
-                       throw new SmbException( SmbException.ERRDOS,
-                                                                       SmbException.ERRnoaccess );
-               }
+        }
+        getUncPath0();
+        delete( unc );
+    }
+    void delete( String fileName ) throws SmbException {
+        if( getUncPath0().length() == 1 ) {
+            throw new SmbException( "Invalid operation for workgroups, servers, or shares" );
+        }
 
-               if( System.currentTimeMillis() > attrExpiration ) {
-                       attributes = ATTR_READONLY | ATTR_DIRECTORY;
-                       createTime = 0L;
-                       lastModified = 0L;
-                       isExists = false;
+        if( System.currentTimeMillis() > attrExpiration ) {
+            attributes = ATTR_READONLY | ATTR_DIRECTORY;
+            createTime = 0L;
+            lastModified = 0L;
+            isExists = false;
 
-                       Info info = queryPath( getUncPath0(),
-                                       Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO );
-                       attributes = info.getAttributes();
-                       createTime = info.getCreateTime();
-                       lastModified = info.getLastWriteTime();
+            Info info = queryPath( getUncPath0(),
+                    Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO );
+            attributes = info.getAttributes();
+            createTime = info.getCreateTime();
+            lastModified = info.getLastWriteTime();
 
-                       attrExpiration = System.currentTimeMillis() + attrExpirationPeriod;
-                       isExists = true;
-               }
+            attrExpiration = System.currentTimeMillis() + attrExpirationPeriod;
+            isExists = true;
+        }
 
-               if(( attributes & ATTR_READONLY ) != 0 ) {
-                       setReadWrite();
-               }
+        if(( attributes & ATTR_READONLY ) != 0 ) {
+            setReadWrite();
+        }
 
-               /*
-                * Delete or Delete Directory Request / Response
-                */
+        /*
+         * Delete or Delete Directory Request / Response
+         */
 
-               if(( attributes & ATTR_DIRECTORY ) != 0 ) {
+        if( log.level > 2 )
+            log.println( "delete: " + fileName );
 
-                       /* Recursively delete directory contents
-                        */
+        if(( attributes & ATTR_DIRECTORY ) != 0 ) {
 
-                       SmbFile[] l = listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null );
+            /* Recursively delete directory contents
+             */
 
-                       for( int i = 0; i < l.length; i++ ) {
-                               l[i].delete();
-                       }
+            SmbFile[] l = listFiles( "*", ATTR_DIRECTORY | ATTR_HIDDEN | ATTR_SYSTEM, null, null );
 
-                       Log.println( Log.WARNINGS, "smb delete directory warning",
-                                                               " fileName=" + fileName );
+            for( int i = 0; i < l.length; i++ ) {
+                l[i].delete();
+            }
 
-                       send( new SmbComDeleteDirectory( fileName ), blank_resp );
-               } else {
+            send( new SmbComDeleteDirectory( fileName ), blank_resp() );
+        } else {
+            send( new SmbComDelete( fileName ), blank_resp() );
+        }
 
-                       Log.println( Log.WARNINGS, "smb delete warning",
-                                                               " fileName=" + fileName );
-
-                       send( new SmbComDelete( fileName ), blank_resp );
-               }
-
-               attrExpiration = sizeExpiration = 0;
-       }
+        attrExpiration = sizeExpiration = 0;
+    }
 
 /**
  * Returns the length of this <tt>SmbFile</tt> in bytes.
@@ -1919,29 +1904,29 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @return The length of the file in bytes or 0 if this <code>SmbFile</code> is not a file.
  */
 
-       public long length() throws SmbException {
-               if( sizeExpiration > System.currentTimeMillis() ) {
-                       return size;
-               }
-
-               if( getType() == TYPE_SHARE ) {
-                       Trans2QueryFSInformationResponse response;
-                       int level = Trans2QueryFSInformationResponse.SMB_INFO_ALLOCATION;
-
-                       response = new Trans2QueryFSInformationResponse( level );
-                       sendTransaction( new Trans2QueryFSInformation( level ), response );
-
-                       size = response.info.getCapacity();
-               } else if( getUncPath0().length() > 1 && type != TYPE_NAMED_PIPE ) {
-                       Info info = queryPath( getUncPath0(),
-                                       Trans2QueryPathInformationResponse.SMB_QUERY_FILE_STANDARD_INFO );
-                       size = info.getSize();
-               } else {
-                       size = 0L;
-               }
-               sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod;
-               return size;
-       }
+    public long length() throws SmbException {
+        if( sizeExpiration > System.currentTimeMillis() ) {
+            return size;
+        }
+
+        if( getType() == TYPE_SHARE ) {
+            Trans2QueryFSInformationResponse response;
+            int level = Trans2QueryFSInformationResponse.SMB_INFO_ALLOCATION;
+
+            response = new Trans2QueryFSInformationResponse( level );
+            sendTransaction( new Trans2QueryFSInformation( level ), response );
+
+            size = response.info.getCapacity();
+        } else if( getUncPath0().length() > 1 && type != TYPE_NAMED_PIPE ) {
+            Info info = queryPath( getUncPath0(),
+                    Trans2QueryPathInformationResponse.SMB_QUERY_FILE_STANDARD_INFO );
+            size = info.getSize();
+        } else {
+            size = 0L;
+        }
+        sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod;
+        return size;
+    }
 
 /**
  * This method returns the free disk space in bytes of the drive this share
@@ -1949,23 +1934,23 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * other than <tt>TYPE_SHARE</tt> or <tt>TYPE_FILESYSTEM</tt> will result
  * in 0L being returned.
  */
-       public long getDiskFreeSpace() throws SmbException {
-               if( getType() == TYPE_SHARE || type == TYPE_FILESYSTEM ) {
-                       Trans2QueryFSInformationResponse response;
-                       int level = Trans2QueryFSInformationResponse.SMB_INFO_ALLOCATION;
+    public long getDiskFreeSpace() throws SmbException {
+        if( getType() == TYPE_SHARE || type == TYPE_FILESYSTEM ) {
+            Trans2QueryFSInformationResponse response;
+            int level = Trans2QueryFSInformationResponse.SMB_INFO_ALLOCATION;
 
-                       response = new Trans2QueryFSInformationResponse( level );
-                       sendTransaction( new Trans2QueryFSInformation( level ), response );
+            response = new Trans2QueryFSInformationResponse( level );
+            sendTransaction( new Trans2QueryFSInformation( level ), response );
 
-                       if( type == TYPE_SHARE ) {
-                               size = response.info.getCapacity();
-                               sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod;
-                       }
+            if( type == TYPE_SHARE ) {
+                size = response.info.getCapacity();
+                sizeExpiration = System.currentTimeMillis() + attrExpirationPeriod;
+            }
 
-                       return response.info.getFree();
-               }
-               return 0L;
-       }
+            return response.info.getFree();
+        }
+        return 0L;
+    }
 
 /**
  * Creates a directory with the path specified by this
@@ -1978,23 +1963,24 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @throws SmbException
  */
 
-       public void mkdir() throws SmbException {
-               if( getUncPath0().length() == 1 ) {
-                       throw new SmbException( SmbException.ERRDOS,
-                                                                       SmbException.ERRnoaccess );
-               }
+    public void mkdir() throws SmbException {
+        String path = getUncPath0();
+
+        if( path.length() == 1 ) {
+            throw new SmbException( "Invalid operation for workgroups, servers, or shares" );
+        }
 
-               Log.println( Log.WARNINGS, "smb create directory warning",
-                                                       " directoryName=" + getUncPath0() );
+        /*
+         * Create Directory Request / Response
+         */
 
-               /*
-                * Create Directory Request / Response
-                */
+        if( log.level > 2 )
+            log.println( "mkdir: " + path );
 
-               send( new SmbComCreateDirectory( getUncPath0() ), blank_resp );
+        send( new SmbComCreateDirectory( path ), blank_resp() );
 
-               attrExpiration = sizeExpiration = 0;
-       }
+        attrExpiration = sizeExpiration = 0;
+    }
 /**
  * Creates a directory with the path specified by this <tt>SmbFile</tt> and any parent directories if necessary.
  * For this method to be successfull, the target
@@ -2005,79 +1991,80 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  *
  * @throws SmbException
  */
-       public void mkdirs() throws SmbException {
-               SmbFile parent;
-
-               try {
-                       parent = new SmbFile( new URL( null, getParent(), Handler.SMB_HANDLER ));
-               } catch( IOException ioe ) {
-                       return;
-               }
-               if( parent.exists() == false ) {
-                       parent.mkdirs();
-               }
-               mkdir();
-       }
-
-       public void createNewFile() throws SmbException {
-               if( getUncPath0().length() == 1 ) {
-                       throw new SmbException( SmbException.ERRDOS,
-                                                                       SmbException.ERRnoaccess );
-               }
-               close( open0( O_RDWR | O_CREAT | O_EXCL, ATTR_NORMAL, 0 ), 0L );
-       }
-
-       void setPathInformation( int attrs, long ctime, long mtime ) throws SmbException {
-               int f = open0( O_RDONLY | SmbComNTCreateAndX.FILE_WRITE_ATTRIBUTES << 16, attrs, 0 );
-
-               sendTransaction( new Trans2SetFileInformation( f, attrs, ctime, mtime ), new Trans2SetFileInformationResponse() );
-
-               close( f, 0L );
-
-               attrExpiration = 0;
-       }
-
-       public void setCreateTime( long time ) throws SmbException {
-               if( getUncPath0().length() == 1 ) {
-                       throw new SmbException( SmbException.ERRDOS,
-                                                                       SmbException.ERRnoaccess );
-               }
-
-               setPathInformation( 0, time, 0L );
-       }
-       public void setLastModified( long time ) throws SmbException {
-               if( getUncPath0().length() == 1 ) {
-                       throw new SmbException( SmbException.ERRDOS,
-                                                                       SmbException.ERRnoaccess );
-               }
-
-               setPathInformation( 0, 0L, time );
-       }
-
-       public int getAttributes() throws SmbException {
-               if( getUncPath0().length() == 1 ) {
-                       return 0;
-               }
-               exists();
-               return attributes & ATTR_GET_MASK;
-       }
-
-       public void setAttributes( int attrs ) throws SmbException {
-               if( getUncPath0().length() == 1 ) {
-                       throw new SmbException( SmbException.ERRDOS,
-                                                                       SmbException.ERRnoaccess );
-               }
-
-               setPathInformation( attrs & ATTR_SET_MASK, 0L, 0L );
-       }
-
-       public void setReadOnly() throws SmbException {
-               setAttributes( getAttributes() | ATTR_READONLY );
-       }
-
-       public void setReadWrite() throws SmbException {
-               setAttributes( getAttributes() & ~ATTR_READONLY );
-       }
+    public void mkdirs() throws SmbException {
+        SmbFile parent;
+
+        try {
+            parent = new SmbFile( new URL( null, getParent(), Handler.SMB_HANDLER ));
+        } catch( IOException ioe ) {
+            return;
+        }
+        if( parent.exists() == false ) {
+            parent.mkdirs();
+        }
+        mkdir();
+    }
+
+    public void createNewFile() throws SmbException {
+        if( getUncPath0().length() == 1 ) {
+            throw new SmbException( "Invalid operation for workgroups, servers, or shares" );
+        }
+        close( open0( O_RDWR | O_CREAT | O_EXCL, ATTR_NORMAL, 0 ), 0L );
+    }
+
+    void setPathInformation( int attrs, long ctime, long mtime ) throws SmbException {
+        int f, options = 0;
+
+        if(( attrs & ATTR_DIRECTORY ) != 0 ) {
+            options = 1;
+        }
+
+        f = open0( O_RDONLY | SmbComNTCreateAndX.FILE_WRITE_ATTRIBUTES << 16, attrs, options );
+        sendTransaction( new Trans2SetFileInformation( f, attrs, ctime, mtime ),
+                new Trans2SetFileInformationResponse() );
+        close( f, 0L );
+
+        attrExpiration = 0;
+    }
+
+    public void setCreateTime( long time ) throws SmbException {
+        if( getUncPath0().length() == 1 ) {
+            throw new SmbException( "Invalid operation for workgroups, servers, or shares" );
+        }
+
+        setPathInformation( 0, time, 0L );
+    }
+    public void setLastModified( long time ) throws SmbException {
+        if( getUncPath0().length() == 1 ) {
+            throw new SmbException( "Invalid operation for workgroups, servers, or shares" );
+        }
+
+        setPathInformation( 0, 0L, time );
+    }
+
+    public int getAttributes() throws SmbException {
+        if( getUncPath0().length() == 1 ) {
+            return 0;
+        }
+        exists();
+        return attributes & ATTR_GET_MASK;
+    }
+
+    public void setAttributes( int attrs ) throws SmbException {
+        if( getUncPath0().length() == 1 ) {
+            throw new SmbException( "Invalid operation for workgroups, servers, or shares" );
+        }
+
+        setPathInformation( attrs & ATTR_SET_MASK, 0L, 0L );
+    }
+
+    public void setReadOnly() throws SmbException {
+        setAttributes( getAttributes() | ATTR_READONLY );
+    }
+
+    public void setReadWrite() throws SmbException {
+        setAttributes( getAttributes() & ~ATTR_READONLY );
+    }
 
 /**
  * Returns a {@link java.net.URL} for this <code>SmbFile</code>. The
@@ -2090,9 +2077,9 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @return   A new <code>{@link java.net.URL}</code> for this <code>SmbFile</code>
  */
 
-       public URL toURL() throws MalformedURLException {
-               return url;
-       }
+    public URL toURL() throws MalformedURLException {
+        return url;
+    }
 
 /**
  * Computes a hashCode for this file based on the URL string and IP
@@ -2106,16 +2093,16 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @return  A hashcode for this abstract file
  */
 
-       public int hashCode() {
-               int hash;
-               try {
-                       hash = getAddress().hashCode();
-               } catch( UnknownHostException uhe ) {
-                       hash = getServer().toUpperCase().hashCode();
-               }
-               getUncPath0();
-               return hash + canon.toUpperCase().hashCode();
-       }
+    public int hashCode() {
+        int hash;
+        try {
+            hash = getAddress().hashCode();
+        } catch( UnknownHostException uhe ) {
+            hash = getServer().toUpperCase().hashCode();
+        }
+        getUncPath0();
+        return hash + canon.toUpperCase().hashCode();
+    }
 
 /**
  * Tests to see if two <code>SmbFile</code> objects are equal. Two
@@ -2138,9 +2125,9 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  *          and <code>false</code> otherwise
  */
 
-       public boolean equals( Object obj ) {
-               return obj instanceof SmbFile && obj.hashCode() == hashCode();
-       }
+    public boolean equals( Object obj ) {
+        return obj instanceof SmbFile && obj.hashCode() == hashCode();
+    }
 
 /**
  * Returns the string representation of this SmbFile object. This will
@@ -2151,34 +2138,34 @@ The <tt>shareAccess</tt> parameter controls what permissions other clients have
  * @return  The original URL representation of this SMB resource
  */
 
-       public String toString() {
-               return url.toString();
-       }
+    public String toString() {
+        return url.toString();
+    }
 
 /* URLConnection implementation */
 
-       public int getContentLength() {
-               try {
-                       return (int)(length() & 0xFFFFFFFFL);
-               } catch( SmbException se ) {
-               }
-               return 0;
-       }
-       public long getDate() {
-               try {
-                       return lastModified();
-               } catch( SmbException se ) {
-               }
-               return 0L;
-       }
-       public long getLastModified() {
-               try {
-                       return lastModified();
-               } catch( SmbException se ) {
-               }
-               return 0L;
-       }
-       public InputStream getInputStream() throws IOException {
-               return new SmbFileInputStream( this );
-       }
+    public int getContentLength() {
+        try {
+            return (int)(length() & 0xFFFFFFFFL);
+        } catch( SmbException se ) {
+        }
+        return 0;
+    }
+    public long getDate() {
+        try {
+            return lastModified();
+        } catch( SmbException se ) {
+        }
+        return 0L;
+    }
+    public long getLastModified() {
+        try {
+            return lastModified();
+        } catch( SmbException se ) {
+        }
+        return 0L;
+    }
+    public InputStream getInputStream() throws IOException {
+        return new SmbFileInputStream( this );
+    }
 }
index 9f4468c..47b9084 100644 (file)
@@ -19,5 +19,5 @@
 package jcifs.smb;
 
 public interface SmbFileFilter {
-       public boolean accept( SmbFile file ) throws SmbException;
+    public boolean accept( SmbFile file ) throws SmbException;
 }
index 8207313..2efc0bc 100644 (file)
@@ -30,10 +30,10 @@ import java.io.IOException;
 
 public class SmbFileInputStream extends InputStream {
 
-       private SmbFile file;
-       private long fp;
-       private int readSize, openFlags;
-       private byte[] tmp = new byte[1];
+    private SmbFile file;
+    private long fp;
+    private int readSize, openFlags;
+    private byte[] tmp = new byte[1];
 
 /**
  * Creates an {@link java.io.InputStream} for reading bytes from a file on
@@ -45,9 +45,9 @@ public class SmbFileInputStream extends InputStream {
  * @return A new <code>InputStream</code> for the specified <code>SmbFile</code>
  */
 
-       public SmbFileInputStream( String url ) throws SmbException, MalformedURLException, UnknownHostException {
-               this( new SmbFile( url ));
-       }
+    public SmbFileInputStream( String url ) throws SmbException, MalformedURLException, UnknownHostException {
+        this( new SmbFile( url ));
+    }
 
 /**
  * Creates an {@link java.io.InputStream} for reading bytes from a file on
@@ -59,17 +59,17 @@ public class SmbFileInputStream extends InputStream {
  * @return A new <code>InputStream</code> for the specified <code>SmbFile</code>
  */
 
-       public SmbFileInputStream( SmbFile file ) throws SmbException, MalformedURLException, UnknownHostException {
-               this( file, SmbFile.O_RDONLY );
-       }
+    public SmbFileInputStream( SmbFile file ) throws SmbException, MalformedURLException, UnknownHostException {
+        this( file, SmbFile.O_RDONLY );
+    }
 
-       SmbFileInputStream( SmbFile file, int openFlags ) throws SmbException, MalformedURLException, UnknownHostException {
-               this.file = file;
-               this.openFlags = openFlags;
-               file.open( openFlags, SmbFile.ATTR_NORMAL, 0 );
-               readSize = Math.min( file.tree.session.transport.rcv_buf_size - 70,
-                                                       file.tree.session.transport.server.maxBufferSize - 70 );
-       }
+    SmbFileInputStream( SmbFile file, int openFlags ) throws SmbException, MalformedURLException, UnknownHostException {
+        this.file = file;
+        this.openFlags = openFlags;
+        file.open( openFlags, SmbFile.ATTR_NORMAL, 0 );
+        readSize = Math.min( file.tree.session.transport.rcv_buf_size - 70,
+                            file.tree.session.transport.server.maxBufferSize - 70 );
+    }
 
 /**
  * Closes this input stream and releases any system resources associated with the stream.
@@ -77,9 +77,9 @@ public class SmbFileInputStream extends InputStream {
  * @throws IOException if a network error occurs
  */
 
-       public void close() throws IOException {
-               file.close();
-       }
+    public void close() throws IOException {
+        file.close();
+    }
 
 /**
  * Reads a byte of data from this input stream.
@@ -87,13 +87,13 @@ public class SmbFileInputStream extends InputStream {
  * @throws IOException if a network error occurs
  */
 
-       public int read() throws IOException {
-               // need oplocks to cache otherwise use BufferedInputStream
-               if( read( tmp, 0, 1 ) == -1 ) {
-                       return -1;
-               }
-               return tmp[0] & 0xFF;
-       }
+    public int read() throws IOException {
+        // need oplocks to cache otherwise use BufferedInputStream
+        if( read( tmp, 0, 1 ) == -1 ) {
+            return -1;
+        }
+        return tmp[0] & 0xFF;
+    }
 
 /**
  * Reads up to b.length bytes of data from this input stream into an array of bytes.
@@ -101,9 +101,9 @@ public class SmbFileInputStream extends InputStream {
  * @throws IOException if a network error occurs
  */
 
-       public int read( byte[] b ) throws IOException {
-               return read( b, 0, b.length );
-       }
+    public int read( byte[] b ) throws IOException {
+        return read( b, 0, b.length );
+    }
 
 /**
  * Reads up to len bytes of data from this input stream into an array of bytes.
@@ -111,86 +111,89 @@ public class SmbFileInputStream extends InputStream {
  * @throws IOException if a network error occurs
  */
 
-       public int read( byte[] b, int off, int len ) throws IOException {
-               if( len <= 0 ) {
-                       return 0;
-               }
-               long start = fp;
-
-               // ensure file is open
-               file.open( openFlags, SmbFile.ATTR_NORMAL, 0 );
-
-//Log.println( Log.WARNINGS, "smb read warning", " fid=" + file.fid + ",off=" + off + ",len=" + len );
-
-               /*
-                * Read AndX Request / Response
-                */
-
-               SmbComReadAndXResponse response = new SmbComReadAndXResponse( b, off );
-
-               if( file.type == SmbFile.TYPE_NAMED_PIPE ) {
-                       response.responseTimeout = 0;
-               }
-
-               int r, n;
-               do {
-                       r = len > readSize ? readSize : len;
-//System.out.println( "len=" + len + ",r=" + r + ",fp=" + fp );
-                       try {
-                               file.send( new SmbComReadAndX( file.fid, fp, r, null ), response );
-                       } catch( SmbException se ) {
-                               if( file.type == SmbFile.TYPE_NAMED_PIPE &&
-                                               se.errorClass == SmbException.ERRDOS &&
-                                               se.errorCode == SmbException.ERRbrokenpipe ) {
-                                       return -1;
-                               }
-                               throw se;
-                       }
-                       if(( n = response.dataLength ) <= 0 ) {
-                               return (int)((fp - start) > 0L ? fp - start : -1);
-                       }
-                       fp += n;
-                       len -= n;
-                       response.off += n;
-               } while( len > 0 && n == r );
-
-               return (int)(fp - start);
-       }
-       public int available() throws IOException {
-               SmbNamedPipe pipe;
-               TransPeekNamedPipe req;
-               TransPeekNamedPipeResponse resp;
-
-               if( file.type != SmbFile.TYPE_NAMED_PIPE ) {
-                       return 0;
-               }
-
-               pipe = (SmbNamedPipe)file;
-               file.open(( pipe.pipeType & 0xFF0000 ) | SmbFile.O_EXCL, SmbFile.ATTR_NORMAL, 0 );
-
-               req = new TransPeekNamedPipe( file.unc, file.fid );
-               resp = new TransPeekNamedPipeResponse( pipe );
-
-               pipe.sendTransaction( req, resp );
-               if( resp.status == TransPeekNamedPipeResponse.STATUS_DISCONNECTED ||
-                               resp.status == TransPeekNamedPipeResponse.STATUS_SERVER_END_CLOSED ) {
-                       file.opened = false;
-                       return 0;
-               }
-               return resp.available;
-       }
+    public int read( byte[] b, int off, int len ) throws IOException {
+        if( len <= 0 ) {
+            return 0;
+        }
+        long start = fp;
+
+        // ensure file is open
+        file.open( openFlags, SmbFile.ATTR_NORMAL, 0 );
+
+        /*
+         * Read AndX Request / Response
+         */
+
+        if( file.log.level > 2 )
+            file.log.println( "read: fid=" + file.fid + ",off=" + off + ",len=" + len );
+
+        SmbComReadAndXResponse response = new SmbComReadAndXResponse( b, off );
+
+        if( file.type == SmbFile.TYPE_NAMED_PIPE ) {
+            response.responseTimeout = 0;
+        }
+
+        int r, n;
+        do {
+            r = len > readSize ? readSize : len;
+
+            if( file.log.level > 2 )
+                file.log.println( "read: len=" + len + ",r=" + r + ",fp=" + fp );
+
+            try {
+                file.send( new SmbComReadAndX( file.fid, fp, r, null ), response );
+            } catch( SmbException se ) {
+                if( file.type == SmbFile.TYPE_NAMED_PIPE &&
+                        se.getNtStatus() == NtStatus.NT_STATUS_PIPE_BROKEN ) {
+                    return -1;
+                }
+                throw se;
+            }
+            if(( n = response.dataLength ) <= 0 ) {
+                return (int)((fp - start) > 0L ? fp - start : -1);
+            }
+            fp += n;
+            len -= n;
+            response.off += n;
+        } while( len > 0 && n == r );
+
+        return (int)(fp - start);
+    }
+    public int available() throws IOException {
+        SmbNamedPipe pipe;
+        TransPeekNamedPipe req;
+        TransPeekNamedPipeResponse resp;
+
+        if( file.type != SmbFile.TYPE_NAMED_PIPE ) {
+            return 0;
+        }
+
+        pipe = (SmbNamedPipe)file;
+        file.open(( pipe.pipeType & 0xFF0000 ) | SmbFile.O_EXCL, SmbFile.ATTR_NORMAL, 0 );
+
+        req = new TransPeekNamedPipe( file.unc, file.fid );
+        resp = new TransPeekNamedPipeResponse( pipe );
+
+        pipe.sendTransaction( req, resp );
+        if( resp.status == TransPeekNamedPipeResponse.STATUS_DISCONNECTED ||
+                resp.status == TransPeekNamedPipeResponse.STATUS_SERVER_END_CLOSED ) {
+            file.opened = false;
+            return 0;
+        }
+        return resp.available;
+    }
 /**
  * Skip n bytes of data on this stream. This operation will not result
  * in any IO with the server. Unlink <tt>InputStream</tt> value less than
  * the one provided will not be returned if it exceeds the end of the file
  * (if this is a problem let us know).
  */
-       public long skip( long n ) throws IOException {
-               if (n > 0) {
-                       fp += n;
-                       return n;
-               }
-               return 0;
-       }
+    public long skip( long n ) throws IOException {
+        if (n > 0) {
+            fp += n;
+            return n;
+        }
+        return 0;
+    }
 }
 
index d0e1f89..18a3f9c 100644 (file)
-/* jcifs smb client library in Java\r
- * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>\r
- * \r
- * This library is free software; you can redistribute it and/or\r
- * modify it under the terms of the GNU Lesser General Public\r
- * License as published by the Free Software Foundation; either\r
- * version 2.1 of the License, or (at your option) any later version.\r
- * \r
- * This library is distributed in the hope that it will be useful,\r
- * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r
- * Lesser General Public License for more details.\r
- * \r
- * You should have received a copy of the GNU Lesser General Public\r
- * License along with this library; if not, write to the Free Software\r
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
- */\r
-\r
-package jcifs.smb;\r
-\r
-import java.net.URL;\r
-import java.io.OutputStream;\r
-import java.io.IOException;\r
-import java.net.UnknownHostException;\r
-import java.net.MalformedURLException;\r
-\r
-/**\r
- * This <code>OutputStream</code> can write bytes to a file on an SMB file server.\r
- */\r
-\r
-public class SmbFileOutputStream extends OutputStream {\r
-\r
-       private SmbFile file;\r
-       private boolean append, useNTSmbs;\r
-       private int openFlags, writeSize;\r
-       private long fp;\r
-       private byte[] tmp = new byte[1];\r
-       private SmbComWriteAndX reqx;\r
-       private SmbComWriteAndXResponse rspx;\r
-       private SmbComWrite req;\r
-       private SmbComWriteResponse rsp;\r
-\r
-/**\r
- * Creates an {@link java.io.OutputStream} for writing to a file\r
- * on an SMB server addressed by the URL parameter. See {@link\r
- * jcifs.smb.SmbFile} for a detailed description and examples of\r
- * the smb URL syntax.\r
- *\r
- * @param url An smb URL string representing the file to write to\r
- * @return A new <code>OutputStream</code> for the specified file\r
- */\r
-\r
-       public SmbFileOutputStream( String url ) throws SmbException, MalformedURLException, UnknownHostException {\r
-               this( url, false );\r
-       }\r
-\r
-/**\r
- * Creates an {@link java.io.OutputStream} for writing bytes to a file on\r
- * an SMB server represented by the {@link jcifs.smb.SmbFile} parameter. See\r
- * {@link jcifs.smb.SmbFile} for a detailed description and examples of\r
- * the smb URL syntax.\r
- *\r
- * @param url An <code>SmbFile</code> specifying the file to write to\r
- * @return A new <code>OutputStream</code> for the specified <code>SmbFile</code>\r
- */\r
-\r
-       public SmbFileOutputStream( SmbFile file ) throws SmbException, MalformedURLException, UnknownHostException {\r
-               this( file, false );\r
-       }\r
-\r
-/**\r
- * Creates an {@link java.io.OutputStream} for writing bytes to a file on an\r
- * SMB server addressed by the URL parameter. See {@link jcifs.smb.SmbFile}\r
- * for a detailed description and examples of the smb URL syntax. If the\r
- * second argument is <code>true</code>, then bytes will be written to the\r
- * end of the file rather than the beginning.\r
- *\r
- * @param url An smb URL string representing the file to write to\r
- * @return A new <code>OutputStream</code> for the specified <code>url</code>\r
- */\r
-\r
-       public SmbFileOutputStream( String url, boolean append ) throws SmbException, MalformedURLException, UnknownHostException {\r
-               this( new SmbFile( url ), append );\r
-       }\r
-\r
-/**\r
- * Creates an {@link java.io.OutputStream} for writing bytes to a file\r
- * on an SMB server addressed by the <code>SmbFile</code> parameter. See\r
- * {@link jcifs.smb.SmbFile} for a detailed description and examples of\r
- * the smb URL syntax. If the second argument is <code>true</code>, then\r
- * bytes will be written to the end of the file rather than the beginning.\r
- * \r
- * @param url An <code>SmbFile</code> representing the file to write to\r
- * @return A new <code>OutputStream</code> for the specified <code>SmbFile</code>\r
- */\r
-\r
-       public SmbFileOutputStream( SmbFile file, boolean append ) throws SmbException, MalformedURLException, UnknownHostException {\r
-               this( file, append, append ? SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_APPEND :\r
-                                                                       SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_TRUNC );\r
-       }\r
-/**\r
- * Creates an {@link java.io.OutputStream} for writing bytes to a file\r
- * on an SMB server addressed by the <code>SmbFile</code> parameter. See\r
- * {@link jcifs.smb.SmbFile} for a detailed description and examples of\r
- * the smb URL syntax.\r
-<p>\r
-The second parameter specifies how the file should be shared. If\r
-<code>SmbFile.FILE_NO_SHARE</code> is specified the client will\r
-have exclusive access to the file. An additional open command\r
-from jCIFS or another application will fail with the "file is being\r
-accessed by another process" error. The <code>FILE_SHARE_READ</code>,\r
-<code>FILE_SHARE_WRITE</code>, and <code>FILE_SHARE_DELETE</code> may be\r
-combined with the bitwise OR '|' to specify that other peocesses may read,\r
-write, and/or delete the file while the jCIFS user has the file open.\r
- * \r
- * @param url An <code>SmbFile</code> representing the file to write to\r
- * @return A new <code>OutputStream</code> for the specified <code>SmbFile</code>\r
- */\r
-\r
-       public SmbFileOutputStream( String url, int shareAccess ) throws SmbException, MalformedURLException, UnknownHostException {\r
-               this( new SmbFile( url, "", null, shareAccess ), false );\r
-       }\r
-\r
-       SmbFileOutputStream( SmbFile file, boolean append, int openFlags ) throws SmbException, MalformedURLException, UnknownHostException {\r
-               this.file = file;\r
-               this.append = append;\r
-               this.openFlags = openFlags;\r
-               if( append ) {\r
-                       try {\r
-                               fp = file.length();\r
-                       } catch( SmbException se ) {\r
-                               fp = 0L;\r
-                       }\r
-               }\r
-               file.open( openFlags, SmbFile.ATTR_NORMAL, 0 );\r
-               writeSize = Math.min( file.tree.session.transport.snd_buf_size - 70,\r
-                                                       file.tree.session.transport.server.maxBufferSize - 70 );\r
-\r
-               useNTSmbs = file.tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS );\r
-               if( useNTSmbs ) {\r
-                       reqx = new SmbComWriteAndX();\r
-                       rspx = new SmbComWriteAndXResponse();\r
-               } else {\r
-                       req = new SmbComWrite();\r
-                       rsp = new SmbComWriteResponse();        \r
-               }\r
-       }\r
-\r
-/**\r
- * Closes this output stream and releases any system resources associated\r
- * with it.\r
- *\r
- * @throws IOException if a network error occurs\r
- */\r
-\r
-       public void close() throws IOException {\r
-               file.close();\r
-       }\r
-\r
-/**\r
- * Writes the specified byte to this file output stream.\r
- *\r
- * @throws IOException if a network error occurs\r
- */\r
-\r
-       public void write( int b ) throws IOException {\r
-               tmp[0] = (byte)b;\r
-               write( tmp, 0, 1 );\r
-       }\r
-\r
-/**\r
- * Writes b.length bytes from the specified byte array to this\r
- * file output stream.\r
- *\r
- * @throws IOException if a network error occurs\r
- */\r
-\r
-       public void write( byte[] b ) throws IOException {\r
-               write( b, 0, b.length );\r
-       }\r
-\r
-/**\r
- * Writes len bytes from the specified byte array starting at\r
- * offset off to this file output stream.\r
- *\r
- * @param b The array \r
- * @throws IOException if a network error occurs\r
- */\r
-\r
-       public void write( byte[] b, int off, int len ) throws IOException {\r
-               if( len <= 0 ) {\r
-                       return;\r
-               }\r
-\r
-               // ensure file is open\r
-               if( file.isOpen() == false ) {\r
-                       file.open( openFlags, SmbFile.ATTR_NORMAL, 0 );\r
-                       if( append ) {\r
-                               fp = file.length();\r
-                       }\r
-               }\r
-\r
-/*\r
-               Log.println( Log.WARNINGS, "smb write warning",\r
-                                               " fid=" + file.fid + ",off=" + off + ",len=" + len );\r
-*/\r
-               int w;\r
-               do {\r
-                       w = len > writeSize ? writeSize : len;\r
-                       if( useNTSmbs ) {\r
-                               reqx.setParam( file.fid, fp, len - w, b, off, w );\r
-                               file.send( reqx, rspx );\r
-                               fp += rspx.count;\r
-                               len -= rspx.count;\r
-                               off += rspx.count;\r
-                       } else {\r
-                               req.setParam( file.fid, fp, len - w, b, off, w );\r
-                               fp += rsp.count;\r
-                               len -= rsp.count;\r
-                               off += rsp.count;\r
-                               file.send( req, rsp );\r
-                       }\r
-               } while( len > 0 );\r
-\r
-               file.attrExpiration = file.sizeExpiration = 0L;\r
-       }\r
-}\r
+/* jcifs smb client library in Java
+ * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package jcifs.smb;
+
+import java.net.URL;
+import java.io.OutputStream;
+import java.io.IOException;
+import java.net.UnknownHostException;
+import java.net.MalformedURLException;
+import jcifs.util.LogStream;
+
+/**
+ * This <code>OutputStream</code> can write bytes to a file on an SMB file server.
+ */
+
+public class SmbFileOutputStream extends OutputStream {
+
+    private SmbFile file;
+    private boolean append, useNTSmbs;
+    private int openFlags, writeSize;
+    private long fp;
+    private byte[] tmp = new byte[1];
+    private SmbComWriteAndX reqx;
+    private SmbComWriteAndXResponse rspx;
+    private SmbComWrite req;
+    private SmbComWriteResponse rsp;
+
+/**
+ * Creates an {@link java.io.OutputStream} for writing to a file
+ * on an SMB server addressed by the URL parameter. See {@link
+ * jcifs.smb.SmbFile} for a detailed description and examples of
+ * the smb URL syntax.
+ *
+ * @param url An smb URL string representing the file to write to
+ * @return A new <code>OutputStream</code> for the specified file
+ */
+
+    public SmbFileOutputStream( String url ) throws SmbException, MalformedURLException, UnknownHostException {
+        this( url, false );
+    }
+
+/**
+ * Creates an {@link java.io.OutputStream} for writing bytes to a file on
+ * an SMB server represented by the {@link jcifs.smb.SmbFile} parameter. See
+ * {@link jcifs.smb.SmbFile} for a detailed description and examples of
+ * the smb URL syntax.
+ *
+ * @param url An <code>SmbFile</code> specifying the file to write to
+ * @return A new <code>OutputStream</code> for the specified <code>SmbFile</code>
+ */
+
+    public SmbFileOutputStream( SmbFile file ) throws SmbException, MalformedURLException, UnknownHostException {
+        this( file, false );
+    }
+
+/**
+ * Creates an {@link java.io.OutputStream} for writing bytes to a file on an
+ * SMB server addressed by the URL parameter. See {@link jcifs.smb.SmbFile}
+ * for a detailed description and examples of the smb URL syntax. If the
+ * second argument is <code>true</code>, then bytes will be written to the
+ * end of the file rather than the beginning.
+ *
+ * @param url An smb URL string representing the file to write to
+ * @return A new <code>OutputStream</code> for the specified <code>url</code>
+ */
+
+    public SmbFileOutputStream( String url, boolean append ) throws SmbException, MalformedURLException, UnknownHostException {
+        this( new SmbFile( url ), append );
+    }
+
+/**
+ * Creates an {@link java.io.OutputStream} for writing bytes to a file
+ * on an SMB server addressed by the <code>SmbFile</code> parameter. See
+ * {@link jcifs.smb.SmbFile} for a detailed description and examples of
+ * the smb URL syntax. If the second argument is <code>true</code>, then
+ * bytes will be written to the end of the file rather than the beginning.
+ * 
+ * @param url An <code>SmbFile</code> representing the file to write to
+ * @return A new <code>OutputStream</code> for the specified <code>SmbFile</code>
+ */
+
+    public SmbFileOutputStream( SmbFile file, boolean append ) throws SmbException, MalformedURLException, UnknownHostException {
+        this( file, append, append ? SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_APPEND :
+                                    SmbFile.O_CREAT | SmbFile.O_WRONLY | SmbFile.O_TRUNC );
+    }
+/**
+ * Creates an {@link java.io.OutputStream} for writing bytes to a file
+ * on an SMB server addressed by the <code>SmbFile</code> parameter. See
+ * {@link jcifs.smb.SmbFile} for a detailed description and examples of
+ * the smb URL syntax.
+<p>
+The second parameter specifies how the file should be shared. If
+<code>SmbFile.FILE_NO_SHARE</code> is specified the client will
+have exclusive access to the file. An additional open command
+from jCIFS or another application will fail with the "file is being
+accessed by another process" error. The <code>FILE_SHARE_READ</code>,
+<code>FILE_SHARE_WRITE</code>, and <code>FILE_SHARE_DELETE</code> may be
+combined with the bitwise OR '|' to specify that other peocesses may read,
+write, and/or delete the file while the jCIFS user has the file open.
+ * 
+ * @param url An <code>SmbFile</code> representing the file to write to
+ * @return A new <code>OutputStream</code> for the specified <code>SmbFile</code>
+ */
+
+    public SmbFileOutputStream( String url, int shareAccess ) throws SmbException, MalformedURLException, UnknownHostException {
+        this( new SmbFile( url, "", null, shareAccess ), false );
+    }
+
+    SmbFileOutputStream( SmbFile file, boolean append, int openFlags ) throws SmbException, MalformedURLException, UnknownHostException {
+        this.file = file;
+        this.append = append;
+        this.openFlags = openFlags;
+        if( append ) {
+            try {
+                fp = file.length();
+            } catch( SmbException se ) {
+                fp = 0L;
+            }
+        }
+        if( file instanceof SmbNamedPipe && file.unc.startsWith( "\\pipe\\" )) {
+            file.unc = file.unc.substring( 5 );
+            file.sendTransaction( new TransWaitNamedPipe( "\\pipe" + file.unc ),
+                                        new TransWaitNamedPipeResponse() );
+        }
+        file.open( openFlags, SmbFile.ATTR_NORMAL, 0 );
+        writeSize = file.tree.session.transport.snd_buf_size - 70;
+
+        useNTSmbs = file.tree.session.transport.hasCapability( ServerMessageBlock.CAP_NT_SMBS );
+        if( useNTSmbs ) {
+            reqx = new SmbComWriteAndX();
+            rspx = new SmbComWriteAndXResponse();
+        } else {
+            req = new SmbComWrite();
+            rsp = new SmbComWriteResponse();    
+        }
+    }
+
+/**
+ * Closes this output stream and releases any system resources associated
+ * with it.
+ *
+ * @throws IOException if a network error occurs
+ */
+
+    public void close() throws IOException {
+        file.close();
+    }
+
+/**
+ * Writes the specified byte to this file output stream.
+ *
+ * @throws IOException if a network error occurs
+ */
+
+    public void write( int b ) throws IOException {
+        tmp[0] = (byte)b;
+        write( tmp, 0, 1 );
+    }
+
+/**
+ * Writes b.length bytes from the specified byte array to this
+ * file output stream.
+ *
+ * @throws IOException if a network error occurs
+ */
+
+    public void write( byte[] b ) throws IOException {
+        write( b, 0, b.length );
+    }
+
+/**
+ * Writes len bytes from the specified byte array starting at
+ * offset off to this file output stream.
+ *
+ * @param b The array 
+ * @throws IOException if a network error occurs
+ */
+
+    public void write( byte[] b, int off, int len ) throws IOException {
+        if( len <= 0 ) {
+            return;
+        }
+
+        // ensure file is open
+        if( file.isOpen() == false ) {
+            if( file instanceof SmbNamedPipe ) {
+                file.sendTransaction( new TransWaitNamedPipe( "\\pipe" + file.unc ),
+                                        new TransWaitNamedPipeResponse() );
+            }
+            file.open( openFlags, SmbFile.ATTR_NORMAL, 0 );
+            if( append ) {
+                fp = file.length();
+            }
+        }
+
+        if( file.log.level > 2 )
+            file.log.println( "write: fid=" + file.fid + ",off=" + off + ",len=" + len );
+
+        int w;
+        do {
+            w = len > writeSize ? writeSize : len;
+            if( useNTSmbs ) {
+                reqx.setParam( file.fid, fp, len - w, b, off, w );
+                file.send( reqx, rspx );
+                fp += rspx.count;
+                len -= rspx.count;
+                off += rspx.count;
+            } else {
+                req.setParam( file.fid, fp, len - w, b, off, w );
+                fp += rsp.count;
+                len -= rsp.count;
+                off += rsp.count;
+                file.send( req, rsp );
+            }
+        } while( len > 0 );
+    }
+}
index 26d3ece..847ea6f 100644 (file)
@@ -19,5 +19,5 @@
 package jcifs.smb;
 
 public interface SmbFilenameFilter {
-       public boolean accept( SmbFile dir, String name ) throws SmbException;
+    public boolean accept( SmbFile dir, String name ) throws SmbException;
 }
index 9289853..7bbb605 100644 (file)
@@ -86,108 +86,108 @@ import java.net.UnknownHostException;
 
 public class SmbNamedPipe extends SmbFile {
 
-       /**
-        * The pipe should be opened read-only.
-        */
-
-       public static final int PIPE_TYPE_RDONLY = O_RDONLY;
-
-       /**
-        * The pipe should be opened only for writing.
-        */
-
-       public static final int PIPE_TYPE_WRONLY = O_WRONLY;
-
-       /**
-        * The pipe should be opened for both reading and writing.
-        */
-
-       public static final int PIPE_TYPE_RDWR   = O_RDWR;
-
-       /**
-        * Pipe operations should behave like the <code>CallNamedPipe</code> Win32 Named Pipe function.
-        */
-
-       public static final int PIPE_TYPE_CALL   = 0x01;
-
-       /**
-        * Pipe operations should behave like the <code>TransactNamedPipe</code> Win32 Named Pipe function.
-        */
-
-       public static final int PIPE_TYPE_TRANSACT = 0x02;
-
-       InputStream pipeIn;
-       OutputStream pipeOut;
-       int pipeType;
-
-       /**
-        * Open the Named Pipe resource specified by the url
-        * parameter. The pipeType parameter should be at least one of
-        * the <code>PIPE_TYPE</code> flags combined with the bitwise OR
-        * operator <code>|</code>. See the examples listed above.
-        */
-
-       public SmbNamedPipe( String url, int pipeType )
-                                                       throws MalformedURLException, UnknownHostException {
-               super( url );
-               this.pipeType = pipeType;
-               type = TYPE_NAMED_PIPE;
-       }
-       public SmbNamedPipe( String url, int pipeType, NtlmPasswordAuthentication auth )
-                                                       throws MalformedURLException, UnknownHostException {
-               super( url, auth );
-               this.pipeType = pipeType;
-               type = TYPE_NAMED_PIPE;
-       }
-       public SmbNamedPipe( URL url, int pipeType, NtlmPasswordAuthentication auth )
-                                                       throws MalformedURLException, UnknownHostException {
-               super( url, auth );
-               this.pipeType = pipeType;
-               type = TYPE_NAMED_PIPE;
-       }
-
-       /**
-        * Return the <code>InputStream</code> used to read information
-        * from this pipe instance. Presumably data would first be written
-        * to the <code>OutputStream</code> associated with this Named
-        * Pipe instance although this is not a requirement (e.g. a
-        * read-only named pipe would write data to this stream on
-        * connection). Reading from this stream may block. Therefore it
-        * may be necessary that an addition thread be used to read and
-        * write to a Named Pipe.
-        */
-
-       public InputStream getNamedPipeInputStream() throws IOException {
-               if( pipeIn == null ) {
-                       if(( pipeType & PIPE_TYPE_CALL ) == PIPE_TYPE_CALL ||
-                                       ( pipeType & PIPE_TYPE_TRANSACT ) == PIPE_TYPE_TRANSACT ) {
-                               pipeIn = new TransactNamedPipeInputStream( this );
-                       } else {
-                               pipeIn = new SmbFileInputStream( this,
-                                                                                       ( pipeType & 0xFF0000 ) | SmbFile.O_EXCL );
-                       }
-               }
-               return pipeIn;
-       }
-
-       /**
-        * Return the <code>OutputStream</code> used to write
-        * information to this pipe instance. The act of writing data
-        * to this stream will result in response data recieved in the
-        * <code>InputStream</code> associated with this Named Pipe
-        * instance (unless of course it does not elicite a response or the pipe is write-only).
-        */
-
-       public OutputStream getNamedPipeOutputStream() throws IOException {
-               if( pipeOut == null ) {
-                       if(( pipeType & PIPE_TYPE_CALL ) == PIPE_TYPE_CALL ||
-                                       ( pipeType & PIPE_TYPE_TRANSACT ) == PIPE_TYPE_TRANSACT ) {
-                               pipeOut = new TransactNamedPipeOutputStream( this );
-                       } else {
-                               pipeOut = new SmbFileOutputStream( this, false,
-                                                                                       ( pipeType & 0xFF0000 ) | SmbFile.O_EXCL );
-                       }
-               }
-               return pipeOut;
-       }
+    /**
+     * The pipe should be opened read-only.
+     */
+
+    public static final int PIPE_TYPE_RDONLY = O_RDONLY;
+
+    /**
+     * The pipe should be opened only for writing.
+     */
+
+    public static final int PIPE_TYPE_WRONLY = O_WRONLY;
+
+    /**
+     * The pipe should be opened for both reading and writing.
+     */
+
+    public static final int PIPE_TYPE_RDWR   = O_RDWR;
+
+    /**
+     * Pipe operations should behave like the <code>CallNamedPipe</code> Win32 Named Pipe function.
+     */
+
+    public static final int PIPE_TYPE_CALL   = 0x01;
+
+    /**
+     * Pipe operations should behave like the <code>TransactNamedPipe</code> Win32 Named Pipe function.
+     */
+
+    public static final int PIPE_TYPE_TRANSACT = 0x02;
+
+    InputStream pipeIn;
+    OutputStream pipeOut;
+    int pipeType;
+
+    /**
+     * Open the Named Pipe resource specified by the url
+     * parameter. The pipeType parameter should be at least one of
+     * the <code>PIPE_TYPE</code> flags combined with the bitwise OR
+     * operator <code>|</code>. See the examples listed above.
+     */
+
+    public SmbNamedPipe( String url, int pipeType )
+                            throws MalformedURLException, UnknownHostException {
+        super( url );
+        this.pipeType = pipeType;
+        type = TYPE_NAMED_PIPE;
+    }
+    public SmbNamedPipe( String url, int pipeType, NtlmPasswordAuthentication auth )
+                            throws MalformedURLException, UnknownHostException {
+        super( url, auth );
+        this.pipeType = pipeType;
+        type = TYPE_NAMED_PIPE;
+    }
+    public SmbNamedPipe( URL url, int pipeType, NtlmPasswordAuthentication auth )
+                            throws MalformedURLException, UnknownHostException {
+        super( url, auth );
+        this.pipeType = pipeType;
+        type = TYPE_NAMED_PIPE;
+    }
+
+    /**
+     * Return the <code>InputStream</code> used to read information
+     * from this pipe instance. Presumably data would first be written
+     * to the <code>OutputStream</code> associated with this Named
+     * Pipe instance although this is not a requirement (e.g. a
+     * read-only named pipe would write data to this stream on
+     * connection). Reading from this stream may block. Therefore it
+     * may be necessary that an addition thread be used to read and
+     * write to a Named Pipe.
+     */
+
+    public InputStream getNamedPipeInputStream() throws IOException {
+        if( pipeIn == null ) {
+            if(( pipeType & PIPE_TYPE_CALL ) == PIPE_TYPE_CALL ||
+                    ( pipeType & PIPE_TYPE_TRANSACT ) == PIPE_TYPE_TRANSACT ) {
+                pipeIn = new TransactNamedPipeInputStream( this );
+            } else {
+                pipeIn = new SmbFileInputStream( this,
+                                            ( pipeType & 0xFF0000 ) | SmbFile.O_EXCL );
+            }
+        }
+        return pipeIn;
+    }
+
+    /**
+     * Return the <code>OutputStream</code> used to write
+     * information to this pipe instance. The act of writing data
+     * to this stream will result in response data recieved in the
+     * <code>InputStream</code> associated with this Named Pipe
+     * instance (unless of course it does not elicite a response or the pipe is write-only).
+     */
+
+    public OutputStream getNamedPipeOutputStream() throws IOException {
+        if( pipeOut == null ) {
+            if(( pipeType & PIPE_TYPE_CALL ) == PIPE_TYPE_CALL ||
+                    ( pipeType & PIPE_TYPE_TRANSACT ) == PIPE_TYPE_TRANSACT ) {
+                pipeOut = new TransactNamedPipeOutputStream( this );
+            } else {
+                pipeOut = new SmbFileOutputStream( this, false,
+                                            ( pipeType & 0xFF0000 ) | SmbFile.O_EXCL );
+            }
+        }
+        return pipeOut;
+    }
 }
index 739fb88..1829182 100644 (file)
@@ -29,309 +29,305 @@ import jcifs.util.Encdec;
 
 public class SmbRandomAccessFile implements DataOutput, DataInput {
 
-       private static final int WRITE_OPTIONS = 0x0842;
+    private static final int WRITE_OPTIONS = 0x0842;
 
-       SmbFile file;
-       long fp;
-       int openFlags, readSize, writeSize, ch, options = 0;
-       byte[] tmp = new byte[8];
-       SmbComWriteAndXResponse write_andx_resp = null;
+    private SmbFile file;
+    private long fp;
+    private int openFlags, readSize, writeSize, ch, options = 0;
+    private byte[] tmp = new byte[8];
+    private SmbComWriteAndXResponse write_andx_resp = null;
 
-       public SmbRandomAccessFile( String url, String mode, int shareAccess )
-                       throws SmbException, MalformedURLException, UnknownHostException {
-               this( new SmbFile( url, "", null, shareAccess ), mode );
-       }
-       public SmbRandomAccessFile( SmbFile file, String mode )
-                       throws SmbException, MalformedURLException, UnknownHostException {
-               this.file = file;
-               if( mode.equals( "r" )) {
-                       this.openFlags = SmbFile.O_CREAT | SmbFile.O_RDONLY;
-               } else if( mode.equals( "rw" )) {
-                       this.openFlags = SmbFile.O_CREAT | SmbFile.O_RDWR | SmbFile.O_APPEND;
-                       write_andx_resp = new SmbComWriteAndXResponse();
-                       options = WRITE_OPTIONS;
-               } else {
-                       throw new IllegalArgumentException( "Invalid mode" );
-               }
-               file.open( openFlags, SmbFile.ATTR_NORMAL, options );
-               readSize = Math.min( file.tree.session.transport.rcv_buf_size - 70,
-                                       file.tree.session.transport.server.maxBufferSize - 70 );
-               writeSize = Math.min( file.tree.session.transport.snd_buf_size - 70,
-                                       file.tree.session.transport.server.maxBufferSize - 70 );
-               fp = 0L;
-       }
+    public SmbRandomAccessFile( String url, String mode, int shareAccess )
+            throws SmbException, MalformedURLException, UnknownHostException {
+        this( new SmbFile( url, "", null, shareAccess ), mode );
+    }
+    public SmbRandomAccessFile( SmbFile file, String mode )
+            throws SmbException, MalformedURLException, UnknownHostException {
+        this.file = file;
+        if( mode.equals( "r" )) {
+            this.openFlags = SmbFile.O_CREAT | SmbFile.O_RDONLY;
+        } else if( mode.equals( "rw" )) {
+            this.openFlags = SmbFile.O_CREAT | SmbFile.O_RDWR | SmbFile.O_APPEND;
+            write_andx_resp = new SmbComWriteAndXResponse();
+            options = WRITE_OPTIONS;
+        } else {
+            throw new IllegalArgumentException( "Invalid mode" );
+        }
+        file.open( openFlags, SmbFile.ATTR_NORMAL, options );
+        readSize = file.tree.session.transport.rcv_buf_size - 70;
+        writeSize = file.tree.session.transport.snd_buf_size - 70;
+        fp = 0L;
+    }
 
-       public int read() throws SmbException {
-               if( read( tmp, 0, 1 ) == -1 ) {
-                       return -1;
-               }
-               return tmp[0] & 0xFF;
-       }
-       public int read( byte b[] ) throws SmbException {
-               return read( b, 0, b.length );
-       }
-       public int read( byte b[], int off, int len ) throws SmbException {
-               if( len <= 0 ) {
-                       return 0;
-               }
-               long start = fp;
+    public int read() throws SmbException {
+        if( read( tmp, 0, 1 ) == -1 ) {
+            return -1;
+        }
+        return tmp[0] & 0xFF;
+    }
+    public int read( byte b[] ) throws SmbException {
+        return read( b, 0, b.length );
+    }
+    public int read( byte b[], int off, int len ) throws SmbException {
+        if( len <= 0 ) {
+            return 0;
+        }
+        long start = fp;
 
-               // ensure file is open
-               if( file.isOpen() == false ) {
-                       file.open( openFlags, SmbFile.ATTR_NORMAL, options );
-               }
+        // ensure file is open
+        if( file.isOpen() == false ) {
+            file.open( openFlags, SmbFile.ATTR_NORMAL, options );
+        }
 
-               int r, n;
-               SmbComReadAndXResponse response = new SmbComReadAndXResponse( b, off );
-               do {
-                       r = len > readSize ? readSize : len;
-                       file.send( new SmbComReadAndX( file.fid, fp, r, null ), response );
-                       if(( n = response.dataLength ) <= 0 ) {
-                               return (int)((fp - start) > 0L ? fp - start : -1);
-                       }
-                       fp += n;
-                       len -= n;
-                       response.off += n;
-               } while( len > 0 && n == r );
+        int r, n;
+        SmbComReadAndXResponse response = new SmbComReadAndXResponse( b, off );
+        do {
+            r = len > readSize ? readSize : len;
+            file.send( new SmbComReadAndX( file.fid, fp, r, null ), response );
+            if(( n = response.dataLength ) <= 0 ) {
+                return (int)((fp - start) > 0L ? fp - start : -1);
+            }
+            fp += n;
+            len -= n;
+            response.off += n;
+        } while( len > 0 && n == r );
 
-               return (int)(fp - start);
-       }
-       public final void readFully( byte b[] ) throws SmbException {
-               readFully( b, 0, b.length );
-       }
-       public final void readFully( byte b[], int off, int len ) throws SmbException {
-               int n = 0, count;
+        return (int)(fp - start);
+    }
+    public final void readFully( byte b[] ) throws SmbException {
+        readFully( b, 0, b.length );
+    }
+    public final void readFully( byte b[], int off, int len ) throws SmbException {
+        int n = 0, count;
 
-               do {    
-                       count = this.read( b, off + n, len - n );
-                       if( count < 0 ) throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, "EOF" );
-                       n += count;
-                       fp += count;
-               } while( n < len );
-       }
-       public int skipBytes( int n ) throws SmbException {
-               if (n > 0) {
-                       fp += n;
-                       return n;
-               }
-               return 0;
-       }
+        do {    
+            count = this.read( b, off + n, len - n );
+            if( count < 0 ) throw new SmbException( "EOF" );
+            n += count;
+            fp += count;
+        } while( n < len );
+    }
+    public int skipBytes( int n ) throws SmbException {
+        if (n > 0) {
+            fp += n;
+            return n;
+        }
+        return 0;
+    }
 
-       public void write( int b ) throws SmbException {
-               tmp[0] = (byte)b;
-               write( tmp, 0, 1 );
-       }
-       public void write( byte b[] ) throws SmbException {
-               write( b, 0, b.length );
-       }
-       public void write( byte b[], int off, int len ) throws SmbException {
-               if( len <= 0 ) {
-                       return;
-               }
+    public void write( int b ) throws SmbException {
+        tmp[0] = (byte)b;
+        write( tmp, 0, 1 );
+    }
+    public void write( byte b[] ) throws SmbException {
+        write( b, 0, b.length );
+    }
+    public void write( byte b[], int off, int len ) throws SmbException {
+        if( len <= 0 ) {
+            return;
+        }
 
-               // ensure file is open
-               if( file.isOpen() == false ) {
-                       file.open( openFlags, SmbFile.ATTR_NORMAL, options );
-               }
+        // ensure file is open
+        if( file.isOpen() == false ) {
+            file.open( openFlags, SmbFile.ATTR_NORMAL, options );
+        }
 
-               int w;
-               do {
-                       w = len > writeSize ? writeSize : len;
-                       file.send( new SmbComWriteAndX( file.fid, fp, len - w, b, off, w, null ), write_andx_resp );
-                       fp += write_andx_resp.count;
-                       len -= write_andx_resp.count;
-                       off += write_andx_resp.count;
-               } while( len > 0 );
-       }
-       public long getFilePointer() throws SmbException {
-               return fp;
-       }
-       public void seek( long pos ) throws SmbException {
-               fp = pos;
-       }
-       public long length() throws SmbException {
-               return file.length();
-       }
-       public void setLength( long newLength ) throws SmbException {
-               // ensure file is open
-               if( file.isOpen() == false ) {
-                       file.open( openFlags, SmbFile.ATTR_NORMAL, options );
-               }
-               SmbComWriteResponse rsp = new SmbComWriteResponse();
-               file.send( new SmbComWrite( file.fid, (int)(newLength & 0xFFFFFFFFL), 0, tmp, 0, 0 ), rsp );
-       }
-       public void close() throws SmbException {
-               file.close();
-       }
+        int w;
+        do {
+            w = len > writeSize ? writeSize : len;
+            file.send( new SmbComWriteAndX( file.fid, fp, len - w, b, off, w, null ), write_andx_resp );
+            fp += write_andx_resp.count;
+            len -= write_andx_resp.count;
+            off += write_andx_resp.count;
+        } while( len > 0 );
+    }
+    public long getFilePointer() throws SmbException {
+        return fp;
+    }
+    public void seek( long pos ) throws SmbException {
+        fp = pos;
+    }
+    public long length() throws SmbException {
+        return file.length();
+    }
+    public void setLength( long newLength ) throws SmbException {
+        // ensure file is open
+        if( file.isOpen() == false ) {
+            file.open( openFlags, SmbFile.ATTR_NORMAL, options );
+        }
+        SmbComWriteResponse rsp = new SmbComWriteResponse();
+        file.send( new SmbComWrite( file.fid, (int)(newLength & 0xFFFFFFFFL), 0, tmp, 0, 0 ), rsp );
+    }
+    public void close() throws SmbException {
+        file.close();
+    }
 
-       public final boolean readBoolean() throws SmbException {
-               if((read( tmp, 0, 1 )) < 0 ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, "EOF" );
-               }
-               return tmp[0] != (byte)0x00;
-       }
-       public final byte readByte() throws SmbException {
-               if((read( tmp, 0, 1 )) < 0 ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, "EOF" );
-               }
-               return tmp[0];
-       }
-       public final int readUnsignedByte() throws SmbException {
-               if((read( tmp, 0, 1 )) < 0 ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, "EOF" );
-               }
-               return tmp[0] & 0xFF;
-       }
-       public final short readShort() throws SmbException {
-               if((read( tmp, 0, 2 )) < 0 ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, "EOF" );
-               }
-               return Encdec.dec_uint16be( tmp, 0 );
-       }
-       public final int readUnsignedShort() throws SmbException {
-               if((read( tmp, 0, 2 )) < 0 ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, "EOF" );
-               }
-               return Encdec.dec_uint16be( tmp, 0 );
-       }
-       public final char readChar() throws SmbException {
-               if((read( tmp, 0, 2 )) < 0 ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, "EOF" );
-               }
-               return (char)Encdec.dec_uint16be( tmp, 0 );
-       }
-       public final int readInt() throws SmbException {
-               if((read( tmp, 0, 4 )) < 0 ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, "EOF" );
-               }
-               return Encdec.dec_uint32be( tmp, 0 );
-       }
-       public final long readLong() throws SmbException {
-               if((read( tmp, 0, 8 )) < 0 ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, "EOF" );
-               }
-               return Encdec.dec_uint64be( tmp, 0 );
-       }
-       public final float readFloat() throws SmbException {
-               if((read( tmp, 0, 4 )) < 0 ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, "EOF" );
-               }
-               return Encdec.dec_floatbe( tmp, 0 );
-       }
-       public final double readDouble() throws SmbException {
-               if((read( tmp, 0, 8 )) < 0 ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, "EOF" );
-               }
-               return Encdec.dec_doublebe( tmp, 0 );
-       }
-       public final String readLine() throws SmbException {
-               StringBuffer input = new StringBuffer();
-               int c = -1;
-               boolean eol = false;
+    public final boolean readBoolean() throws SmbException {
+        if((read( tmp, 0, 1 )) < 0 ) {
+            throw new SmbException( "EOF" );
+        }
+        return tmp[0] != (byte)0x00;
+    }
+    public final byte readByte() throws SmbException {
+        if((read( tmp, 0, 1 )) < 0 ) {
+            throw new SmbException( "EOF" );
+        }
+        return tmp[0];
+    }
+    public final int readUnsignedByte() throws SmbException {
+        if((read( tmp, 0, 1 )) < 0 ) {
+            throw new SmbException( "EOF" );
+        }
+        return tmp[0] & 0xFF;
+    }
+    public final short readShort() throws SmbException {
+        if((read( tmp, 0, 2 )) < 0 ) {
+            throw new SmbException( "EOF" );
+        }
+        return Encdec.dec_uint16be( tmp, 0 );
+    }
+    public final int readUnsignedShort() throws SmbException {
+        if((read( tmp, 0, 2 )) < 0 ) {
+            throw new SmbException( "EOF" );
+        }
+        return Encdec.dec_uint16be( tmp, 0 );
+    }
+    public final char readChar() throws SmbException {
+        if((read( tmp, 0, 2 )) < 0 ) {
+            throw new SmbException( "EOF" );
+        }
+        return (char)Encdec.dec_uint16be( tmp, 0 );
+    }
+    public final int readInt() throws SmbException {
+        if((read( tmp, 0, 4 )) < 0 ) {
+            throw new SmbException( "EOF" );
+        }
+        return Encdec.dec_uint32be( tmp, 0 );
+    }
+    public final long readLong() throws SmbException {
+        if((read( tmp, 0, 8 )) < 0 ) {
+            throw new SmbException( "EOF" );
+        }
+        return Encdec.dec_uint64be( tmp, 0 );
+    }
+    public final float readFloat() throws SmbException {
+        if((read( tmp, 0, 4 )) < 0 ) {
+            throw new SmbException( "EOF" );
+        }
+        return Encdec.dec_floatbe( tmp, 0 );
+    }
+    public final double readDouble() throws SmbException {
+        if((read( tmp, 0, 8 )) < 0 ) {
+            throw new SmbException( "EOF" );
+        }
+        return Encdec.dec_doublebe( tmp, 0 );
+    }
+    public final String readLine() throws SmbException {
+        StringBuffer input = new StringBuffer();
+        int c = -1;
+        boolean eol = false;
 
-               while (!eol) {
-                       switch( c = read() ) {
-                               case -1:
-                               case '\n':
-                                       eol = true;
-                                       break;
-                               case '\r':
-                                       eol = true;
-                                       long cur = fp;
-                                       if( read() != '\n' ) {
-                                               fp = cur;
-                                       }
-                                       break;
-                               default:
-                                       input.append( (char)c );
-                                       break;
-                       }
-               }
+        while (!eol) {
+            switch( c = read() ) {
+                case -1:
+                case '\n':
+                    eol = true;
+                    break;
+                case '\r':
+                    eol = true;
+                    long cur = fp;
+                    if( read() != '\n' ) {
+                        fp = cur;
+                    }
+                    break;
+                default:
+                    input.append( (char)c );
+                    break;
+            }
+        }
 
-               if ((c == -1) && (input.length() == 0)) {
-                       return null;
-               }
+        if ((c == -1) && (input.length() == 0)) {
+            return null;
+        }
 
-               return input.toString();
-       }
+        return input.toString();
+    }
 
-       public final String readUTF() throws SmbException {
-               int size = readUnsignedShort();
-               byte[] b = new byte[size];
-               read( b, 0, size );
-               try {
-                       return Encdec.dec_utf8( b, 0, size );
-               } catch( IOException ioe ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, ioe.getMessage() );
-               }
-       }
-       public final void writeBoolean( boolean v ) throws SmbException {
-               tmp[0] = (byte)(v ? 1 : 0);
-               write( tmp, 0, 1 );
-       }
-       public final void writeByte( int v ) throws SmbException {
-               tmp[0] = (byte)v;
-               write( tmp, 0, 1 );
-       }
-       public final void writeShort( int v ) throws SmbException {
-               Encdec.enc_uint16be( (short)v, tmp, 0 );
-               write( tmp, 0, 2 );
-       }
-       public final void writeChar( int v ) throws SmbException {
-               Encdec.enc_uint16be( (short)v, tmp, 0 );
-               write( tmp, 0, 2 );
-       }
-       public final void writeInt( int v ) throws SmbException {
-               Encdec.enc_uint32be( v, tmp, 0 );
-               write( tmp, 0, 4 );
-       }
-       public final void writeLong( long v ) throws SmbException {
-               Encdec.enc_uint64be( v, tmp, 0 );
-               write( tmp, 0, 8 );
-       }
-       public final void writeFloat( float v ) throws SmbException {
-               Encdec.enc_floatbe( v, tmp, 0 );
-               write( tmp, 0, 4 );
-       }
-       public final void writeDouble( double v ) throws SmbException {
-               Encdec.enc_doublebe( v, tmp, 0 );
-               write( tmp, 0, 8 );
-       }
-       public final void writeBytes( String s ) throws SmbException {
-               int len = s.length();
-               byte[] b = new byte[len];
-               s.getBytes( 0, len, b, 0 );
-               write( b, 0, len );
-       }
-       public final void writeChars( String s ) throws SmbException {
-               int clen = s.length();
-               int blen = 2 * clen;
-               byte[] b = new byte[blen];
-               char[] c = new char[clen];
-               s.getChars( 0, clen, c, 0 );
-               for( int i = 0, j = 0; i < clen; i++ ) {
-                       b[j++] = (byte)(c[i] >>> 8);
-                       b[j++] = (byte)(c[i] >>> 0);
-               }
-               write( b, 0, blen );
-       }
-       public final void writeUTF( String str ) throws SmbException {
-               int len = str.length();
-               int ch, size = 0;
-               byte[] dst;
+    public final String readUTF() throws SmbException {
+        int size = readUnsignedShort();
+        byte[] b = new byte[size];
+        read( b, 0, size );
+        try {
+            return Encdec.dec_utf8( b, 0, size );
+        } catch( IOException ioe ) {
+            throw new SmbException( "", ioe );
+        }
+    }
+    public final void writeBoolean( boolean v ) throws SmbException {
+        tmp[0] = (byte)(v ? 1 : 0);
+        write( tmp, 0, 1 );
+    }
+    public final void writeByte( int v ) throws SmbException {
+        tmp[0] = (byte)v;
+        write( tmp, 0, 1 );
+    }
+    public final void writeShort( int v ) throws SmbException {
+        Encdec.enc_uint16be( (short)v, tmp, 0 );
+        write( tmp, 0, 2 );
+    }
+    public final void writeChar( int v ) throws SmbException {
+        Encdec.enc_uint16be( (short)v, tmp, 0 );
+        write( tmp, 0, 2 );
+    }
+    public final void writeInt( int v ) throws SmbException {
+        Encdec.enc_uint32be( v, tmp, 0 );
+        write( tmp, 0, 4 );
+    }
+    public final void writeLong( long v ) throws SmbException {
+        Encdec.enc_uint64be( v, tmp, 0 );
+        write( tmp, 0, 8 );
+    }
+    public final void writeFloat( float v ) throws SmbException {
+        Encdec.enc_floatbe( v, tmp, 0 );
+        write( tmp, 0, 4 );
+    }
+    public final void writeDouble( double v ) throws SmbException {
+        Encdec.enc_doublebe( v, tmp, 0 );
+        write( tmp, 0, 8 );
+    }
+    public final void writeBytes( String s ) throws SmbException {
+        byte[] b = s.getBytes();
+        write( b, 0, b.length );
+    }
+    public final void writeChars( String s ) throws SmbException {
+        int clen = s.length();
+        int blen = 2 * clen;
+        byte[] b = new byte[blen];
+        char[] c = new char[clen];
+        s.getChars( 0, clen, c, 0 );
+        for( int i = 0, j = 0; i < clen; i++ ) {
+            b[j++] = (byte)(c[i] >>> 8);
+            b[j++] = (byte)(c[i] >>> 0);
+        }
+        write( b, 0, blen );
+    }
+    public final void writeUTF( String str ) throws SmbException {
+        int len = str.length();
+        int ch, size = 0;
+        byte[] dst;
 
-               for( int i = 0; i < len; i++ ) {
-                       ch = str.charAt( i );
-                       size += ch > 0x07F ? (ch > 0x7FF ? 3 : 2) : 1;
-               }
-               dst = new byte[size];
-               writeShort( size );
-               try {
-                       Encdec.enc_utf8( str, dst, 0, size );
-               } catch( IOException ioe ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, ioe.getMessage() );
-               }
-               write( dst, 0, size );
-       }
+        for( int i = 0; i < len; i++ ) {
+            ch = str.charAt( i );
+            size += ch > 0x07F ? (ch > 0x7FF ? 3 : 2) : 1;
+        }
+        dst = new byte[size];
+        writeShort( size );
+        try {
+            Encdec.enc_utf8( str, dst, 0, size );
+        } catch( IOException ioe ) {
+            throw new SmbException( "", ioe );
+        }
+        write( dst, 0, size );
+    }
 }
 
index a14a8dc..91e6548 100644 (file)
@@ -22,6 +22,7 @@ import java.util.Vector;
 import java.util.Enumeration;
 import java.net.InetAddress;
 import java.net.UnknownHostException;
+import jcifs.Config;
 import jcifs.UniAddress;
 
 /**
@@ -33,15 +34,31 @@ import jcifs.UniAddress;
  * procedure. Instead, it simply performs a "tree connect" to IPC$ using
  * the supplied credentials. This is only a subset of the NETLOGON procedure
  * but is achives the same effect.
+
+Note that it is possible to change the resource against which clients
+are authenticated to be something other than <tt>IPC$</tt> using the
+<tt>jcifs.smb.client.logonShare</tt> property. This can be used to
+provide simple group based access control. For example, one could setup
+the NTLM HTTP Filter with the <tt>jcifs.smb.client.domainController</tt>
+init parameter set to the name of the server used for authentication. On
+that host, create a share called JCIFSAUTH and adjust the access control
+list for that share to permit only the clients that should have access to
+the target website. Finally, set the <tt>jcifs.smb.client.logonShare</tt>
+to JCIFSAUTH. This should restrict access to only those clients that have
+access to the JCIFSAUTH share. The access control on that share can be
+changed without changing init parameters or reinitializing the webapp.
  */
 
 public final class SmbSession {
 
-       public static byte[] getChallenge( UniAddress dc ) throws SmbException, UnknownHostException {
-               SmbTransport trans = SmbTransport.getSmbTransport( dc, 0 );
-               trans.negotiate();
-               return trans.server.encryptionKey;
-       }
+    private static final String LOGON_SHARE = Config.getProperty( "jcifs.smb.client.logonShare", "IPC$" );
+
+    public static byte[] getChallenge( UniAddress dc )
+                throws SmbException, UnknownHostException {
+        SmbTransport trans = SmbTransport.getSmbTransport( dc, 0 );
+        trans.negotiate();
+        return trans.server.encryptionKey;
+    }
 /**
  * Authenticate arbitrary credentials represented by the
  * <tt>NtlmPasswordAuthentication</tt> object against the domain controller
@@ -50,134 +67,161 @@ public final class SmbSession {
  * occurs an <tt>SmbException</tt> will be thrown. If the credentials are
  * valid, the method will return without throwing an exception. See the
  * last <a href="../../../../FAQ.html">FAQ</a> question.
+ *
+ * See also the <tt>jcifs.smb.client.logonShare</tt> property.
  */
-       public static void logon( UniAddress dc,
-                                               NtlmPasswordAuthentication auth ) throws SmbException {
-               SmbTransport.getSmbTransport( dc, 0 ).getSmbSession( auth ).getSmbTree( "IPC$", null ).treeConnect( null, null );
-       }
-
-       int uid;
-       NtlmPasswordAuthentication auth;
-       SmbTransport transport;
-       Vector trees;
-       boolean sessionSetup;
-
-       SmbSession( SmbTransport transport, NtlmPasswordAuthentication auth ) {
-               this.transport = transport;
-               this.auth = auth;
-               trees = new Vector();
-       }
-
-       synchronized SmbTree getSmbTree( String share, String service ) {
-               SmbTree t;
-
-               if( share == null ) {
-                       share = "IPC$";
-               }
-               for( Enumeration e = trees.elements(); e.hasMoreElements(); ) {
-                       t = (SmbTree)e.nextElement();
-                       if( t.matches( share, service )) {
-                               return t;
-                       }
-               }
-               t = new SmbTree( this, share, service );
-               trees.addElement( t );
-               return t;
-       }
-       boolean matches( NtlmPasswordAuthentication auth ) {
-               return this.auth == auth || this.auth.equals( auth );
-       }
-       void sendTransaction( SmbComTransaction request,
-                                                       SmbComTransactionResponse response ) throws SmbException {
-               // transactions are not batchable
-               sessionSetup( null, null );
-               request.uid = uid;
-               request.auth = auth;
-               transport.sendTransaction( request, response );
-       }
-       void send( ServerMessageBlock request,
-                                                       ServerMessageBlock response ) throws SmbException {
-               if( response != null ) {
-                       response.received = false;
-               }
-               sessionSetup( request, response );
-               if( response != null && response.received ) {
-                       return;
-               }
-               request.uid = uid;
-               request.auth = auth;
-               transport.send( request, response );
-       }
-       void sessionSetup( ServerMessageBlock andx,
-                                                       ServerMessageBlock andxResponse ) throws SmbException {
-synchronized( transport ) {
-               if( sessionSetup ) {
-                       return;
-               }
-
-               transport.negotiate();
-
-               if( transport.useSigning && transport.macSigningKey == null &&
-                               NtlmPasswordAuthentication.NULL != auth &&
-                               NtlmPasswordAuthentication.NULL.equals( auth ) == false ) {
-                       //      NtlmPasswordAuthentication.GUEST.equals( auth ) == false ) {
-                    /* The first SMB_COM_SESSION_SETUP_ANX with creds other than
-                     * null or guest generates the signing key */
-                       transport.initSigning( auth );
-               }
-
-               Log.println( Log.WARNINGS, "smb session setup warning",
-                                       " requesting session with accountName=" + auth.username +
-                                       ",primaryDomain=" + auth.domain );
-
-               /*
-                * Session Setup And X Request / Response
-                */
-
-               SmbComSessionSetupAndX request = new SmbComSessionSetupAndX( this, andx );
-               SmbComSessionSetupAndXResponse response = new SmbComSessionSetupAndXResponse( andxResponse );
-               request.auth = auth;
-               transport.send( request, response );
-
-               uid = response.uid;
-               sessionSetup = true;
+    public static void logon( UniAddress dc,
+                        NtlmPasswordAuthentication auth ) throws SmbException {
+        SmbTransport.getSmbTransport( dc, 0 ).getSmbSession( auth ).getSmbTree( LOGON_SHARE, null ).treeConnect( null, null );
+    }
+
+    private int uid;
+    private Vector trees;
+    private boolean sessionSetup;
+    // Transport parameters allows trans to be removed from CONNECTIONS
+    private UniAddress address;
+    private int port, localPort;
+    private InetAddress localAddr;
+
+    SmbTransport transport = SmbTransport.NULL_TRANSPORT;
+    NtlmPasswordAuthentication auth;
+
+    SmbSession( UniAddress address, int port,
+                InetAddress localAddr, int localPort,
+                NtlmPasswordAuthentication auth ) {
+        this.address = address;
+        this.port = port;
+        this.localAddr = localAddr;
+        this.localPort = localPort;
+        this.auth = auth;
+        trees = new Vector();
+    }
+
+    synchronized SmbTree getSmbTree( String share, String service ) {
+        SmbTree t;
+
+        if( share == null ) {
+            share = "IPC$";
+        }
+        for( Enumeration e = trees.elements(); e.hasMoreElements(); ) {
+            t = (SmbTree)e.nextElement();
+            if( t.matches( share, service )) {
+                return t;
+            }
+        }
+        t = new SmbTree( this, share, service );
+        trees.addElement( t );
+        return t;
+    }
+    boolean matches( NtlmPasswordAuthentication auth ) {
+        return this.auth == auth || this.auth.equals( auth );
+    }
+    synchronized SmbTransport transport() throws SmbException {
+        if( transport == SmbTransport.NULL_TRANSPORT ) {
+            transport = SmbTransport.getSmbTransport( address, port, localAddr, localPort );
+        }
+        return transport;
+    }
+    void sendTransaction( SmbComTransaction request,
+                            SmbComTransactionResponse response ) throws SmbException {
+        // transactions are not batchable
+        sessionSetup( null, null );
+        request.uid = uid;
+        request.auth = auth;
+        transport().sendTransaction( request, response );
+    }
+    void send( ServerMessageBlock request,
+                            ServerMessageBlock response ) throws SmbException {
+        if( response != null ) {
+            response.received = false;
+        }
+        sessionSetup( request, response );
+        if( response != null && response.received ) {
+            return;
+        }
+        request.uid = uid;
+        request.auth = auth;
+        transport().send( request, response );
+    }
+    void sessionSetup( ServerMessageBlock andx,
+                            ServerMessageBlock andxResponse ) throws SmbException {
+synchronized( transport() ) {
+        if( sessionSetup ) {
+            return;
+        }
+
+        transport.negotiate();
+
+        /* Create SMB signature digest if necessary
+         */
+
+        if(( transport.flags2 & ServerMessageBlock.FLAGS2_SECURITY_SIGNATURES ) != 0 &&
+                (transport.dig == null || transport.dig.sessionSetup == false) &&
+                                         /* Only the first SMB_COM_SESSION_SETUP_ANX
+                                          * with creds other than NULL initializes
+                                          * signing */
+                auth != NtlmPasswordAuthentication.NULL &&
+                NtlmPasswordAuthentication.NULL.equals( auth ) == false ) {
+            transport.dig = new SigningDigest( transport, auth );
+        }
+
+        /*
+         * Session Setup And X Request / Response
+         */
+
+        if( transport.log.level > 2 )
+            transport.log.println( "sessionSetup: accountName=" + auth.username + ",primaryDomain=" + auth.domain );
+
+        SmbComSessionSetupAndX request = new SmbComSessionSetupAndX( this, andx );
+        SmbComSessionSetupAndXResponse response = new SmbComSessionSetupAndXResponse( andxResponse );
+        request.auth = auth;
+        transport.send( request, response );
+
+        uid = response.uid;
+        sessionSetup = true;
+        if( transport.dig != null )
+            transport.dig.sessionSetup = true;
 }
-       }
-       void logoff( boolean inError ) {
+    }
+    void logoff( boolean inError ) {
 synchronized( transport ) {
-               if( sessionSetup == false ) {
-                       return;
-               }
-
-               for( Enumeration e = trees.elements(); e.hasMoreElements(); ) {
-                       SmbTree t = (SmbTree)e.nextElement();
-                       t.treeDisconnect( inError );
-               }
-
-               if( transport.server.security == ServerMessageBlock.SECURITY_SHARE ) {
-                       return;
-               }
-
-               if( !inError ) {
-
-                       /*
-                        * Logoff And X Request / Response
-                        */
-
-                       try {
-                               SmbComLogoffAndX request = new SmbComLogoffAndX( null );
-                               request.uid = uid;
-                               transport.send( request, null );
-                       } catch( SmbException se ) {
-                       }
-               }
-               sessionSetup = false;
+        try {
+            if( sessionSetup == false ) {
+                return;
+            }
+
+            for( Enumeration e = trees.elements(); e.hasMoreElements(); ) {
+                SmbTree t = (SmbTree)e.nextElement();
+                t.treeDisconnect( inError );
+            }
+
+            if( transport.server.security == ServerMessageBlock.SECURITY_SHARE ) {
+                return;
+            }
+
+            if( !inError ) {
+
+                /*
+                 * Logoff And X Request / Response
+                 */
+
+                SmbComLogoffAndX request = new SmbComLogoffAndX( null );
+                request.uid = uid;
+                try {
+                    transport.send( request, null );
+                } catch( SmbException se ) {
+                }
+            }
+            sessionSetup = false;
+        } finally {
+            transport = SmbTransport.NULL_TRANSPORT;
+        }
 }
-       }
-       public String toString() {
-               return "SmbSession[accountName=" + auth.username +
-                               ",primaryDomain=" + auth.domain +
-                               ",uid=" + uid +
-                               ",sessionSetup=" + sessionSetup + "]";
-       }
+    }
+    public String toString() {
+        return "SmbSession[accountName=" + auth.username +
+                ",primaryDomain=" + auth.domain +
+                ",uid=" + uid +
+                ",sessionSetup=" + sessionSetup + "]";
+    }
 }
index 6e64a5c..35f5f59 100644 (file)
@@ -1,6 +1,6 @@
 /* jcifs smb client library in Java
  * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
- *                                     "Eric Glass" <jcifs at samba dot org>
+ *                  "Eric Glass" <jcifs at samba dot org>
  * 
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
@@ -36,1086 +36,908 @@ import java.net.UnknownHostException;
 import java.security.MessageDigest;
 
 import java.util.Arrays;
-import java.util.Vector;
 import java.util.LinkedList;
 import java.util.ListIterator;
 import java.util.Enumeration;
-import java.util.Hashtable;
+import java.util.HashMap;
 
-class SmbTransport implements Runnable {
-
-       private static final byte[] LMV2_CROSSDOMAIN_KEY = new byte[16];
-
-       private static final int DEFAULT_MAX_MPX_COUNT = 10;
-       private static final int DEFAULT_RESPONSE_TIMEOUT = 10000;
-       private static final int DEFAULT_SO_TIMEOUT     = 15000;
-       private static final int PUSHBACK_BUF_SIZE       = 64;
-       private static final int DEFAULT_RCV_BUF_SIZE  = 60416;
-       private static final int DEFAULT_SND_BUF_SIZE  = 5000;
-       private static final int DEFAULT_SSN_LIMIT       = 250;
-
-       private static final int LM_COMPATIBILITY =
-                       Config.getInt("jcifs.smb.lmCompatibility", 0);
-
-       static final int MID_OFFSET       = 30;
-       static final int HEADER_LENGTH   = 32;
-       static final int FLAGS_OFFSET   = 9;
-       static final int FLAGS_RESPONSE  = 0x80;
-
-       static final int ST_GROUND = 0;
-       static final int ST_NEGOTIATING = 1;
-
-       private NbtSocket socket; // should become UniSocket?
-       private InputStream in;
-       private OutputStream out;
-       private int localPort, soTimeout, responseTimeout;
-       private long closeTime;
-       private InetAddress localAddr;
-       private Hashtable responseTable;
-       private Thread thread;
-       private Object outLock;
+import jcifs.util.LogStream;
+import jcifs.util.Hexdump;
 
-       private MessageDigest signingDigest;
+class SmbTransport implements Runnable {
 
-       private static Vector connections = new Vector();
-       private static MpxControl mpxCtrl = new MpxControl();
+    private static final int DEFAULT_MAX_MPX_COUNT = 10;
+    private static final int DEFAULT_RESPONSE_TIMEOUT = 10000;
+    private static final int DEFAULT_SO_TIMEOUT = 15000;
+    private static final int DEFAULT_RCV_BUF_SIZE = 60416;
+    private static final int DEFAULT_SND_BUF_SIZE = 5000;
+    private static final int DEFAULT_SSN_LIMIT = 250;
+
+    private static final InetAddress LADDR = Config.getInetAddress( "jcifs.smb.client.laddr", null );
+    private static final int LPORT = Config.getInt( "jcifs.smb.client.lport", 0 );
+    private static final int SSN_LIMIT = Config.getInt( "jcifs.smb.client.ssnLimit", DEFAULT_SSN_LIMIT );
+    private static final int MAX_MPX_COUNT = Config.getInt( "jcifs.smb.client.maxMpxCount", DEFAULT_MAX_MPX_COUNT );
+    private static final int SND_BUF_SIZE = Config.getInt( "jcifs.smb.client.snd_buf_size", DEFAULT_SND_BUF_SIZE );
+    private static final int RCV_BUF_SIZE = Config.getInt( "jcifs.smb.client.rcv_buf_size", DEFAULT_RCV_BUF_SIZE );
+    private static final boolean USE_UNICODE = Config.getBoolean( "jcifs.smb.client.useUnicode", true );
+    private static final boolean FORCE_UNICODE = Config.getBoolean( "jcifs.smb.client.useUnicode", false );
+    private static final boolean USE_NTSTATUS = Config.getBoolean( "jcifs.smb.client.useNtStatus", true );
+    private static final boolean SIGNPREF = Config.getBoolean("jcifs.smb.client.signingPreferred", false );
+    private static final boolean USE_NTSMBS = Config.getBoolean( "jcifs.smb.client.useNTSmbs", true );
+    private static final int DEFAULT_FLAGS2 =
+                ServerMessageBlock.FLAGS2_LONG_FILENAMES |
+                ServerMessageBlock.FLAGS2_EXTENDED_ATTRIBUTES |
+                ( SIGNPREF ? ServerMessageBlock.FLAGS2_SECURITY_SIGNATURES : 0 ) |
+                ( USE_NTSTATUS ? ServerMessageBlock.FLAGS2_STATUS32 : 0 ) |
+                ( USE_UNICODE ? ServerMessageBlock.FLAGS2_UNICODE : 0 );
+    private static final int DEFAULT_CAPABILITIES =
+                ( USE_NTSMBS ? ServerMessageBlock.CAP_NT_SMBS : 0 ) |
+                ( USE_NTSTATUS ? ServerMessageBlock.CAP_STATUS32 : 0 ) |
+                ( USE_UNICODE ? ServerMessageBlock.CAP_UNICODE : 0 ) |
+                ServerMessageBlock.CAP_DFS;
+    private static final int FLAGS2 = Config.getInt( "jcifs.smb.client.flags2", DEFAULT_FLAGS2 );
+    private static final int CAPABILITIES = Config.getInt( "jcifs.smb.client.capabilities", DEFAULT_CAPABILITIES );
+    private static final int SO_TIMEOUT = Config.getInt( "jcifs.smb.client.soTimeout", DEFAULT_SO_TIMEOUT );
+    private static final boolean TCP_NODELAY = Config.getBoolean( "jcifs.smb.client.tcpNoDelay", false );
+    private static final int RESPONSE_TIMEOUT =
+                Config.getInt( "jcifs.smb.client.responseTimeout", DEFAULT_RESPONSE_TIMEOUT );
+
+    private static final int PUSHBACK_BUF_SIZE = 64;
+    private static final int MID_OFFSET = 30;
+    private static final int FLAGS_RESPONSE = 0x80;
+    private static final int ST_GROUND = 0;
+    private static final int ST_NEGOTIATING = 1;
+    private static final LinkedList CONNECTIONS = new LinkedList();
+    private static final int MAGIC[] = { 0xFF, 'S', 'M', 'B' };
 
 private static byte[] snd_buf = new byte[0xFFFF];
 private static byte[] rcv_buf = new byte[0xFFFF];
 
-       LinkedList sessions;
-       boolean negotiated, useUnicode, useSigning;
-
-       UniAddress address;
-
-       byte[] macSigningKey;
-       int signSequence;
-
-       int port, rcv_buf_size, snd_buf_size;
-
-       int negotiatedDialectIndex;
-       int negotiatedMaxMpxCount;
-       int negotiatedMaxBufferSize;
-       int negotiatedCapabilities;
-
-       int ssnLimit = Config.getInt( "jcifs.smb.client.ssnLimit", DEFAULT_SSN_LIMIT );
-
-       int state;
-
-       ClientProperties client = new ClientProperties();
-       ServerProperties server = new ServerProperties();
-
-       LinkedList referrals = new LinkedList();
-
-       class ClientProperties {
-               int maxMpxCount = Config.getInt( "jcifs.smb.client.maxMpxCount",
-                                                                                                       DEFAULT_MAX_MPX_COUNT );
-               int maxBufferSize = Config.getInt( "jcifs.smb.client.snd_buf_size",
-                                                                                                       DEFAULT_SND_BUF_SIZE );
-               int sessionKey = 0x00000000;
-               /* NT 4 Workstation client capabilities 0x00D4
-                * we don't do NT Status Codes or Level II oplocks
-                * but we could do raw and mpx
-                */
-               int flags2 = Config.getInt( "jcifs.smb.client.flags2",
-                               ServerMessageBlock.FLAGS2_LONG_FILENAMES |
-                               ServerMessageBlock.FLAGS2_EXTENDED_ATTRIBUTES |
-                               ServerMessageBlock.FLAGS2_UNICODE );
-               int capabilities = Config.getInt( "jcifs.smb.client.capabilities",
-                               ServerMessageBlock.CAP_UNICODE |
-                               ServerMessageBlock.CAP_NT_SMBS);
-               String nativeOs = Config.getProperty( "jcifs.smb.client.nativeOs",
-                               System.getProperty( "os.name" ));
-               String nativeLanMan = Config.getProperty( "jcifs.smb.client.nativeLanMan", "jCIFS" );
-               int vcNumber = 1;
-       }
-       class ServerProperties {
-               String tconHostName;
-
-               byte flags;
-               int flags2;
-               int maxMpxCount;
-               int maxBufferSize;
-               int sessionKey;
-               // NT 4 Workstation is 0x43FD
-               int capabilities;
-               String oemDomainName;
-               String primaryDomain;
-               String nativeOs;
-               String nativeLanMan;
-
-               int securityMode;
-               int security;
-               boolean encryptedPasswords;
-               boolean signaturesEnabled;
-               boolean signaturesRequired;
-               int maxNumberVcs;
-               int maxRawSize;
-               long serverTime;
-               int serverTimeZone;
-               int encryptionKeyLength;
-               byte[] encryptionKey;
-       }
-
-       static synchronized SmbTransport getSmbTransport( UniAddress address, int port ) {
-               return getSmbTransport( address, port,
-                                                       Config.getInetAddress( "jcifs.smb.client.laddr", null ),
-                                                       Config.getInt( "jcifs.smb.client.lport", 0 ));
-       }
-       static synchronized SmbTransport getSmbTransport( UniAddress address, int port,
-                                                                       InetAddress localAddr, int localPort ) {
-               SmbTransport conn;
-               for( Enumeration e = connections.elements(); e.hasMoreElements(); ) {
-                       conn = (SmbTransport)e.nextElement();
-                       if( conn.matches( address, port, localAddr, localPort )) {
-                               return conn;
-                       }
-               }
-
-               conn = new SmbTransport( address, port, localAddr, localPort );
-               connections.addElement( conn );
-               return conn;
-       }
-
-       SmbTransport( UniAddress address, int port, InetAddress localAddr, int localPort ) {
-               this.address = address;
-               this.port = port;
-               this.localAddr = localAddr;
-               this.localPort = localPort;
-
-               useUnicode = Config.getBoolean( "jcifs.smb.client.useUnicode", true );
-               if( useUnicode == false ) {
-                       client.flags2 &= 0xFFFF ^ ServerMessageBlock.FLAGS2_UNICODE;
-                       client.capabilities &= 0xFFFF ^ ServerMessageBlock.CAP_UNICODE;
-               }
-               if( Config.getBoolean( "jcifs.smb.client.useNTSmbs", true ) == false ) {
-                       client.capabilities &= ~ServerMessageBlock.CAP_NT_SMBS;
-               }
-               useSigning = Config.getBoolean("jcifs.smb.client.signingPreferred", false);
-               if( useSigning ) {
-                       client.flags2 |= ServerMessageBlock.FLAGS2_SECURITY_SIGNATURES;
-               }
-
-               soTimeout = Config.getInt( "jcifs.smb.client.soTimeout", DEFAULT_SO_TIMEOUT );
-               responseTimeout = Config.getInt( "jcifs.smb.client.responseTimeout", DEFAULT_RESPONSE_TIMEOUT );
-               rcv_buf_size = Config.getInt( "jcifs.smb.client.rcv_buf_size", DEFAULT_RCV_BUF_SIZE );
-               snd_buf_size = client.maxBufferSize;
-               sessions = new LinkedList();
-               responseTable = new Hashtable();
-               outLock = new Object();
-               state = ST_GROUND;
-       }
-
-       synchronized SmbSession getSmbSession() {
-               return getSmbSession( new NtlmPasswordAuthentication( null, null, null ));
-       }
-       synchronized SmbSession getSmbSession( NtlmPasswordAuthentication auth ) {
-               SmbSession ssn;
-
-               ListIterator iter = sessions.listIterator();
-               while( iter.hasNext() ) {
-                       ssn = (SmbSession)iter.next();
-                       if( ssn.matches( auth )) {
-                               ssn.auth = auth;
-                               return ssn;
-                       }
-               }
-               ssn = new SmbSession( this, auth );
-               sessions.add( ssn );
-
-               if( sessions.size() > ssnLimit ) {
-                       int nclose = sessions.size() / 10;
-                       SmbSession s;
-
-                       while( nclose-- > 0 ) {
-                               s = (SmbSession)sessions.removeFirst();
-                               s.logoff( false );
-                       }
-               }
-
-               return ssn;
-       }
-       boolean matches( UniAddress address, int port, InetAddress localAddr, int localPort ) {
-               InetAddress defaultLocal = null;
-               try {
-                       defaultLocal = InetAddress.getLocalHost();
-               } catch( UnknownHostException uhe ) {
-               }
-               int p1 = ( port == 0 || port == 139 ) ? 0 : port;
-               int p2 = ( this.port == 0 || this.port == 139 ) ? 0 : this.port;
-               InetAddress la1 = localAddr == null ? defaultLocal : localAddr;
-               InetAddress la2 = this.localAddr == null ? defaultLocal : this.localAddr;
-               return address.equals( this.address ) &&
-                                       p1 == p2 &&
-                                       la1.equals( la2 ) &&
-                                       localPort == this.localPort;
-       }
-       boolean hasCapability( int cap ) throws SmbException {
-               if (state == ST_GROUND) {
-                       negotiate();
-               }
-               return (negotiatedCapabilities & cap) == cap;
-       }
-       void ensureOpen() throws IOException {
-               if( socket == null ) {
-                       Object obj;
-                       NbtAddress naddr;
-                       String calledName;
-
-                       /* Hack to convert InetAddress to NbtAddress until we properly
-                        * abstract NetBIOSless transport with some kind of "UniSocket".
-                        */
-                       obj = address.getAddress();
-                       if( obj instanceof NbtAddress ) {
-                               naddr = (NbtAddress)obj;
-                       } else {
-                               try {
-                                       naddr = NbtAddress.getByName( ((InetAddress)obj).getHostAddress() );
-                               } catch( UnknownHostException uhe ) {
-                                       naddr = null; // never happen
-                               }
-                       }
-
-                       calledName = address.firstCalledName();
-                       do {
-                               try {
-                                       socket = new NbtSocket( naddr, calledName, port, localAddr, localPort );
-                                       break;
-                               } catch( NbtException ne ) {
-                                       if( ne.errorClass == NbtException.ERR_SSN_SRVC &&
-                                                               ( ne.errorCode == NbtException.CALLED_NOT_PRESENT ||
-                                                               ne.errorCode == NbtException.NOT_LISTENING_CALLED )) {
-                                               Log.println( Log.WARNINGS, "smb warning", ne.getMessage() );
-                                       } else {
-                                               throw ne;
-                                       }
-                               }
-                       } while(( calledName = address.nextCalledName()) != null );
-
-                       if( calledName == null ) {
-                               throw new IOException( "Failed to establish session with " + address );
-                       }
-
-                       /* Save the calledName for using on SMB_COM_TREE_CONNECT
-                        */
-                       if( calledName == NbtAddress.SMBSERVER_NAME ) {
-                               server.tconHostName = address.getHostAddress();
-                       } else {
-                               server.tconHostName = calledName;
-                       }
-
-                       if( Config.getBoolean( "jcifs.smb.client.tcpNoDelay", false )) {
-                               socket.setTcpNoDelay( true );
-                       }
-                       in = new PushbackInputStream( socket.getInputStream(), PUSHBACK_BUF_SIZE );
-                       out = socket.getOutputStream();
-                       thread = new Thread( this, "JCIFS-SmbTransport" );
-                       thread.setDaemon( true );
-                       thread.start();
-               }
-       }
-       void tryClose( boolean inError ) {
-               SmbSession ssn;
-
-               if( socket == null ) {
-                       inError = true;
-               }
-
-               ListIterator iter = sessions.listIterator();
-               while( iter.hasNext() ) {
-                       ssn = (SmbSession)iter.next();
-                       ssn.logoff( inError );
-               }
-               if( socket != null ) {
-                       try {
-                               socket.close();
-                       } catch( IOException ioe ) {
-                       }
-               }
-               in = null;
-               out = null;
-               socket = null;
-               thread = null;
-               responseTable.clear();
-               state = ST_GROUND;
-       }
-       public void run() {
-               int mid, l, i, n, m;
-               ServerMessageBlock response;
-               int magic[] = { 0xFF, 'S', 'M', 'B' };
-
-               while( thread == Thread.currentThread() ) {
-                       try {
-                               socket.setSoTimeout( soTimeout );
-
-                               m = 0;
-                               while( m < 4 ) {
-                                       if(( i = in.read() ) < 0 ) {
-                                               return;
-                                       }
-                                       if(( i & 0xFF ) == magic[m] ) {
-                                               m++;
-                                       } else if(( i & 0xFF ) == 0xFF ) {
-                                               m = 1;
-                                       } else {
-                                               m = 0;
-                                       }
-                               }
+    private NbtSocket socket;
+    private HashMap responseTable;
+    private InputStream in;
+    private OutputStream out;
+    private int localPort;
+    private InetAddress localAddr;
+    private Thread thread;
+    private Object outLock;
+    private UniAddress address;
+    private int port;
+    private LinkedList sessions;
+    private LinkedList referrals = new LinkedList();
+    private int state;
+    private Mid[] mids = new Mid[MAX_MPX_COUNT];
+    private short mid_next;
+
+    static final String NATIVE_OS =
+            Config.getProperty( "jcifs.smb.client.nativeOs", System.getProperty( "os.name" ));
+    static final String NATIVE_LANMAN =
+            Config.getProperty( "jcifs.smb.client.nativeLanMan", "jCIFS" );
+    static final int VC_NUMBER = 1;
+    static LogStream log = LogStream.getInstance();
+    static final SmbTransport NULL_TRANSPORT = new SmbTransport();
+
+    class Mid {
+        short mid;
+
+        public int hashCode() {
+            return mid;
+        }
+        public boolean equals( Object obj ) {
+            return ((Mid)obj).mid == mid;
+        }
+    }
+    class ServerData {
+        byte flags;
+        int flags2;
+        int maxMpxCount;
+        int maxBufferSize;
+        int sessionKey;
+        // NT 4 Workstation is 0x43FD
+        int capabilities;
+        String oemDomainName;
+        int securityMode;
+        int security;
+        boolean encryptedPasswords;
+        boolean signaturesEnabled;
+        boolean signaturesRequired;
+        int maxNumberVcs;
+        int maxRawSize;
+        long serverTime;
+        int serverTimeZone;
+        int encryptionKeyLength;
+        byte[] encryptionKey;
+    }
+
+    int flags2 = FLAGS2;
+    int maxMpxCount = MAX_MPX_COUNT;
+    int snd_buf_size = SND_BUF_SIZE;
+    int rcv_buf_size = RCV_BUF_SIZE;
+    int capabilities = CAPABILITIES;
+    int sessionKey = 0x00000000;
+    boolean useUnicode = USE_UNICODE;
+    String tconHostName;
+    ServerData server;
+    SigningDigest dig;
+
+    static synchronized SmbTransport getSmbTransport( UniAddress address, int port ) {
+        return getSmbTransport( address, port, LADDR, LPORT );
+    }
+    static synchronized SmbTransport getSmbTransport( UniAddress address, int port,
+                                    InetAddress localAddr, int localPort ) {
+        SmbTransport conn;
+
+        synchronized( CONNECTIONS ) {
+            if( SSN_LIMIT != 1 ) {
+                ListIterator iter = CONNECTIONS.listIterator();
+                while( iter.hasNext() ) {
+                    conn = (SmbTransport)iter.next();
+                    if( conn.matches( address, port, localAddr, localPort ) &&
+                            ( SSN_LIMIT == 0 || conn.sessions.size() < SSN_LIMIT )) {
+                        return conn;
+                    }
+                }
+            }
+
+            conn = new SmbTransport( address, port, localAddr, localPort );
+            CONNECTIONS.add( 0, conn );
+        }
+
+        return conn;
+    }
+
+    SmbTransport( UniAddress address, int port, InetAddress localAddr, int localPort ) {
+        this.address = address;
+        this.port = port;
+        this.localAddr = localAddr;
+        this.localPort = localPort;
+
+        sessions = new LinkedList();
+        responseTable = new HashMap();
+        outLock = new Object();
+        state = ST_GROUND;
+
+        int i;
+        for( i = 0; i < MAX_MPX_COUNT; i++ ) {
+            mids[i] = new Mid();
+        }
+    }
+    SmbTransport() {
+    }
+
+    synchronized SmbSession getSmbSession() {
+        return getSmbSession( new NtlmPasswordAuthentication( null, null, null ));
+    }
+    synchronized SmbSession getSmbSession( NtlmPasswordAuthentication auth ) {
+        SmbSession ssn;
+
+        ListIterator iter = sessions.listIterator();
+        while( iter.hasNext() ) {
+            ssn = (SmbSession)iter.next();
+            if( ssn.matches( auth )) {
+                ssn.auth = auth;
+                return ssn;
+            }
+        }
+        ssn = new SmbSession( address, port, localAddr, localPort, auth );
+        ssn.transport = this;
+        sessions.add( ssn );
+
+        return ssn;
+    }
+    boolean matches( UniAddress address, int port, InetAddress localAddr, int localPort ) {
+        InetAddress defaultLocal = null;
+        try {
+            defaultLocal = InetAddress.getLocalHost();
+        } catch( UnknownHostException uhe ) {
+        }
+        int p1 = ( port == 0 || port == 139 ) ? 0 : port;
+        int p2 = ( this.port == 0 || this.port == 139 ) ? 0 : this.port;
+        InetAddress la1 = localAddr == null ? defaultLocal : localAddr;
+        InetAddress la2 = this.localAddr == null ? defaultLocal : this.localAddr;
+        return address.equals( this.address ) &&
+                    p1 == p2 &&
+                    la1.equals( la2 ) &&
+                    localPort == this.localPort;
+    }
+    boolean hasCapability( int cap ) throws SmbException {
+        if (state == ST_GROUND) {
+            negotiate();
+        }
+        return (capabilities & cap) == cap;
+    }
+    void ensureOpen() throws IOException {
+        if( socket == null ) {
+            Object obj;
+            NbtAddress naddr;
+            String calledName;
+
+            obj = address.getAddress();
+            if( obj instanceof NbtAddress ) {
+                naddr = (NbtAddress)obj;
+            } else {
+                try {
+                    naddr = NbtAddress.getByName( ((InetAddress)obj).getHostAddress() );
+                } catch( UnknownHostException uhe ) {
+                    naddr = null; // never happen
+                }
+            }
+
+            calledName = address.firstCalledName();
+            do {
+                try {
+                    socket = new NbtSocket( naddr, calledName, port, localAddr, localPort );
+                    break;
+                } catch( NbtException ne ) {
+                    if( ne.errorClass == NbtException.ERR_SSN_SRVC &&
+                                ( ne.errorCode == NbtException.CALLED_NOT_PRESENT ||
+                                ne.errorCode == NbtException.NOT_LISTENING_CALLED )) {
+                        if( log.level > 2 )
+                            ne.printStackTrace( log );
+                    } else {
+                        throw ne;
+                    }
+                }
+            } while(( calledName = address.nextCalledName()) != null );
+
+            if( calledName == null ) {
+                throw new IOException( "Failed to establish session with " + address );
+            }
+
+            /* Save the calledName for using on SMB_COM_TREE_CONNECT
+             */
+            if( calledName == NbtAddress.SMBSERVER_NAME ) {
+                tconHostName = address.getHostAddress();
+            } else {
+                tconHostName = calledName;
+            }
+
+            if( TCP_NODELAY ) {
+                socket.setTcpNoDelay( true );
+            }
+            in = new PushbackInputStream( socket.getInputStream(), PUSHBACK_BUF_SIZE );
+            out = socket.getOutputStream();
+            thread = new Thread( this, "JCIFS-SmbTransport" );
+            thread.setDaemon( true );
+            thread.start();
+        }
+    }
+    void tryClose( boolean inError ) {
+        SmbSession ssn;
+
+        if( socket == null ) {
+            inError = true;
+        }
+
+        ListIterator iter = sessions.listIterator();
+        while( iter.hasNext() ) {
+            ssn = (SmbSession)iter.next();
+            ssn.logoff( inError );
+        }
+        if( socket != null ) {
+            try {
+                socket.close();
+            } catch( IOException ioe ) {
+            }
+        }
+        dig = null;
+        in = null;
+        out = null;
+        socket = null;
+        thread = null;
+        responseTable.clear();
+        referrals.clear();
+        sessions.clear();
+        synchronized( CONNECTIONS ) {
+            CONNECTIONS.remove( this );
+        }
+        state = ST_GROUND;
+    }
+    public void run() {
+        Mid mid = new Mid();
+        int i, m, nbtlen;
+        ServerMessageBlock response;
+
+        while( thread == Thread.currentThread() ) {
+            try {
+                socket.setSoTimeout( SO_TIMEOUT );
+
+                m = 0;
+                while( m < 4 ) {
+                    if(( i = in.read() ) < 0 ) {
+                        return;
+                    }
+                    if(( i & 0xFF ) == MAGIC[m] ) {
+                        m++;
+                    } else if(( i & 0xFF ) == 0xFF ) {
+                        m = 1;
+                    } else {
+                        m = 0;
+                    }
+                }
+
+                nbtlen = 4 + in.available();
 
 synchronized( rcv_buf ) {
-                               rcv_buf[0] = (byte)0xFF;
-                               rcv_buf[1] = (byte)'S';
-                               rcv_buf[2] = (byte)'M';
-                               rcv_buf[3] = (byte)'B';
-
-                               if( in.read( rcv_buf, 4, HEADER_LENGTH - 4 ) != ( HEADER_LENGTH - 4 )) {
-                                       /* Read on a netbios SocketInputStream does not
-                                        * return until len bytes have been read or the stream is
-                                        * closed. This must be the latter case.
-                                        */
-                                       break;
-                               }
-                               ((PushbackInputStream)in).unread( rcv_buf, 0, HEADER_LENGTH );
-                               if( rcv_buf[0] != (byte)0xFF ||
-                                                               rcv_buf[1] != (byte)'S' ||
-                                                               rcv_buf[2] != (byte)'M' ||
-                                                               rcv_buf[3] != (byte)'B' ) {
-                                       Log.println( Log.WARNINGS, "smb warning",
-                                                                                               "bad smb header, purging session message" );
-                                       in.skip( in.available() );
-                                       continue;
-                               }
-                               if(( rcv_buf[FLAGS_OFFSET] & FLAGS_RESPONSE ) == FLAGS_RESPONSE ) {
-                                       mid = ServerMessageBlock.readInt2( rcv_buf, MID_OFFSET );
-
-                                       response = (ServerMessageBlock)responseTable.get( new Integer( mid ));
-                                       if( response == null ) {
-                                               Log.println( Log.WARNINGS, "smb warning",
-                                                               " no handler for mid=" + mid + ", purging session message" );
-                                               in.skip( in.available() );
-                                               continue;
-                                       }
-                                       synchronized( response ) {
-                                               response.useUnicode = useUnicode;
-                                               Log.println( Log.DEBUGGING, "smb transport warning",
-                                                                                                               " new data read from socket" );
-
-                                               if( response instanceof SmbComTransactionResponse ) {
-                                                       Enumeration e = (Enumeration)response;
-                                                       if( e.hasMoreElements() ) {
-                                                               e.nextElement();
-                                                       } else {
-                                                               Log.println( Log.WARNINGS, "smb warning",
-                                                                                       "more responses to transaction than expected" );
-                                                               continue;
-                                                       }
-                                                       response.readWireFormat( in, rcv_buf, 0 );
-                                                       response.received = true;
-                                                       Log.printMessageData( "smb received", response );
-
-                                                       if( response.errorCode != 0 || e.hasMoreElements() == false ) {
-                                                               ((SmbComTransactionResponse)response).hasMore = false;
-                                                               if( useSigning ) {
-                                                                       response.verifyFailed = verify(rcv_buf, 0, response);
-                                                               }
-                                                               response.notify();
-                                                       } else {
-                                                               ensureOpen();
-                                                       }
-                                               } else {
-                                                       response.readWireFormat( in, rcv_buf, 0 );
-                                                       response.received = true;
-
-                                                       Log.printMessageData( "smb received", response );
-                                                       ServerMessageBlock smb = response;
-                                                       while( smb instanceof AndXServerMessageBlock &&
-                                                                       ( smb = ((AndXServerMessageBlock)smb).andx ) != null ) {
-                                                               Log.printMessageData( "smb andx data", smb );
-                                                       }
-                                                       Log.printHexDump( "smb received", rcv_buf, 0, response.length );
-                                                       if( useSigning ) {
-                                                               response.verifyFailed = verify(rcv_buf, 0, response);
-                                                       }
-
-                                                       response.notify();
-                                               }
-                                       }
-                               } else {
-                                       // it's a request(break oplock)
-                               }
+                rcv_buf[0] = (byte)0xFF;
+                rcv_buf[1] = (byte)'S';
+                rcv_buf[2] = (byte)'M';
+                rcv_buf[3] = (byte)'B';
+
+                if( in.read( rcv_buf, 4, ServerMessageBlock.HEADER_LENGTH - 4 ) !=
+                                    ( ServerMessageBlock.HEADER_LENGTH - 4 )) {
+                    /* Read on a netbios SocketInputStream does not
+                     * return until len bytes have been read or the stream is
+                     * closed. This must be the latter case.
+                     */
+                    break;
+                }
+                ((PushbackInputStream)in).unread( rcv_buf, 0, ServerMessageBlock.HEADER_LENGTH );
+                if( rcv_buf[0] != (byte)0xFF ||
+                                rcv_buf[1] != (byte)'S' ||
+                                rcv_buf[2] != (byte)'M' ||
+                                rcv_buf[3] != (byte)'B' ) {
+                    if( log.level > 1 )
+                        log.println( "bad smb header, purging session message: " + address );
+                    in.skip( in.available() );
+                    continue;
+                }
+                if(( rcv_buf[ServerMessageBlock.FLAGS_OFFSET] &
+                            ServerMessageBlock.FLAGS_RESPONSE ) ==
+                            ServerMessageBlock.FLAGS_RESPONSE ) {
+                    mid.mid = (short)(ServerMessageBlock.readInt2( rcv_buf, MID_OFFSET ) & 0xFFFF);
+
+                    response = (ServerMessageBlock)responseTable.get( mid );
+                    if( response == null ) {
+                        if( log.level > 1 ) {
+                            log.println( "no handler for mid=" + mid.mid +
+                                    ", purging session message: " + address );
+                        }
+                        in.skip( in.available() );
+                        continue;
+                    }
+                    synchronized( response ) {
+                        response.useUnicode = useUnicode;
+
+                        if( log.level > 2 )
+                            log.println( "new data read from socket: " + address );
+
+                        if( response instanceof SmbComTransactionResponse ) {
+                            Enumeration e = (Enumeration)response;
+                            if( e.hasMoreElements() ) {
+                                e.nextElement();
+                            } else {
+                                if( log.level > 2 )
+                                    log.println( "more responses to transaction than expected" );
+                                continue;
+                            }
+                            if((m = response.readWireFormat( in, rcv_buf, 0 )) != nbtlen ) {
+                                if( log.level > 1 ) {
+                                    log.println( "decoded " + m + " but nbtlen=" +
+                                            nbtlen + ", purging session message" );
+                                }
+                                in.skip( in.available() );
+                            }
+                            response.received = true;
+
+                            if( log.level > 2 )
+                                log.println( response );
+
+                            if( response.errorCode != 0 || e.hasMoreElements() == false ) {
+                                ((SmbComTransactionResponse)response).hasMore = false;
+                                if( dig != null ) {
+                                    synchronized( outLock ) {
+                                        dig.verify(rcv_buf, 0, response);
+                                    }
+                                }
+                                response.notify();
+                            } else {
+                                ensureOpen();
+                            }
+                        } else {
+                            response.readWireFormat( in, rcv_buf, 0 );
+                            response.received = true;
+
+                            if( log.level > 2 ) {
+                                ServerMessageBlock smb = response;
+
+                                do {
+                                    log.println( smb );
+                                } while( smb instanceof AndXServerMessageBlock &&
+                                            ( smb = ((AndXServerMessageBlock)smb).andx ) != null );
+                                if( log.level > 5 ) {
+                                    Hexdump.hexdump( log, rcv_buf, 0, Math.min( response.length, 1024 ));
+                                }
+                            }
+
+                            if( dig != null && (response.errorCode == 0 || response.command != ServerMessageBlock.SMB_COM_SESSION_SETUP_ANDX )) {
+                                synchronized( outLock ) {
+                                    dig.verify(rcv_buf, 0, response);
+                                }
+                            }
+
+                            response.notify();
+                        }
+                    }
+                } else {
+                    // it's a request(break oplock)
+                }
 }
-                       } catch( InterruptedIOException iioe ) {
-                               if( responseTable.size() == 0 ) {
-                                       tryClose( false );
-                               } else {
-                                       Log.println( Log.WARNINGS, "smb warning",
-                                                               " soTimeout has occured but there are " +
-                                                               responseTable.size() + " pending requests" );
-                               }
-                       } catch( IOException ioe ) {
-                               synchronized( this ) {
-                                       tryClose( true );
-                               }
-                               if( ioe.getMessage().startsWith( "Connection reset" ) == false ) {
-                                       Log.printStackTrace( "exception reading from socket input: " + address, ioe );
-                               }
-                       }
-               }
-       }
-
-       void initSigning(NtlmPasswordAuthentication auth) throws SmbException {
-               if( auth.hashesExternal ) {
-                       useSigning = false;
-                       return;
-               }
-
-               signSequence = 0;
-
-               switch (LM_COMPATIBILITY) {
-               case 0:
-               case 1:
-               case 2:
-                       macSigningKey = new byte[40];
-                       try {
-                               auth.getUserSessionKey(server.encryptionKey, macSigningKey, 0);
-                               System.arraycopy(auth.getUnicodeHash(server.encryptionKey),
-                                               0, macSigningKey, 16, 24);
-                       } catch (Exception ex) {
-                               Log.printStackTrace("Unable to calculate MAC signing key.", ex);
-                               macSigningKey = null;
-                       }
-                       break;
-               case 3:
-               case 4:
-               case 5:
-                       macSigningKey = new byte[16];
-                       try {
-                               auth.getUserSessionKey(server.encryptionKey, macSigningKey, 0);
-                       } catch (Exception ex) {
-                               Log.printStackTrace("Unable to calculate MAC signing key.", ex);
-                               macSigningKey = null;
-                       }
-                       break;
-               default:
-                       macSigningKey = new byte[40];
-                       try {
-                               auth.getUserSessionKey(server.encryptionKey, macSigningKey, 0);
-                               System.arraycopy(auth.getUnicodeHash(server.encryptionKey),
-                                               0, macSigningKey, 16, 24);
-                       } catch (Exception ex) {
-                               Log.printStackTrace("Unable to calculate MAC signing key.", ex);
-                               macSigningKey = null;
-                       }
-                       break;
-               }
-       }
-
-       /**
-        * Performs MAC signing of the SMB.  This is done as follows.
-        * The signature field of the SMB is overwritted with the sequence number;
-        * The MD5 digest of the MAC signing key + the entire SMB is taken;
-        * The first 8 bytes of this are placed in the signature field.
-        *
-        * @param data The data.
-        * @param offset The starting offset at which the SMB header begins.
-        * @param length The length of the SMB data starting at offset. 
-        */
-       private void sign(byte[] data, int offset, int length) {
-               if (macSigningKey == null) return;
-               try {
-                       signingDigest.update(macSigningKey);
-                       int index = offset + ServerMessageBlock.SIGNATURE_OFFSET;
-                       for (int i = 0; i < 8; i++) data[index + i] = 0;
-                       ServerMessageBlock.writeInt4(signSequence, data, index);
-                       signingDigest.update(data, offset, length);
-                       System.arraycopy(signingDigest.digest(), 0, data, index, 8);
-               } catch (Exception ex) {
-                       Log.printStackTrace("Error signing SMB.", ex);
-               } finally {
-                       signSequence += 2;
-               }
-       } 
-
-       /**
-        * Performs MAC signature verification.  This calculates the signature
-        * of the SMB and compares it to the signature field on the SMB itself.
-        *
-        * @param data The data.
-        * @param offset The starting offset at which the SMB header begins.
-        * @param length The length of the SMB data starting at offset. 
-        */
-       private boolean verify(byte[] data, int offset, ServerMessageBlock response) throws IOException {
-               if (macSigningKey == null) return false;
-               signingDigest.update(macSigningKey);
-               int index = offset;
-               signingDigest.update(data, index, ServerMessageBlock.SIGNATURE_OFFSET); 
-               index += ServerMessageBlock.SIGNATURE_OFFSET;
-               byte[] sequence = new byte[8]; 
-               ServerMessageBlock.writeInt4(response.verifySequence, sequence, 0); 
-               signingDigest.update(sequence); 
-               index += 8;
-               if( response.command == ServerMessageBlock.SMB_COM_READ_ANDX ) {
-                       /* SmbComReadAndXResponse reads directly from the stream into separate byte[] b.
-                        */
-                       SmbComReadAndXResponse raxr = (SmbComReadAndXResponse)response;
-                       int length = response.length - raxr.dataLength;
-                       signingDigest.update(data, index, length - ServerMessageBlock.SIGNATURE_OFFSET - 8);
-                       signingDigest.update(raxr.b, raxr.off, raxr.dataLength);
-               } else {
-                       signingDigest.update(data, index, response.length - ServerMessageBlock.SIGNATURE_OFFSET - 8);
-               }
-               byte[] signature = signingDigest.digest();
-               for (int i = 0; i < 8; i++) {
-                       if (signature[i] != data[offset + ServerMessageBlock.SIGNATURE_OFFSET + i]) {
-                                                                                       // can this just use == ?
-                               if (Arrays.equals(LMV2_CROSSDOMAIN_KEY, macSigningKey)) return true;
-                               signingDigest.update(LMV2_CROSSDOMAIN_KEY);
-                               index = offset;
-                               signingDigest.update(data, index, ServerMessageBlock.SIGNATURE_OFFSET);
-                               index += ServerMessageBlock.SIGNATURE_OFFSET;
-                               ServerMessageBlock.writeInt4(response.verifySequence, sequence, 0);
-                               signingDigest.update(sequence);
-                               index += 8;
-                               signingDigest.update(data, index, response.length - ServerMessageBlock.SIGNATURE_OFFSET - 8);
-                               signature = signingDigest.digest();
-                               for (i = 0; i < 8; i++) {
-                                       if (signature[i] != data[offset + ServerMessageBlock.SIGNATURE_OFFSET + i]) {
-                                               return true;
-                                       }
-                               }
-                               // verified using LMv2 cross-domain MAC key; start using that.
-                               macSigningKey = LMV2_CROSSDOMAIN_KEY;
-                               break;
-                       }
-               }
-
-               return false;
-       }
-       synchronized DfsReferral getDfsReferral( NtlmPasswordAuthentication auth, String path ) throws SmbException {
-               String subpath, node, host;
-               DfsReferral dr = new DfsReferral();
-               int p, n, i, s;
-               UniAddress addr;
-
-               SmbTree ipc = getSmbSession( auth ).getSmbTree( "IPC$", null );
-               Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();
-               ipc.sendTransaction( new Trans2GetDfsReferral( path ), resp );
-
-               subpath = path.substring( 0, resp.pathConsumed );
-               node = resp.referral.node;
-               if( subpath.charAt( 0 ) != '\\' ||
-                               (i = subpath.indexOf( '\\', 1 )) < 2 ||
-                               (p = subpath.indexOf( '\\', i + 1 )) < (i + 2) ||
-                               node.charAt( 0 ) != '\\' ||
-                               (s = node.indexOf( '\\', 1 )) < 2) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRdfs, "Invalid DFS path: " + path );
-               }
-               if ((n = node.indexOf( '\\', s + 1 )) == -1) {
-                       n = node.length();
-               }
-
-               dr.path = subpath.substring( p );
-               dr.node = node.substring( 0, n );
-               dr.nodepath = node.substring( n );
-               dr.server = node.substring( 1, s );
-               dr.share = node.substring( s, n );
-               dr.resolveHashes = auth.hashesExternal; /* NTLM HTTP Authentication must be re-negotiated
-                                                  * with challenge from 'server' to access DFS vol. */
-               return dr;
-       }
-       synchronized DfsReferral lookupReferral( String unc ) {
-               DfsReferral dr;
-               ListIterator iter = referrals.listIterator();
-               int i, len;
-
-               while( iter.hasNext() ) {
-                       dr = (DfsReferral)iter.next();
-                       len = dr.path.length();
-                       for( i = 0; i < len && i < unc.length(); i++ ) {
-                               if( dr.path.charAt( i ) != unc.charAt( i )) {
-                                       break;
-                               }
-                       }
-                       if( i == len ) {
-                               return dr;
-                       }
-               }
-
-               return null;
-       }
-       void send( ServerMessageBlock request,
-                                                       ServerMessageBlock response ) throws SmbException {
-               Integer mid = null;
-
-               if (state == ST_GROUND) {
-                       negotiate();
-               }
-
-               request.flags2 |= client.flags2;
-               request.mid = aquireMid();
-               request.useUnicode = useUnicode;
-
-               if( response == null ) {
-                       try {
-                               synchronized( outLock ) {
-                                       ensureOpen();
+            } catch( InterruptedIOException iioe ) {
+                if( responseTable.size() == 0 ) {
+                    tryClose( false );
+                } else if( log.level > 1 ) {
+                    log.println( "soTimeout has occured but there are " +
+                            responseTable.size() + " pending requests" );
+                }
+            } catch( IOException ioe ) {
+                synchronized( this ) {
+                    tryClose( true );
+                }
+                if( log.level > 0 &&
+                            ioe.getMessage().startsWith( "Connection reset" ) == false ) {
+                    log.println( ioe.getMessage() + ": " + address );
+                    ioe.printStackTrace( log );
+                }
+            }
+        }
+    }
+
+    synchronized DfsReferral getDfsReferral( NtlmPasswordAuthentication auth, String path ) throws SmbException {
+        String subpath, node, host;
+        DfsReferral dr = new DfsReferral();
+        int p, n, i, s;
+        UniAddress addr;
+
+        SmbTree ipc = getSmbSession( auth ).getSmbTree( "IPC$", null );
+        Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();
+        ipc.sendTransaction( new Trans2GetDfsReferral( path ), resp );
+
+        subpath = path.substring( 0, resp.pathConsumed );
+        node = resp.referral.node;
+        if( subpath.charAt( 0 ) != '\\' ||
+                (i = subpath.indexOf( '\\', 1 )) < 2 ||
+                (p = subpath.indexOf( '\\', i + 1 )) < (i + 2) ||
+                node.charAt( 0 ) != '\\' ||
+                (s = node.indexOf( '\\', 1 )) < 2) {
+            throw new SmbException( "Invalid DFS path: " + path );
+        }
+        if ((n = node.indexOf( '\\', s + 1 )) == -1) {
+            n = node.length();
+        }
+
+        dr.path = subpath.substring( p );
+        dr.node = node.substring( 0, n );
+        dr.nodepath = node.substring( n );
+        dr.server = node.substring( 1, s );
+        dr.share = node.substring( s + 1, n );
+        dr.resolveHashes = auth.hashesExternal;
+                        /* NTLM HTTP Authentication must be re-negotiated
+                         * with challenge from 'server' to access DFS vol. */
+        return dr;
+    }
+    synchronized DfsReferral lookupReferral( String unc ) {
+        DfsReferral dr;
+        ListIterator iter = referrals.listIterator();
+        int i, len;
+
+        while( iter.hasNext() ) {
+            dr = (DfsReferral)iter.next();
+            len = dr.path.length();
+            for( i = 0; i < len && i < unc.length(); i++ ) {
+                if( dr.path.charAt( i ) != unc.charAt( i )) {
+                    break;
+                }
+            }
+            if( i == len && (len == unc.length() || unc.charAt( len ) == '\\')) {
+                return dr;
+            }
+        }
+
+        return null;
+    }
+    void send( ServerMessageBlock request,
+                            ServerMessageBlock response ) throws SmbException {
+        Mid mid = null;
+
+        if (state == ST_GROUND) {
+            negotiate();
+        }
+
+        request.flags2 |= flags2;
+        request.useUnicode = useUnicode;
+
+        if( response == null ) {
+            try {
+                synchronized( outLock ) {
+                    mid = aquireMid();
+                    request.mid = mid.mid;
+                    ensureOpen();
 synchronized( snd_buf ) {
-                                       int length = request.writeWireFormat(snd_buf, 0);
-                                       if( useSigning ) {
-                                               sign(snd_buf, 0, length);
-                                       }
-                                       out.write(snd_buf, 0, length);
-                                       out.flush();
-
-                                       Log.printMessageData( "smb sent", request );
-                                       ServerMessageBlock smb = request;
-                                       while( smb instanceof AndXServerMessageBlock &&
-                                                                       ( smb = ((AndXServerMessageBlock)smb).andx ) != null ) {
-                                               Log.printMessageData( "smb andx data", smb );
-                                       }
-                                       Log.printHexDump( "smb sent", snd_buf, 0, request.length );
+                    int length = request.writeWireFormat(snd_buf, 4);
+                    if( dig != null ) {
+                        dig.sign(snd_buf, 4, length, request, null );
+                    }
+                    out.write(snd_buf, 4, length);
+                    out.flush();
+
+                    if( log.level > 2 ) {
+                        ServerMessageBlock smb = request;
+
+                        do {
+                            log.println( smb );
+                        } while( smb instanceof AndXServerMessageBlock &&
+                                ( smb = ((AndXServerMessageBlock)smb).andx ) != null );
+                        if( log.level > 5 ) {
+                            Hexdump.hexdump( log, snd_buf, 0, Math.min( request.length, 1024 ));
+                        }
+                    }
 }
-                               }
-                       } catch( IOException ioe ) {
-                               tryClose( true );
-                               throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, ioe.getMessage() );
-                       } finally {
-                               releaseMid( request.mid );
-                       }
-
-                       return;
-               }
-
-               // now for the normal case where response is not null
-
-               try {
-                       synchronized( response ) {
-
-                               response.received = false;
-                               mid = new Integer( request.mid );
-                               responseTable.put( mid, response );
-
-                               synchronized( outLock ) {
-                                       ensureOpen();
+                }
+            } catch( IOException ioe ) {
+                tryClose( true );
+                throw new SmbException( "An error occured sending the request.", ioe );
+            } finally {
+                synchronized( outLock ) {
+                    releaseMid( mid );
+                }
+            }
+
+            return;
+        }
+
+        // now for the normal case where response is not null
+
+        try {
+            synchronized( response ) {
+                synchronized( outLock ) {
+                    response.received = false;
+                    mid = aquireMid();
+                    request.mid = mid.mid;
+                    responseTable.put( mid, response );
+                    ensureOpen();
 synchronized( snd_buf ) {
-                                       int length = request.writeWireFormat(snd_buf, 0);
-                                       if( useSigning ) {
-                                               response.verifySequence = signSequence + 1;
-                                               sign(snd_buf, 0, length);
-                                       }
-                                       out.write(snd_buf, 0, length);
-                                       out.flush();
-//Log.printHexDump( System.err, Thread.currentThread().getName() + ": " + request.toString(), snd_buf, 0, Math.min( length, 63 ));
-
-                                       Log.printMessageData( "smb sent", request );
-                                       ServerMessageBlock smb = request;
-                                       while( smb instanceof AndXServerMessageBlock &&
-                                                                       ( smb = ((AndXServerMessageBlock)smb).andx ) != null ) {
-                                               Log.printMessageData( "smb andx data", smb );
-                                       }
-                                       Log.printHexDump( "smb sent", snd_buf, 0, request.length );
+                    int length = request.writeWireFormat(snd_buf, 4);
+                    if( dig != null ) {
+                        dig.sign( snd_buf, 4, length, request, response );
+                    }
+                    out.write(snd_buf, 4, length);
+                    out.flush();
+
+                    if( log.level > 2 ) {
+                        ServerMessageBlock smb = request;
+
+                        do {
+                            log.println( smb );
+                        } while( smb instanceof AndXServerMessageBlock &&
+                                ( smb = ((AndXServerMessageBlock)smb).andx ) != null );
+                        if( log.level > 5 ) {
+                            Hexdump.hexdump( log, snd_buf, 0, request.length );
+                        }
+                    }
 }
-                               }
-
-                               // default it 1 so that 0 can be used as forever
-                               response.wait( response.responseTimeout == 1 ?
-                                                                                               responseTimeout : response.responseTimeout );
-                       }
-               } catch( InterruptedException ie ) {
-                       tryClose( true );
-               } catch( IOException ioe ) {
-                       tryClose( true );
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, ioe.getMessage() );
-               } finally {
-                       responseTable.remove( mid );
-                       releaseMid( request.mid );
-               }
-
-               if( response.received == false ) {
-                       tryClose( true );
-                       throw new SmbException( SmbException.ERRCLI,
-                                                                       SmbException.ERRserverTimeout,
-                                                                       address );
-               } else if( response.verifyFailed ) {
-                       tryClose( true );
-                       throw new SmbException( SmbException.ERRCLI,
-                                                                       SmbException.ERRioe,
-                                                                       "Unverifiable signature." );
-               }
-               switch( response.errorCode & 0xFF ) {
-                       case SmbException.SUCCESS:
-                               break;
-                       case SmbException.ERRDOS:
-                               switch(( response.errorCode >> 16 ) & 0xFFFF ) {
-                                       case SmbException.ERRnoaccess:
-                                               throw new SmbAuthException( response.errorCode );
-                               }
-                               throw new SmbException( response.errorCode );
-                       case SmbException.ERRSRV:
-                               switch(( response.errorCode >> 16 ) & 0xFFFF ) {
-                                       case SmbException.ERRreserved:
-                                               if( request.auth == null ) {
-                                                       throw new SmbException( response.errorCode );
-                                               }
-                                               DfsReferral dr = getDfsReferral( request.auth, request.path );
-                                               referrals.add( dr );
-                                               throw dr;
-                                       case SmbException.ERRbadpw:
-                                       case SmbException.ERRaccess:
-                                       case SmbException.ERRaccountExpired:
-                                       case SmbException.ERRbadClient:
-                                       case SmbException.ERRbadLogonTime:
-                                       case SmbException.ERRpasswordExpired:
-                                               throw new SmbAuthException( response.errorCode );
-                               }
-                       default:
-                               throw new SmbException( response.errorCode );
-               }
-
-       }
-       void sendTransaction( SmbComTransaction request,
-                                                       SmbComTransactionResponse response ) throws SmbException {
-               Integer mid = null;
-
-               negotiate();
-
-               request.flags2 |= client.flags2;
-               request.mid = aquireMid();
-               mid = new Integer( request.mid );
-               request.useUnicode = useUnicode;
-               request.maxBufferSize = negotiatedMaxBufferSize;
-               response.received = false;
-               response.hasMore = true;
-               response.isPrimary = true;
-
-               try {
-                       request.txn_buf = BufferCache.getBuffer();
-                       response.txn_buf = BufferCache.getBuffer();
-
-                       request.nextElement();
-                       if( request.hasMoreElements() ) {
-                               // multi-part request
-
-                               SmbComBlankResponse interimResponse = new SmbComBlankResponse();
-
-                               synchronized( interimResponse ) {
-
-                                       responseTable.put( mid, interimResponse );
-
-                                       synchronized( outLock ) {
-                                               ensureOpen();
+                }
+
+                // default it 1 so that 0 can be used as forever
+                response.wait( response.responseTimeout == 1 ? RESPONSE_TIMEOUT : response.responseTimeout );
+            }
+        } catch( InterruptedException ie ) {
+            tryClose( true );
+        } catch( IOException ioe ) {
+            tryClose( true );
+            throw new SmbException( "An error occured sending the request.", ioe );
+        } finally {
+            synchronized( outLock ) {
+                responseTable.remove( mid );
+                releaseMid( mid );
+            }
+        }
+
+        if( response.received == false ) {
+            tryClose( true );
+            throw new SmbException( "Timeout waiting for response from server: " + address );
+        } else if( response.verifyFailed ) {
+            tryClose( true );
+            throw new SmbException( "Unverifiable signature: " + address );
+        }
+        response.errorCode = SmbException.getStatusByCode( response.errorCode );
+        switch( response.errorCode ) {
+            case NtStatus.NT_STATUS_OK:
+                break;
+            case NtStatus.NT_STATUS_ACCESS_DENIED:
+            case NtStatus.NT_STATUS_WRONG_PASSWORD:
+            case NtStatus.NT_STATUS_LOGON_FAILURE:
+            case NtStatus.NT_STATUS_ACCOUNT_RESTRICTION:
+            case NtStatus.NT_STATUS_INVALID_LOGON_HOURS:
+            case NtStatus.NT_STATUS_INVALID_WORKSTATION:
+            case NtStatus.NT_STATUS_PASSWORD_EXPIRED:
+            case NtStatus.NT_STATUS_ACCOUNT_DISABLED:
+                throw new SmbAuthException( response.errorCode );
+            case NtStatus.NT_STATUS_PATH_NOT_COVERED:
+                if( request.auth == null ) {
+                    throw new SmbException( response.errorCode, null );
+                }
+                DfsReferral dr = getDfsReferral( request.auth, request.path );
+                referrals.add( dr );
+                throw dr;
+            default:
+                throw new SmbException( response.errorCode, null );
+        }
+    }
+    void sendTransaction( SmbComTransaction request,
+                            SmbComTransactionResponse response ) throws SmbException {
+        Mid mid = null;
+
+        negotiate();
+
+        request.flags2 |= flags2;
+        request.useUnicode = useUnicode;
+        request.maxBufferSize = snd_buf_size;
+        response.received = false;
+        response.hasMore = true;
+        response.isPrimary = true;
+
+        try {
+            request.txn_buf = BufferCache.getBuffer();
+            response.txn_buf = BufferCache.getBuffer();
+
+            request.nextElement();
+            if( request.hasMoreElements() ) {
+                // multi-part request
+
+                SmbComBlankResponse interimResponse = new SmbComBlankResponse();
+
+                synchronized( interimResponse ) {
+                    synchronized( outLock ) {
+                        mid = aquireMid();
+                        request.mid = mid.mid;
+                        responseTable.put( mid, interimResponse );
+                        ensureOpen();
 synchronized(snd_buf) {
-                                               int length = request.writeWireFormat(snd_buf, 0);
-                                               if( useSigning ) {
-                                                       response.verifySequence = signSequence + 1;
-                                                       sign(snd_buf, 0, length);
-                                               }
-                                               out.write(snd_buf, 0, length);
-                                               out.flush();
-
-                                               Log.printMessageData( "smb sent", request );
-                                               Log.printHexDump( "smb sent", snd_buf, 0, request.length );
+                        int length = request.writeWireFormat(snd_buf, 4);
+                        if( dig != null ) {
+                            dig.sign(snd_buf, 4, length, request, response);
+                        }
+                        out.write(snd_buf, 4, length);
+                        out.flush();
+
+                        if( log.level > 2 ) {
+                            log.println( request );
+                            if( log.level > 5 ) {
+                                Hexdump.hexdump( log, snd_buf, 0, request.length );
+                            }
+                        }
 }
-                                       }
-
-                                       interimResponse.wait( responseTimeout );
-
-                                       if( interimResponse.received == false ) {
-                                               throw new SmbException( SmbException.ERRserverTimeout );
-                                       }
-                                       switch( interimResponse.errorCode & 0xFF ) {
-                                               case SmbException.SUCCESS:
-                                                       break;
-                                               case SmbException.ERRDOS:
-                                                       switch(( response.errorCode >> 16 ) & 0xFFFF ) {
-                                                               case SmbException.ERRnoaccess:
-                                                                       throw new SmbAuthException( response.errorCode );
-                                                       }
-                                                       throw new SmbException( response.errorCode );
-                                               case SmbException.ERRSRV:
-                                                       switch(( interimResponse.errorCode >> 16 ) & 0xFFFF ) {
-                                                               case SmbException.ERRreserved:
-                                                                       if( request.auth == null ) {
-                                                                               throw new SmbException( response.errorCode );
-                                                                       }
-                                                                       DfsReferral dr = getDfsReferral( request.auth, request.path );
-                                                                       referrals.add( dr );
-                                                                       throw dr;
-                                                               case SmbException.ERRbadpw:
-                                                               case SmbException.ERRaccess:
-                                                               case SmbException.ERRaccountExpired:
-                                                               case SmbException.ERRbadClient:
-                                                               case SmbException.ERRbadLogonTime:
-                                                               case SmbException.ERRpasswordExpired:
-                                                                       throw new SmbAuthException( interimResponse.errorCode );
-                                                       }
-                                               default:
-                                                       throw new SmbException( interimResponse.errorCode );
-                                       }
-                               }
-                               request.nextElement();
-                       }
-
-                       synchronized( response ) {
-                               responseTable.put( mid, response );
-                               do {
-                                       synchronized( outLock ) {
-                                               ensureOpen();
+                    }
+
+                    interimResponse.wait( RESPONSE_TIMEOUT );
+
+                    if( interimResponse.received == false ) {
+                        throw new SmbException( "Timeout waiting for response from server: " + address );
+                    }
+                    interimResponse.errorCode = SmbException.getStatusByCode( interimResponse.errorCode );
+                    switch( interimResponse.errorCode ) {
+                        case NtStatus.NT_STATUS_OK:
+                            break;
+                        case NtStatus.NT_STATUS_ACCESS_DENIED:
+                        case NtStatus.NT_STATUS_WRONG_PASSWORD:
+                        case NtStatus.NT_STATUS_LOGON_FAILURE:
+                        case NtStatus.NT_STATUS_ACCOUNT_RESTRICTION:
+                        case NtStatus.NT_STATUS_INVALID_LOGON_HOURS:
+                        case NtStatus.NT_STATUS_INVALID_WORKSTATION:
+                        case NtStatus.NT_STATUS_PASSWORD_EXPIRED:
+                        case NtStatus.NT_STATUS_ACCOUNT_DISABLED:
+                            throw new SmbAuthException( interimResponse.errorCode );
+                        case NtStatus.NT_STATUS_PATH_NOT_COVERED:
+                            if( request.auth == null ) {
+                                throw new SmbException( interimResponse.errorCode, null );
+                            }
+                            DfsReferral dr = getDfsReferral( request.auth, request.path );
+                            referrals.add( dr );
+                            throw dr;
+                        default:
+                            throw new SmbException( interimResponse.errorCode, null );
+                    }
+                }
+                request.nextElement();
+            }
+
+            synchronized( response ) {
+                synchronized( outLock ) {
+                    mid = aquireMid();
+                    request.mid = mid.mid;
+                    responseTable.put( mid, response );
+                }
+                do {
+                    synchronized( outLock ) {
+                        ensureOpen();
 synchronized( snd_buf ) {
-                                               int length = request.writeWireFormat(snd_buf, 0);
-                                               if( useSigning ) {
-                                                       response.verifySequence = signSequence + 1;
-                                                       sign(snd_buf, 0, length);
-                                               }
-                                               out.write(snd_buf, 0, length);
-                                               out.flush();
-
-                                               Log.printMessageData( "smb sent", request );
-                                               Log.printHexDump( "smb sent", snd_buf, 0, request.length );
+                        int length = request.writeWireFormat(snd_buf, 4);
+                        if( dig != null ) {
+                            dig.sign(snd_buf, 4, length, request, response);
+                        }
+                        out.write(snd_buf, 4, length);
+                        out.flush();
+
+                        if( log.level > 2 ) {
+                            log.println( request );
+                            if( log.level > 5 ) {
+                                Hexdump.hexdump( log, snd_buf, 0, request.length );
+                            }
+                        }
 }
-                                       }
-                               } while( request.hasMoreElements() && request.nextElement() != null );
-
-                               do {
-                                       // default it 1 so that 0 can be used as forever
-                                       response.received = false;
-                                       response.wait( response.responseTimeout == 1 ? responseTimeout : response.responseTimeout );
-                               } while( response.received && response.hasMoreElements() );
-                       }
-               } catch( InterruptedException ie ) {
-                       tryClose( true );
-               } catch( IOException ioe ) {
-                       tryClose( true );
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, ioe.getMessage() );
-               } finally {
-                       responseTable.remove( mid );
-                       releaseMid( request.mid );
-                       BufferCache.releaseBuffer( request.txn_buf );
-                       BufferCache.releaseBuffer( response.txn_buf );
-               }
-
-               if( response.received == false ) {
-                       tryClose( true );
-                       throw new SmbException( SmbException.ERRCLI,
-                                                                       SmbException.ERRserverTimeout,
-                                                                       address );
-               } else if( response.verifyFailed ) {
-                       tryClose( true );
-                       throw new SmbException( SmbException.ERRCLI,
-                                                                       SmbException.ERRioe,
-                                                                       "Unverifiable signature." );
-               }
-               switch( response.errorCode & 0xFF ) {
-                       case SmbException.SUCCESS:
-                               break;
-                       case SmbException.ERRDOS:
-                               switch(( response.errorCode >> 16 ) & 0xFFFF ) {
-                                       case SmbException.ERRnoaccess:
-                                               throw new SmbAuthException( response.errorCode );
-                               }
-                               throw new SmbException( response.errorCode );
-                       case SmbException.ERRSRV:
-                               switch(( response.errorCode >> 16 ) & 0xFFFF ) {
-                                       case SmbException.ERRreserved:
-                                               if( request.auth == null ) {
-                                                       throw new SmbException( response.errorCode );
-                                               }
-                                               DfsReferral dr = getDfsReferral( request.auth, request.path );
-                                               referrals.add( dr );
-                                               throw dr;
-                                       case SmbException.ERRbadpw:
-                                       case SmbException.ERRaccess:
-                                       case SmbException.ERRaccountExpired:
-                                       case SmbException.ERRbadClient:
-                                       case SmbException.ERRbadLogonTime:
-                                       case SmbException.ERRpasswordExpired:
-                                               throw new SmbAuthException( response.errorCode );
-                               }
-                       default:
-                               throw new SmbException( response.errorCode );
-               }
-       }
-       synchronized void negotiate() throws SmbException {
-
-               if( state >= ST_NEGOTIATING ) {
-                       return;
-               }
-               state = ST_NEGOTIATING;
-
-               Log.println( Log.WARNINGS, "smb negotiation warning",
-                                                       " requesting negotiation with " + address );
-
-               /*
-                * Negotiate Protocol Request / Response
-                */
-
-               // reset MAC signing
-               macSigningKey = null;
-
-               SmbComNegotiateResponse response = new SmbComNegotiateResponse();
-               send( new SmbComNegotiate(), response );
-
-               if( response.dialectIndex > 10 ) {
-                       tryClose( true );
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRbadDialect );
-               }
-
-               server.securityMode             = response.securityMode;
-               server.security                 = response.security;
-               server.encryptedPasswords  = response.encryptedPasswords;
-               server.signaturesEnabled   = response.signaturesEnabled;
-               server.signaturesRequired  = response.signaturesRequired;
-               if (server.signaturesRequired || (server.signaturesEnabled && useSigning)) {
-                       useSigning = true;
-                       client.flags2 |= ServerMessageBlock.FLAGS2_SECURITY_SIGNATURES;
-
-                       if (signingDigest == null) {
-                               try {
-                                       signingDigest = MessageDigest.getInstance("MD5");
-                               } catch (Exception ex) {
-                                       Log.printStackTrace("Unable to obtain MD5 digest.", ex);
-                                       return;
-                               }
-                       }
-               } else {
-                       useSigning = false;
-                       client.flags2 &= 0xFFFF ^ ServerMessageBlock.FLAGS2_SECURITY_SIGNATURES;
-               }
-               negotiatedDialectIndex   = response.dialectIndex;;
-               server.maxMpxCount               = response.maxMpxCount;
-               negotiatedMaxMpxCount     = client.maxMpxCount < server.maxMpxCount ?
-                                                                               client.maxMpxCount : server.maxMpxCount;
-               mpxCtrl.maxMpxCount             = negotiatedMaxMpxCount < 1 ?
-                                                                               1 : negotiatedMaxMpxCount;
-               server.maxNumberVcs             = response.maxNumberVcs;
-               server.maxBufferSize       = response.maxBufferSize;
-               negotiatedMaxBufferSize = client.maxBufferSize < server.maxBufferSize ?
-                                                                               client.maxBufferSize : server.maxBufferSize;
-               server.maxRawSize                 = response.maxRawSize;
-               server.sessionKey                 = response.sessionKey;
-               server.capabilities             = response.capabilities;
-               negotiatedCapabilities   = client.capabilities & server.capabilities;
-               if(( negotiatedCapabilities & ServerMessageBlock.CAP_UNICODE ) == 0 ) {
-                       // server doesn't want unicode
-                       if( Config.getBoolean( "jcifs.smb.client.useUnicode", false )) {
-                               // force unicode
-                               negotiatedCapabilities |= ServerMessageBlock.CAP_UNICODE;
-                       } else {
-                               // not explicitly set to true so flip unicode off as server requests
-                               useUnicode = false;
-                               client.flags2 &= 0xFFFF ^ ServerMessageBlock.FLAGS2_UNICODE;
-                       }
-               }
-               server.serverTime                 = response.serverTime;
-               server.serverTimeZone     = response.serverTimeZone;
-               server.encryptionKeyLength = response.encryptionKeyLength;
-               server.encryptionKey       = response.encryptionKey;
-               server.oemDomainName       = response.oemDomainName;
-       }
-       public String toString() {
-               String ret = "SmbTransport[address=" + address;
-               if( socket == null ) {
-                       ret += ",port=,localAddr=,localPort=]";
-               } else {
-                       ret += ",port=" + socket.getPort() +
-                       ",localAddr=" + socket.getLocalAddress() +
-                       ",localPort=" + socket.getLocalPort() + "]";
-               }
-               return ret;
-       }
-
-       static int aquireMid() throws SmbException {
-               try {
-                       return mpxCtrl.aquireMid();
-               } catch( InterruptedException ie ) {
-                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe, ie.getMessage() );
-               }
-       }
-       static void releaseMid( int mid ) {
-               mpxCtrl.releaseMid( mid );
-       }
-
-       static class MpxControl {
-               MpxListNode first, last;
-               class MpxListNode {
-                       int i;  
-                       MpxListNode next;
-                       MpxListNode( int id ) {
-                               i = id;
-                               next = null;
-                       }
-               }          
-               int nextMid, mpxCount, maxMpxCount;
-
-               MpxControl() {
-                       nextMid = 0;
-                       mpxCount = 0;
-                       maxMpxCount = 1;
-                       first = last = null;
-               }
-
-               synchronized void clear() {
-                       nextMid = 0;
-                       mpxCount = 0;
-                       maxMpxCount = 1;
-                       first = last = null;
-               }
-               synchronized int aquireMid() throws InterruptedException {
-                       while( mpxCount >= maxMpxCount ) {
-                               wait();
-                       }
-                       if(( ++nextMid % 0xFFFF ) == 0 ) {
-                               nextMid = 1;
-                       }
-                       add( nextMid );
-                       mpxCount++;
-                       return nextMid;
-               }
-               synchronized void releaseMid( int i ) {
-                       remove( i );
-                       mpxCount--;
-                       notify();
-               }
-               synchronized boolean contains( int i ) {
-                       for( MpxListNode tmp = first; tmp != null; tmp = tmp.next ) {
-                               if( tmp.i == i ) {
-                                       return true;
-                               }
-                       }
-                       return false;
-               }          
-               synchronized void add( int i ) {
-                       if( contains( i )) {
-                               return;
-                       }
-                       if( first == null ) {
-                               first = last = new MpxListNode( i );
-                       } else {
-                               last = last.next = new MpxListNode( i );
-                       }
-               }
-               synchronized void remove( int i ) {
-                       if( first == null ) {
-                               return;
-                       } else if( first == last && first.i == i ) {
-                               first = last = null;
-                               return;
-                       }
-                       MpxListNode tmp, prev;
-                       for( tmp = prev = first; tmp != null; tmp = tmp.next ) {
-                               if( tmp.i == i ) {
-                                       if( tmp == first ) {
-                                               first = first.next;
-                                       } else if( tmp == last ) {
-                                               last = prev;
-                                               last.next = null;
-                                       } else {
-                                               prev.next = tmp.next;
-                                       }
-                                       return;
-                               }
-                               prev = tmp;
-                       }
-               }          
-       }
+                    }
+                } while( request.hasMoreElements() && request.nextElement() != null );
+
+                do {
+                    // default it 1 so that 0 can be used as forever
+                    response.received = false;
+                    response.wait( response.responseTimeout == 1 ? RESPONSE_TIMEOUT : response.responseTimeout );
+                } while( response.received && response.hasMoreElements() );
+            }
+        } catch( InterruptedException ie ) {
+            tryClose( true );
+        } catch( IOException ioe ) {
+            tryClose( true );
+            throw new SmbException( "An error occured sending the request.", ioe );
+        } finally {
+            synchronized( outLock ) {
+                responseTable.remove( mid );
+                releaseMid( mid );
+            }
+            BufferCache.releaseBuffer( request.txn_buf );
+            BufferCache.releaseBuffer( response.txn_buf );
+        }
+
+        if( response.received == false ) {
+            tryClose( true );
+            throw new SmbException( "Timeout waiting for response from server: " + address );
+        } else if( response.verifyFailed ) {
+            tryClose( true );
+            throw new SmbException( "Unverifiable signature: " + address );
+        }
+        response.errorCode = SmbException.getStatusByCode( response.errorCode );
+        switch( response.errorCode ) {
+            case NtStatus.NT_STATUS_OK:
+                break;
+            case NtStatus.NT_STATUS_ACCESS_DENIED:
+            case NtStatus.NT_STATUS_WRONG_PASSWORD:
+            case NtStatus.NT_STATUS_LOGON_FAILURE:
+            case NtStatus.NT_STATUS_ACCOUNT_RESTRICTION:
+            case NtStatus.NT_STATUS_INVALID_LOGON_HOURS:
+            case NtStatus.NT_STATUS_INVALID_WORKSTATION:
+            case NtStatus.NT_STATUS_PASSWORD_EXPIRED:
+            case NtStatus.NT_STATUS_ACCOUNT_DISABLED:
+                throw new SmbAuthException( response.errorCode );
+            case NtStatus.NT_STATUS_PATH_NOT_COVERED:
+                if( request.auth == null ) {
+                    throw new SmbException( response.errorCode, null );
+                }
+                DfsReferral dr = getDfsReferral( request.auth, request.path );
+                referrals.add( dr );
+                throw dr;
+            default:
+                throw new SmbException( response.errorCode, null );
+        }
+    }
+    synchronized void negotiate() throws SmbException {
+
+        if( this == NULL_TRANSPORT ) {
+            throw new RuntimeException( "Null transport cannot be used" );
+        }
+        if( state >= ST_NEGOTIATING ) {
+            return;
+        }
+        state = ST_NEGOTIATING;
+
+        if( log.level > 2 )
+            log.println( "requesting negotiation with " + address );
+
+        /*
+         * Negotiate Protocol Request / Response
+         */
+
+        SmbComNegotiateResponse response = new SmbComNegotiateResponse();
+        send( new SmbComNegotiate(), response );
+
+        if( response.dialectIndex > 10 ) {
+            tryClose( true );
+            throw new SmbException( "This client does not support the negotiated dialect." );
+        }
+
+        server = new ServerData();
+        server.securityMode = response.securityMode;
+        server.security = response.security;
+        server.encryptedPasswords = response.encryptedPasswords;
+        server.signaturesEnabled = response.signaturesEnabled;
+        server.signaturesRequired = response.signaturesRequired;
+        server.maxMpxCount = response.maxMpxCount;
+        server.maxNumberVcs = response.maxNumberVcs;
+        server.maxBufferSize = response.maxBufferSize;
+        server.maxRawSize = response.maxRawSize;
+        server.sessionKey = response.sessionKey;
+        server.capabilities = response.capabilities;
+        server.serverTime = response.serverTime;
+        server.serverTimeZone = response.serverTimeZone;
+        server.encryptionKeyLength = response.encryptionKeyLength;
+        server.encryptionKey = response.encryptionKey;
+        server.oemDomainName = response.oemDomainName;
+
+        if (server.signaturesRequired || (server.signaturesEnabled && SIGNPREF)) {
+            flags2 |= ServerMessageBlock.FLAGS2_SECURITY_SIGNATURES;
+        } else {
+            flags2 &= 0xFFFF ^ ServerMessageBlock.FLAGS2_SECURITY_SIGNATURES;
+        }
+
+        maxMpxCount = maxMpxCount < server.maxMpxCount ? maxMpxCount : server.maxMpxCount;
+        maxMpxCount = maxMpxCount < 1 ? 1 : maxMpxCount;
+
+        snd_buf_size = snd_buf_size < server.maxBufferSize ? snd_buf_size : server.maxBufferSize;
+
+        capabilities &= server.capabilities;
+        if(( capabilities & ServerMessageBlock.CAP_UNICODE ) == 0 ) {
+            // server doesn't want unicode
+            if( FORCE_UNICODE ) {
+                capabilities |= ServerMessageBlock.CAP_UNICODE;
+            } else {
+                useUnicode = false;
+                flags2 &= 0xFFFF ^ ServerMessageBlock.FLAGS2_UNICODE;
+            }
+        }
+    }
+    public String toString() {
+        String ret = "SmbTransport[address=" + address;
+        if( socket == null ) {
+            ret += ",port=,localAddr=,localPort=]";
+        } else {
+            ret += ",port=" + socket.getPort() +
+            ",localAddr=" + socket.getLocalAddress() +
+            ",localPort=" + socket.getLocalPort() + "]";
+        }
+        return ret;
+    }
+
+    /* Manage MIDs */
+
+    Mid aquireMid() throws SmbException {
+        int i;
+
+        if( mid_next == 0 ) {
+            mid_next++;
+        }
+
+        for( ;; ) {
+            for( i = 0; i < maxMpxCount; i++ ) {
+                if( mids[i].mid == 0 ) {
+                    break;
+                }
+            }
+            if( i == maxMpxCount ) {
+                try {
+                    outLock.wait();
+                } catch( InterruptedException ie ) {
+                    throw new SmbException( "Interrupted aquiring mid", ie );
+                }
+            } else {
+                break;
+            }
+        }
+
+        mids[i].mid = mid_next++;
+
+        return mids[i];
+    }
+    void releaseMid( Mid mid ) {
+        int i;
+
+        for( i = 0; i < maxMpxCount; i++ ) {
+            if( mids[i].mid == mid.mid ) {
+                mid.mid = 0;
+                outLock.notify();
+                return;
+            }
+        }
+        if( log.level > 1 )
+            log.println( "mid not found" );
+    }
 }
index 7c5ea58..f594435 100644 (file)
@@ -22,141 +22,142 @@ import java.io.IOException;
 import java.net.UnknownHostException;
 import jcifs.UniAddress;
 import jcifs.netbios.NbtAddress;
+import jcifs.Config;
 
 class SmbTree {
 
-       int tid;
-       String share;
-       String service = jcifs.Config.getProperty( "jcifs.smb.client.serviceType", "?????" );
-       SmbSession session;
-       boolean treeConnected, inDfs;
-
-       SmbTree( SmbSession session, String share, String service ) {
-               this.session = session;
-               this.share = share.toUpperCase();
-               if( service != null && service.startsWith( "??" ) == false ) {
-                       this.service = service;
-               }
-       }
-
-       boolean matches( String share, String service ) {
-               return this.share.equalsIgnoreCase( share ) &&
-                               ( service == null || service.startsWith( "??" ) ||
-                               this.service.equalsIgnoreCase( service ));
-       }
-       void sendTransaction( SmbComTransaction request,
-                                                       SmbComTransactionResponse response ) throws SmbException {
-               // transactions are not batchable
-               treeConnect( null, null );
-               if( service.equals( "A:" ) == false ) {
-                       switch( ((SmbComTransaction)request).subCommand ) {
-                               case SmbComTransaction.NET_SHARE_ENUM:
-                               case SmbComTransaction.NET_SERVER_ENUM2:
-                               case SmbComTransaction.TRANS_PEEK_NAMED_PIPE:
-                               case SmbComTransaction.TRANS_WAIT_NAMED_PIPE:
-                               case SmbComTransaction.TRANS_CALL_NAMED_PIPE:
-                               case SmbComTransaction.TRANS_TRANSACT_NAMED_PIPE:
-                               case SmbComTransaction.TRANS2_GET_DFS_REFERRAL:
-                                       break;
-                               default:
-                                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe,
-                                                               "Invalid operation for " + service + " service");
-                       }
-               }
-               request.tid = tid;
-               if( inDfs && request.path != null && request.path.length() > 0 ) {
-                       request.path = '\\' + session.transport.server.tconHostName + '\\' + share + request.path;
-               }
-               session.sendTransaction( request, response );
-       }
-       void send( ServerMessageBlock request,
-                                                       ServerMessageBlock response ) throws SmbException {
-               if( response != null ) {
-                       response.received = false;
-               }
-               treeConnect( request, response );
-               if( request == null || (response != null && response.received )) {
-                       return;
-               }
-               if( service.equals( "A:" ) == false ) {
-                       switch( request.command ) {
-                               case ServerMessageBlock.SMB_COM_OPEN_ANDX:
-                               case ServerMessageBlock.SMB_COM_NT_CREATE_ANDX:
-                               case ServerMessageBlock.SMB_COM_READ_ANDX:
-                               case ServerMessageBlock.SMB_COM_WRITE_ANDX:
-                               case ServerMessageBlock.SMB_COM_CLOSE:
-                               case ServerMessageBlock.SMB_COM_TREE_DISCONNECT:
-                                       break;
-                               default:
-                                       throw new SmbException( SmbException.ERRCLI, SmbException.ERRioe,
-                                                               "Invalid operation for " + service + " service");
-                       }
-               }
-               request.tid = tid;
-               if( inDfs && request.path != null && request.path.length() > 0 ) {
-                       request.flags2 = ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS;
-                       request.path = '\\' + session.transport.server.tconHostName + '\\' + share + request.path;
-               }
-               session.send( request, response );
-       }
-       void treeConnect( ServerMessageBlock andx,
-                                                       ServerMessageBlock andxResponse ) throws SmbException {
-               String unc;
-synchronized( session.transport ) {
+    private static final String DEFAULT_SERVICE = Config.getProperty( "jcifs.smb.client.serviceType", "?????" );
+
+    private int tid;
+    private String share;
+
+    String service = DEFAULT_SERVICE;
+    SmbSession session;
+    boolean treeConnected, inDfs;
 
-               if( treeConnected ) {
-                       return;
-               }
+    SmbTree( SmbSession session, String share, String service ) {
+        this.session = session;
+        this.share = share.toUpperCase();
+        if( service != null && service.startsWith( "??" ) == false ) {
+            this.service = service;
+        }
+    }
 
-               /* The hostname to use in the path is only known for
-                * sure if the NetBIOS session has been successfully
-                * established.
-                */
+    boolean matches( String share, String service ) {
+        return this.share.equalsIgnoreCase( share ) &&
+                ( service == null || service.startsWith( "??" ) ||
+                this.service.equalsIgnoreCase( service ));
+    }
+    void sendTransaction( SmbComTransaction request,
+                            SmbComTransactionResponse response ) throws SmbException {
+        // transactions are not batchable
+        treeConnect( null, null );
+        if( service.equals( "A:" ) == false ) {
+            switch( ((SmbComTransaction)request).subCommand ) {
+                case SmbComTransaction.NET_SHARE_ENUM:
+                case SmbComTransaction.NET_SERVER_ENUM2:
+                case SmbComTransaction.TRANS_PEEK_NAMED_PIPE:
+                case SmbComTransaction.TRANS_WAIT_NAMED_PIPE:
+                case SmbComTransaction.TRANS_CALL_NAMED_PIPE:
+                case SmbComTransaction.TRANS_TRANSACT_NAMED_PIPE:
+                case SmbComTransaction.TRANS2_GET_DFS_REFERRAL:
+                    break;
+                default:
+                    throw new SmbException( "Invalid operation for " + service + " service" );
+            }
+        }
+        request.tid = tid;
+        if( inDfs && request.path != null && request.path.length() > 0 ) {
+            request.path = '\\' + session.transport().tconHostName + '\\' + share + request.path;
+        }
+        session.sendTransaction( request, response );
+    }
+    void send( ServerMessageBlock request,
+                            ServerMessageBlock response ) throws SmbException {
+        if( response != null ) {
+            response.received = false;
+        }
+        treeConnect( request, response );
+        if( request == null || (response != null && response.received )) {
+            return;
+        }
+        if( service.equals( "A:" ) == false ) {
+            switch( request.command ) {
+                case ServerMessageBlock.SMB_COM_OPEN_ANDX:
+                case ServerMessageBlock.SMB_COM_NT_CREATE_ANDX:
+                case ServerMessageBlock.SMB_COM_READ_ANDX:
+                case ServerMessageBlock.SMB_COM_WRITE_ANDX:
+                case ServerMessageBlock.SMB_COM_CLOSE:
+                case ServerMessageBlock.SMB_COM_TREE_DISCONNECT:
+                    break;
+                default:
+                    throw new SmbException( "Invalid operation for " + service + " service" );
+            }
+        }
+        request.tid = tid;
+        if( inDfs && request.path != null && request.path.length() > 0 ) {
+            request.flags2 = ServerMessageBlock.FLAGS2_RESOLVE_PATHS_IN_DFS;
+            request.path = '\\' + session.transport().tconHostName + '\\' + share + request.path;
+        }
+        session.send( request, response );
+    }
+    void treeConnect( ServerMessageBlock andx,
+                            ServerMessageBlock andxResponse ) throws SmbException {
+        String unc;
+synchronized( session.transport() ) {
 
-               session.transport.negotiate();
+        if( treeConnected ) {
+            return;
+        }
 
-               unc = "\\\\" + session.transport.server.tconHostName + '\\' + share;
+        /* The hostname to use in the path is only known for
+         * sure if the NetBIOS session has been successfully
+         * established.
+         */
 
-               Log.println( Log.WARNINGS, "smb tree connect warning",
-                               " requesting tree connect with unc=" + unc +
-                               ",service=" + service );
+        session.transport.negotiate();
 
-               /*
-                * Tree Connect And X Request / Response
-                */
+        unc = "\\\\" + session.transport.tconHostName + '\\' + share;
 
-               SmbComTreeConnectAndXResponse response =
-                                                                       new SmbComTreeConnectAndXResponse( andxResponse );
-               SmbComTreeConnectAndX request =
-                                                                       new SmbComTreeConnectAndX( session, unc, service, andx );
-               session.send( request, response );
+        /*
+         * Tree Connect And X Request / Response
+         */
 
-               tid = response.tid;
-               service = response.service;
-               inDfs = response.shareIsInDfs;
-               treeConnected = true;
+        if( session.transport.log.level > 2 )
+            session.transport.log.println( "treeConnect: unc=" + unc + ",service=" + service );
+
+        SmbComTreeConnectAndXResponse response =
+                                    new SmbComTreeConnectAndXResponse( andxResponse );
+        SmbComTreeConnectAndX request =
+                                    new SmbComTreeConnectAndX( session, unc, service, andx );
+        session.send( request, response );
+
+        tid = response.tid;
+        service = response.service;
+        inDfs = response.shareIsInDfs;
+        treeConnected = true;
 }
-       }
-       void treeDisconnect( boolean inError ) {
+    }
+    void treeDisconnect( boolean inError ) {
 synchronized( session.transport ) {
-               if( treeConnected == false ) {
-                       return;
-               }
-               if( !inError ) {
-                       try {
-                               send( new SmbComTreeDisconnect(), null );
-                       } catch( SmbException ioe ) {
-                       }
-               }
-               treeConnected = false;
+        if( treeConnected == false ) {
+            return;
+        }
+        if( !inError ) {
+            try {
+                send( new SmbComTreeDisconnect(), null );
+            } catch( SmbException se ) {
+            }
+        }
+        treeConnected = false;
 }
-       }
-
-       public String toString() {
-               return "SmbTree[share=" + share +
-                       ",service=" + service +
-                       ",tid=" + tid +
-                       ",inDfs=" + inDfs +
-                       ",treeConnected=" + treeConnected + "]";
-       }
+    }
+
+    public String toString() {
+        return "SmbTree[share=" + share +
+            ",service=" + service +
+            ",tid=" + tid +
+            ",inDfs=" + inDfs +
+            ",treeConnected=" + treeConnected + "]";
+    }
 }
index 08ad662..b42ed1a 100644 (file)
 package jcifs.smb;
 
 import jcifs.Config;
+import jcifs.util.Hexdump;
 
 class Trans2FindFirst2 extends SmbComTransaction {
 
-
-       // information levels
-
-       static final int SMB_INFO_STANDARD                 = 1;
-       static final int SMB_INFO_QUERY_EA_SIZE            = 2;
-       static final int SMB_INFO_QUERY_EAS_FROM_LIST      = 3;
-       static final int SMB_FIND_FILE_DIRECTORY_INFO      = 0x101;
-       static final int SMB_FIND_FILE_FULL_DIRECTORY_INFO = 0x102;
-       static final int SMB_FILE_NAMES_INFO               = 0x103;
-       static final int SMB_FILE_BOTH_DIRECTORY_INFO      = 0x104;
-
-       // flags
-
-       static final int FLAGS_CLOSE_AFTER_THIS_REQUEST = 0x01;
-       static final int FLAGS_CLOSE_IF_END_REACHED     = 0x02;
-       static final int FLAGS_RETURN_RESUME_KEYS       = 0x04;
-       static final int FLAGS_RESUME_FROM_PREVIOUS_END = 0x08;
-       static final int FLAGS_FIND_WITH_BACKUP_INTENT  = 0x10;
-
-       
-       static final int DEFAULT_MAX_DATA_COUNT = 1200;
-       static final int DEFAULT_SEARCH_COUNT = 15;
-
-       int searchAttributes;
-       int searchCount;
-       int flags;
-       int informationLevel;
-       int searchStorageType = 0;
-       String wildcard;
-
-       Trans2FindFirst2( String filename, String wildcard, int searchAttributes ) {
-               if( filename.equals( "\\" )) {
-                       this.path = filename;
-               } else {
-                       this.path = filename + "\\";
-               }
-               this.wildcard = wildcard;
-               this.searchAttributes = searchAttributes & SmbFile.ATTR_GET_MASK;
-               command = SMB_COM_TRANSACTION2;
-               subCommand = TRANS2_FIND_FIRST2;
-
-               searchCount = Config.getInt( "jcifs.smb.client.listCount", DEFAULT_SEARCH_COUNT );
-               flags = 0x00;
-               informationLevel = SMB_FILE_BOTH_DIRECTORY_INFO;
-
-               totalDataCount = 0;
-               maxParameterCount = 10;
-               maxDataCount = Config.getInt( "jcifs.smb.client.listSize", DEFAULT_MAX_DATA_COUNT );
-               maxSetupCount = 0;
-       }
-
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = subCommand;
-               dst[dstIndex++] = (byte)0x00;
-               return 2;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
-
-               writeInt2( searchAttributes, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( searchCount, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( flags, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( informationLevel, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( searchStorageType, dst, dstIndex );
-               dstIndex += 4;
-               dstIndex += writeString( path + wildcard, dst, dstIndex );
-
-               return dstIndex - start;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "Trans2FindFirst2[" + super.toString() +
-                       ",searchAttributes=0x" + Log.getHexString( searchAttributes, 2 ) +
-                       ",searchCount=" + searchCount +
-                       ",flags=0x" + Log.getHexString( flags, 2 ) +
-                       ",informationLevel=0x" + Log.getHexString( informationLevel, 3 ) +
-                       ",searchStorageType=" + searchStorageType +
-                       ",filename=" + path + "]" );
-       }
+    // flags
+
+    private static final int FLAGS_CLOSE_AFTER_THIS_REQUEST = 0x01;
+    private static final int FLAGS_CLOSE_IF_END_REACHED     = 0x02;
+    private static final int FLAGS_RETURN_RESUME_KEYS       = 0x04;
+    private static final int FLAGS_RESUME_FROM_PREVIOUS_END = 0x08;
+    private static final int FLAGS_FIND_WITH_BACKUP_INTENT  = 0x10;
+
+    private static final int DEFAULT_LIST_SIZE = 65535;
+    private static final int DEFAULT_LIST_COUNT = 200;
+
+    private int searchAttributes;
+    private int flags;
+    private int informationLevel;
+    private int searchStorageType = 0;
+    private String wildcard;
+
+    // information levels
+
+    static final int SMB_INFO_STANDARD                 = 1;
+    static final int SMB_INFO_QUERY_EA_SIZE            = 2;
+    static final int SMB_INFO_QUERY_EAS_FROM_LIST      = 3;
+    static final int SMB_FIND_FILE_DIRECTORY_INFO      = 0x101;
+    static final int SMB_FIND_FILE_FULL_DIRECTORY_INFO = 0x102;
+    static final int SMB_FILE_NAMES_INFO               = 0x103;
+    static final int SMB_FILE_BOTH_DIRECTORY_INFO      = 0x104;
+
+    static final int LIST_SIZE = Config.getInt( "jcifs.smb.client.listSize", DEFAULT_LIST_SIZE );
+    static final int LIST_COUNT = Config.getInt( "jcifs.smb.client.listCount", DEFAULT_LIST_COUNT );
+
+    Trans2FindFirst2( String filename, String wildcard, int searchAttributes ) {
+        if( filename.equals( "\\" )) {
+            this.path = filename;
+        } else {
+            this.path = filename + "\\";
+        }
+        this.wildcard = wildcard;
+        this.searchAttributes = searchAttributes & SmbFile.ATTR_GET_MASK;
+        command = SMB_COM_TRANSACTION2;
+        subCommand = TRANS2_FIND_FIRST2;
+
+        flags = 0x00;
+        informationLevel = SMB_FILE_BOTH_DIRECTORY_INFO;
+
+        totalDataCount = 0;
+        maxParameterCount = 10;
+        maxDataCount = LIST_SIZE;
+        maxSetupCount = 0;
+    }
+
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = subCommand;
+        dst[dstIndex++] = (byte)0x00;
+        return 2;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
+
+        writeInt2( searchAttributes, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( LIST_COUNT, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( flags, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( informationLevel, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( searchStorageType, dst, dstIndex );
+        dstIndex += 4;
+        dstIndex += writeString( path + wildcard, dst, dstIndex );
+
+        return dstIndex - start;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "Trans2FindFirst2[" + super.toString() +
+            ",searchAttributes=0x" + Hexdump.toHexString( searchAttributes, 2 ) +
+            ",searchCount=" + LIST_COUNT +
+            ",flags=0x" + Hexdump.toHexString( flags, 2 ) +
+            ",informationLevel=0x" + Hexdump.toHexString( informationLevel, 3 ) +
+            ",searchStorageType=" + searchStorageType +
+            ",filename=" + path + "]" );
+    }
 }
index b3d1546..a9e7ce4 100644 (file)
@@ -23,220 +23,211 @@ import java.util.Date;
 
 class Trans2FindFirst2Response extends SmbComTransactionResponse {
 
-       // information levels
-
-       static final int SMB_INFO_STANDARD                 = 1;
-       static final int SMB_INFO_QUERY_EA_SIZE            = 2;
-       static final int SMB_INFO_QUERY_EAS_FROM_LIST      = 3;
-       static final int SMB_FIND_FILE_DIRECTORY_INFO      = 0x101;
-       static final int SMB_FIND_FILE_FULL_DIRECTORY_INFO = 0x102;
-       static final int SMB_FILE_NAMES_INFO               = 0x103;
-       static final int SMB_FILE_BOTH_DIRECTORY_INFO      = 0x104;
-
-       class SmbFindFileBothDirectoryInfo implements FileEntry {
-               int nextEntryOffset;
-               int fileIndex;
-               long creationTime;
-               long lastAccessTime;
-               long lastWriteTime;
-               long changeTime;
-               long endOfFile;
-               long allocationSize;
-               int extFileAttributes;
-               int fileNameLength;
-               int eaSize;
-               int shortNameLength;
-               String shortName;
-               String filename;
-
-               public String getName() {
-                       return filename;
-               }
-               public int getType() {
-                       return SmbFile.TYPE_FILESYSTEM;
-               }
-               public int getAttributes() {
-                       return extFileAttributes;
-               }
-               public long createTime() {
-                       return creationTime;
-               }
-               public long lastModified() {
-                       return lastWriteTime;
-               }
-               public long length() {
-                       return endOfFile;
-               }
-
-               public String toString() {
-                       return new String( "SmbFindFileBothDirectoryInfo[" +
-                               "nextEntryOffset=" + nextEntryOffset +
-                               ",fileIndex=" + fileIndex +
-                               ",creationTime=" + new Date( creationTime ) +
-                               ",lastAccessTime=" + new Date( lastAccessTime ) +
-                               ",lastWriteTime=" + new Date( lastWriteTime ) +
-                               ",changeTime=" + new Date( changeTime ) +
-                               ",endOfFile=" + endOfFile +
-                               ",allocationSize=" + allocationSize +
-                               ",extFileAttributes=" + extFileAttributes +
-                               ",fileNameLength=" + fileNameLength +
-                               ",eaSize=" + eaSize +
-                               ",shortNameLength=" + shortNameLength +
-                               ",shortName=" + shortName +
-                               ",filename=" + filename + "]" );
-               }
-       }
-
-       int sid;
-       boolean isEndOfSearch;
-       int eaErrorOffset;
-       int lastNameOffset, lastNameBufferIndex;
-       String lastName;
-       int resumeKey;
-
-
-       Trans2FindFirst2Response() {
-               command = SMB_COM_TRANSACTION2;
-               subCommand = SmbComTransaction.TRANS2_FIND_FIRST2;
-       }
-
-       String readString( byte[] src, int srcIndex, int len ) {
-               String str = null;
-               try {
-                       if( useUnicode ) {
-                               // should Unicode alignment be corrected for here?
-                               str = new String( src, srcIndex, len, "UnicodeLittle" );
-                       } else {
-       
-                               /* On NT without Unicode the fileNameLength
-                                * includes the '\0' whereas on win98 it doesn't. I
-                                * guess most clients only support non-unicode so
-                                * they don't run into this.
-                                */
-       
-       /* UPDATE: Maybe not! Could this be a Unicode alignment issue. I hope
-        * so. We cannot just comment out this method and use readString of
-        * ServerMessageBlock.java because the arguments are different, however
-        * one might be able to reduce this.
-        */
-       
-                               if( len > 0 && src[srcIndex + len - 1] == '\0' ) {
-                                       len--;
-                               }
-                               str = new String( src, srcIndex, len, ServerMessageBlock.encoding );
-                       }
-               } catch( UnsupportedEncodingException uee ) {
-                       Log.printStackTrace( "smb exception", uee );
-               }
-               return str;
-       }
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               int start = bufferIndex;
-
-               if( subCommand == SmbComTransaction.TRANS2_FIND_FIRST2 ) {
-                       sid = readInt2( buffer, bufferIndex );
-                       bufferIndex += 2;
-               }
-               numEntries = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               isEndOfSearch = ( buffer[bufferIndex] & 0x01 ) == 0x01 ? true : false;
-               bufferIndex += 2;
-               eaErrorOffset = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               lastNameOffset = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-
-               return bufferIndex - start;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               int start = bufferIndex;
-               SmbFindFileBothDirectoryInfo e;
-
-               lastNameBufferIndex = bufferIndex + lastNameOffset;
-
-               results = new SmbFindFileBothDirectoryInfo[numEntries];
-               for( int i = 0; i < numEntries; i++ ) {
-                       results[i] = e = new SmbFindFileBothDirectoryInfo();
-
-                       e.nextEntryOffset = readInt4( buffer, bufferIndex );
-                       e.fileIndex = readInt4( buffer, bufferIndex + 4 );
-                       e.creationTime = readTime( buffer, bufferIndex + 8 );
-       //              e.lastAccessTime = readTime( buffer, bufferIndex + 16 );
-                       e.lastWriteTime = readTime( buffer, bufferIndex + 24 );
-       //              e.changeTime = readTime( buffer, bufferIndex + 32 );
-                       e.endOfFile = readLong( buffer, bufferIndex + 40 );
-       //              e.allocationSize = readLong( buffer, bufferIndex + 48 );
-                       e.extFileAttributes = readInt4( buffer, bufferIndex + 56 );
-                       e.fileNameLength = readInt4( buffer, bufferIndex + 60 );
-       //              e.eaSize = readInt4( buffer, bufferIndex + 64 );
-       //              e.shortNameLength = buffer[bufferIndex + 68] & 0xFF;
-
-                       /* With NT, the shortName is in Unicode regardless of what is negotiated.
-                        */
-
-       //              e.shortName = readString( buffer, bufferIndex + 70, e.shortNameLength );
-                       e.filename = readString( buffer, bufferIndex + 94, e.fileNameLength );
-
-//Log.println( Log.DEBUGGING, "Trans2FindFirst2/Next2Response debugging", "bufferIndex=" + bufferIndex + ",lastNameBufferIndex=" + lastNameBufferIndex + ",nextEntryOffet=" + ( bufferIndex + e.nextEntryOffset ));
-
-                       /* lastNameOffset ends up pointing to either to
-                        * the exact location of the filename(e.g. Win98)
-                        * or to the start of the entry containing the
-                        * filename(e.g. NT). Ahhrg! In either case the
-                        * lastNameOffset falls between the start of the
-                        * entry and the next entry.
-                        */
-
-                       if( lastNameBufferIndex >= bufferIndex && ( e.nextEntryOffset == 0 ||
-                                               lastNameBufferIndex < ( bufferIndex + e.nextEntryOffset ))) {
-                               lastName = e.filename;
-                               resumeKey = e.fileIndex;
-                       }
-
-//Log.println( Log.DEBUGGING, "info entry", e );
-
-                       bufferIndex += e.nextEntryOffset;
-               }
-
-
-               if( lastName == null ) {
-                       Log.println( Log.WARNINGS, "Trans2FindFirst2/Next2Response debugging",
-                                                                                       "lastName was null" );
-               }
-
-               /* last nextEntryOffset for NT 4(but not 98) is 0 so we must
-                * use dataCount or our accounting will report an error for NT :~(
-                */
-               
-               //return bufferIndex - start;
-
-               return dataCount;
-       }
-       public String toString() {
-               String c;
-               if( subCommand == SmbComTransaction.TRANS2_FIND_FIRST2 ) {
-                       c = "Trans2FindFirst2Response[";
-               } else {
-                       c = "Trans2FindNext2Response[";
-               }
-               return new String( c + super.toString() +
-                       ",sid=" + sid +
-                       ",searchCount=" + numEntries +
-                       ",isEndOfSearch=" + isEndOfSearch +
-                       ",eaErrorOffset=" + eaErrorOffset +
-                       ",lastNameOffset=" + lastNameOffset +
-                       ",lastName=" + lastName + "]" );
-       }
+    // information levels
+
+    static final int SMB_INFO_STANDARD                 = 1;
+    static final int SMB_INFO_QUERY_EA_SIZE            = 2;
+    static final int SMB_INFO_QUERY_EAS_FROM_LIST      = 3;
+    static final int SMB_FIND_FILE_DIRECTORY_INFO      = 0x101;
+    static final int SMB_FIND_FILE_FULL_DIRECTORY_INFO = 0x102;
+    static final int SMB_FILE_NAMES_INFO               = 0x103;
+    static final int SMB_FILE_BOTH_DIRECTORY_INFO      = 0x104;
+
+    class SmbFindFileBothDirectoryInfo implements FileEntry {
+        int nextEntryOffset;
+        int fileIndex;
+        long creationTime;
+        long lastAccessTime;
+        long lastWriteTime;
+        long changeTime;
+        long endOfFile;
+        long allocationSize;
+        int extFileAttributes;
+        int fileNameLength;
+        int eaSize;
+        int shortNameLength;
+        String shortName;
+        String filename;
+
+        public String getName() {
+            return filename;
+        }
+        public int getType() {
+            return SmbFile.TYPE_FILESYSTEM;
+        }
+        public int getAttributes() {
+            return extFileAttributes;
+        }
+        public long createTime() {
+            return creationTime;
+        }
+        public long lastModified() {
+            return lastWriteTime;
+        }
+        public long length() {
+            return endOfFile;
+        }
+
+        public String toString() {
+            return new String( "SmbFindFileBothDirectoryInfo[" +
+                "nextEntryOffset=" + nextEntryOffset +
+                ",fileIndex=" + fileIndex +
+                ",creationTime=" + new Date( creationTime ) +
+                ",lastAccessTime=" + new Date( lastAccessTime ) +
+                ",lastWriteTime=" + new Date( lastWriteTime ) +
+                ",changeTime=" + new Date( changeTime ) +
+                ",endOfFile=" + endOfFile +
+                ",allocationSize=" + allocationSize +
+                ",extFileAttributes=" + extFileAttributes +
+                ",fileNameLength=" + fileNameLength +
+                ",eaSize=" + eaSize +
+                ",shortNameLength=" + shortNameLength +
+                ",shortName=" + shortName +
+                ",filename=" + filename + "]" );
+        }
+    }
+
+    int sid;
+    boolean isEndOfSearch;
+    int eaErrorOffset;
+    int lastNameOffset, lastNameBufferIndex;
+    String lastName;
+    int resumeKey;
+
+
+    Trans2FindFirst2Response() {
+        command = SMB_COM_TRANSACTION2;
+        subCommand = SmbComTransaction.TRANS2_FIND_FIRST2;
+    }
+
+    String readString( byte[] src, int srcIndex, int len ) {
+        String str = null;
+        try {
+            if( useUnicode ) {
+                // should Unicode alignment be corrected for here?
+                str = new String( src, srcIndex, len, "UnicodeLittle" );
+            } else {
+    
+                /* On NT without Unicode the fileNameLength
+                 * includes the '\0' whereas on win98 it doesn't. I
+                 * guess most clients only support non-unicode so
+                 * they don't run into this.
+                 */
+    
+    /* UPDATE: Maybe not! Could this be a Unicode alignment issue. I hope
+     * so. We cannot just comment out this method and use readString of
+     * ServerMessageBlock.java because the arguments are different, however
+     * one might be able to reduce this.
+     */
+    
+                if( len > 0 && src[srcIndex + len - 1] == '\0' ) {
+                    len--;
+                }
+                str = new String( src, srcIndex, len, ServerMessageBlock.OEM_ENCODING );
+            }
+        } catch( UnsupportedEncodingException uee ) {
+            if( log.level > 1 )
+                uee.printStackTrace( log );
+        }
+        return str;
+    }
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        int start = bufferIndex;
+
+        if( subCommand == SmbComTransaction.TRANS2_FIND_FIRST2 ) {
+            sid = readInt2( buffer, bufferIndex );
+            bufferIndex += 2;
+        }
+        numEntries = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        isEndOfSearch = ( buffer[bufferIndex] & 0x01 ) == 0x01 ? true : false;
+        bufferIndex += 2;
+        eaErrorOffset = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        lastNameOffset = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+
+        return bufferIndex - start;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        int start = bufferIndex;
+        SmbFindFileBothDirectoryInfo e;
+
+        lastNameBufferIndex = bufferIndex + lastNameOffset;
+
+        results = new SmbFindFileBothDirectoryInfo[numEntries];
+        for( int i = 0; i < numEntries; i++ ) {
+            results[i] = e = new SmbFindFileBothDirectoryInfo();
+
+            e.nextEntryOffset = readInt4( buffer, bufferIndex );
+            e.fileIndex = readInt4( buffer, bufferIndex + 4 );
+            e.creationTime = readTime( buffer, bufferIndex + 8 );
+    //      e.lastAccessTime = readTime( buffer, bufferIndex + 16 );
+            e.lastWriteTime = readTime( buffer, bufferIndex + 24 );
+    //      e.changeTime = readTime( buffer, bufferIndex + 32 );
+            e.endOfFile = readInt8( buffer, bufferIndex + 40 );
+    //      e.allocationSize = readInt8( buffer, bufferIndex + 48 );
+            e.extFileAttributes = readInt4( buffer, bufferIndex + 56 );
+            e.fileNameLength = readInt4( buffer, bufferIndex + 60 );
+    //      e.eaSize = readInt4( buffer, bufferIndex + 64 );
+    //      e.shortNameLength = buffer[bufferIndex + 68] & 0xFF;
+
+            /* With NT, the shortName is in Unicode regardless of what is negotiated.
+             */
+
+    //      e.shortName = readString( buffer, bufferIndex + 70, e.shortNameLength );
+            e.filename = readString( buffer, bufferIndex + 94, e.fileNameLength );
+
+            /* lastNameOffset ends up pointing to either to
+             * the exact location of the filename(e.g. Win98)
+             * or to the start of the entry containing the
+             * filename(e.g. NT). Ahhrg! In either case the
+             * lastNameOffset falls between the start of the
+             * entry and the next entry.
+             */
+
+            if( lastNameBufferIndex >= bufferIndex && ( e.nextEntryOffset == 0 ||
+                        lastNameBufferIndex < ( bufferIndex + e.nextEntryOffset ))) {
+                lastName = e.filename;
+                resumeKey = e.fileIndex;
+            }
+
+            bufferIndex += e.nextEntryOffset;
+        }
+
+        /* last nextEntryOffset for NT 4(but not 98) is 0 so we must
+         * use dataCount or our accounting will report an error for NT :~(
+         */
+
+        //return bufferIndex - start;
+
+        return dataCount;
+    }
+    public String toString() {
+        String c;
+        if( subCommand == SmbComTransaction.TRANS2_FIND_FIRST2 ) {
+            c = "Trans2FindFirst2Response[";
+        } else {
+            c = "Trans2FindNext2Response[";
+        }
+        return new String( c + super.toString() +
+            ",sid=" + sid +
+            ",searchCount=" + numEntries +
+            ",isEndOfSearch=" + isEndOfSearch +
+            ",eaErrorOffset=" + eaErrorOffset +
+            ",lastNameOffset=" + lastNameOffset +
+            ",lastName=" + lastName + "]" );
+    }
 }
index c02ae47..2bd7a23 100644 (file)
 package jcifs.smb;
 
 import jcifs.Config;
+import jcifs.util.Hexdump;
 
 class Trans2FindNext2 extends SmbComTransaction {
 
-       int sid, searchCount, informationLevel, resumeKey, flags;
-       String filename;
+    private int sid, informationLevel, resumeKey, flags;
+    private String filename;
 
-       Trans2FindNext2( int sid, int resumeKey, String filename ) {
-               this.sid = sid;
-               this.resumeKey = resumeKey;
-               this.filename = filename;
-               command = SMB_COM_TRANSACTION2;
-               subCommand = TRANS2_FIND_NEXT2;
-               searchCount = Config.getInt( "jcifs.smb.client.listCount",
-                                                                                               Trans2FindFirst2.DEFAULT_SEARCH_COUNT );
-               informationLevel = Trans2FindFirst2.SMB_FILE_BOTH_DIRECTORY_INFO;
-               flags = 0x00;
-               maxParameterCount = 8;
-               maxDataCount = Config.getInt( "jcifs.smb.client.listSize",
-                                                                                               Trans2FindFirst2.DEFAULT_MAX_DATA_COUNT );
-               maxSetupCount = 0;
-       }
+    Trans2FindNext2( int sid, int resumeKey, String filename ) {
+        this.sid = sid;
+        this.resumeKey = resumeKey;
+        this.filename = filename;
+        command = SMB_COM_TRANSACTION2;
+        subCommand = TRANS2_FIND_NEXT2;
+        informationLevel = Trans2FindFirst2.SMB_FILE_BOTH_DIRECTORY_INFO;
+        flags = 0x00;
+        maxParameterCount = 8;
+        maxDataCount = Trans2FindFirst2.LIST_SIZE;
+        maxSetupCount = 0;
+    }
 
-       public void reset( int resumeKey, String lastName ) {
-               super.reset();
-               this.resumeKey = resumeKey;
-               this.filename = lastName;
-               flags2 = 0;
-       }
+    void reset( int resumeKey, String lastName ) {
+        super.reset();
+        this.resumeKey = resumeKey;
+        this.filename = lastName;
+        flags2 = 0;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = subCommand;
-               dst[dstIndex++] = (byte)0x00;
-               return 2;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = subCommand;
+        dst[dstIndex++] = (byte)0x00;
+        return 2;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               writeInt2( sid, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( searchCount, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( informationLevel, dst, dstIndex );
-               dstIndex += 2;
-               writeInt4( resumeKey, dst, dstIndex );
-               dstIndex += 4;
-               writeInt2( flags, dst, dstIndex );
-               dstIndex += 2;
-               dstIndex += writeString( filename, dst, dstIndex );
+        writeInt2( sid, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( Trans2FindFirst2.LIST_COUNT, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( informationLevel, dst, dstIndex );
+        dstIndex += 2;
+        writeInt4( resumeKey, dst, dstIndex );
+        dstIndex += 4;
+        writeInt2( flags, dst, dstIndex );
+        dstIndex += 2;
+        dstIndex += writeString( filename, dst, dstIndex );
 
-               return dstIndex - start;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "Trans2FindNext2[" + super.toString() +
-                       ",sid=" + sid +
-                       ",searchCount=" + searchCount +
-                       ",informationLevel=0x" + Log.getHexString( informationLevel, 3 ) +
-                       ",resumeKey=0x" + Log.getHexString( resumeKey, 4 ) +
-                       ",flags=0x" + Log.getHexString( flags, 2 ) +
-                       ",filename=" + filename + "]" );
-       }
+        return dstIndex - start;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "Trans2FindNext2[" + super.toString() +
+            ",sid=" + sid +
+            ",searchCount=" + Trans2FindFirst2.LIST_SIZE +
+            ",informationLevel=0x" + Hexdump.toHexString( informationLevel, 3 ) +
+            ",resumeKey=0x" + Hexdump.toHexString( resumeKey, 4 ) +
+            ",flags=0x" + Hexdump.toHexString( flags, 2 ) +
+            ",filename=" + filename + "]" );
+    }
 }
index e8952f3..29e7d97 100644 (file)
@@ -20,47 +20,47 @@ package jcifs.smb;
 
 class Trans2GetDfsReferral extends SmbComTransaction {
 
-       int maxReferralLevel = 3;
+    private int maxReferralLevel = 3;
 
-       Trans2GetDfsReferral( String filename ) {
-               path = filename;
-               command = SMB_COM_TRANSACTION2;
-               subCommand = TRANS2_GET_DFS_REFERRAL;
-               totalDataCount = 0;
-               maxParameterCount = 0;
-               maxDataCount = 4096;
-               maxSetupCount = (byte)0x00;
-       }
+    Trans2GetDfsReferral( String filename ) {
+        path = filename;
+        command = SMB_COM_TRANSACTION2;
+        subCommand = TRANS2_GET_DFS_REFERRAL;
+        totalDataCount = 0;
+        maxParameterCount = 0;
+        maxDataCount = 4096;
+        maxSetupCount = (byte)0x00;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = subCommand;
-               dst[dstIndex++] = (byte)0x00;
-               return 2;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = subCommand;
+        dst[dstIndex++] = (byte)0x00;
+        return 2;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               writeInt2( maxReferralLevel, dst, dstIndex );
-               dstIndex += 2;
-               dstIndex += writeString( path, dst, dstIndex );
+        writeInt2( maxReferralLevel, dst, dstIndex );
+        dstIndex += 2;
+        dstIndex += writeString( path, dst, dstIndex );
 
-               return dstIndex - start;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "Trans2GetDfsReferral[" + super.toString() +
-                       ",maxReferralLevel=0x" + maxReferralLevel +
-                       ",filename=" + path + "]" );
-       }
+        return dstIndex - start;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "Trans2GetDfsReferral[" + super.toString() +
+            ",maxReferralLevel=0x" + maxReferralLevel +
+            ",filename=" + path + "]" );
+    }
 }
index 9c51f33..7314c80 100644 (file)
@@ -22,118 +22,122 @@ import java.util.Date;
 
 class Trans2GetDfsReferralResponse extends SmbComTransactionResponse {
 
-       class Referral {
-               int version;
-               int size;
-               int serverType;
-               int flags;
-               int proximity;
-               int ttl;
-               int pathOffset;
-               int altPathOffset;
-               int nodeOffset;
-               String path;
-               String altPath;
-               String node;
-
-               int readWireFormat( byte[] buffer, int bufferIndex, int len ) {
-                       int start = bufferIndex;
-
-                       version = readInt2( buffer, bufferIndex );
+    class Referral {
+        private int version;
+        private int size;
+        private int serverType;
+        private int flags;
+        private int proximity;
+        private int ttl;
+        private int pathOffset;
+        private int altPathOffset;
+        private int nodeOffset;
+        private String path = null;
+        private String altPath;
+
+        String node;
+
+        int readWireFormat( byte[] buffer, int bufferIndex, int len ) {
+            int start = bufferIndex;
+
+            version = readInt2( buffer, bufferIndex );
 if( version != 3 && version != 1 ) {
-       throw new RuntimeException( "Version " + version + " referral not supported. Please report this to jcifs at samba dot org." );
+    throw new RuntimeException( "Version " + version + " referral not supported. Please report this to jcifs at samba dot org." );
 }
-                       bufferIndex += 2;
-                       size = readInt2( buffer, bufferIndex );
-                       bufferIndex += 2;
-                       serverType = readInt2( buffer, bufferIndex );
-                       bufferIndex += 2;
-                       flags = readInt2( buffer, bufferIndex );
-                       bufferIndex += 2;
-                       if( version == 3 ) {
-                               proximity = readInt2( buffer, bufferIndex );
-                               bufferIndex += 2;
-                               ttl = readInt2( buffer, bufferIndex );
-                               bufferIndex += 2;
-                               pathOffset = readInt2( buffer, bufferIndex );
-                               bufferIndex += 2;
-                               altPathOffset = readInt2( buffer, bufferIndex );
-                               bufferIndex += 2;
-                               nodeOffset = readInt2( buffer, bufferIndex );
-                               bufferIndex += 2;
-
-                               path = readString( buffer, start + pathOffset, len, (flags2 & FLAGS2_UNICODE) != 0);
-                               node = readString( buffer, start + nodeOffset, len, (flags2 & FLAGS2_UNICODE) != 0);
-                       } else if( version == 1 ) {
-                               node = readString( buffer, bufferIndex, len, (flags2 & FLAGS2_UNICODE) != 0);
-                       }
-
-                       return size;
-               }
-
-               public String toString() {
-                       return new String( "Referral[" +
-                               "version=" + version + ",size=" + size +
-                               ",serverType=" + serverType + ",flags=" + flags +
-                               ",proximity=" + proximity + ",ttl=" + ttl +
-                               ",pathOffset=" + pathOffset + ",altPathOffset=" + altPathOffset +
-                               ",nodeOffset=" + nodeOffset + ",path=" + path + ",altPath=" + altPath +
-                               ",node=" + node + "]" );
-               }
-       }
-
-       int pathConsumed;
-       int numReferrals;
-       int flags;
-       Referral referral;
-
-       Trans2GetDfsReferralResponse() {
-               subCommand = SmbComTransaction.TRANS2_GET_DFS_REFERRAL;
-       }
-
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               int start = bufferIndex;
-
-               pathConsumed = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-                       /* Samba 2.2.8a will reply with Unicode paths even though
-                        * ASCII is negotiated so we must use flags2 (probably
-                        * should anyway).
-                        */
-               if((flags2 & FLAGS2_UNICODE) != 0) {
-                       pathConsumed /= 2;
-               }
-               numReferrals = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               flags = readInt2( buffer, bufferIndex );
-               bufferIndex += 4;
-
-               referral = new Referral();
-               while( numReferrals-- > 0 ) { 
-                       bufferIndex += referral.readWireFormat( buffer, bufferIndex, len );
-               }
-
-               return bufferIndex - start;
-       }
-       public String toString() {
-               return new String( "Trans2GetDfsReferralResponse[" +
-                       super.toString() + ",pathConsumed=" + pathConsumed +
-                       ",numReferrals=" + numReferrals + ",flags=" + flags +
-                       "," + referral + "]" );
-       }
+            bufferIndex += 2;
+            size = readInt2( buffer, bufferIndex );
+            bufferIndex += 2;
+            serverType = readInt2( buffer, bufferIndex );
+            bufferIndex += 2;
+            flags = readInt2( buffer, bufferIndex );
+            bufferIndex += 2;
+            if( version == 3 ) {
+                proximity = readInt2( buffer, bufferIndex );
+                bufferIndex += 2;
+                ttl = readInt2( buffer, bufferIndex );
+                bufferIndex += 2;
+                pathOffset = readInt2( buffer, bufferIndex );
+                bufferIndex += 2;
+                altPathOffset = readInt2( buffer, bufferIndex );
+                bufferIndex += 2;
+                nodeOffset = readInt2( buffer, bufferIndex );
+                bufferIndex += 2;
+
+                path = readString( buffer, start + pathOffset, len, (flags2 & FLAGS2_UNICODE) != 0);
+                node = readString( buffer, start + nodeOffset, len, (flags2 & FLAGS2_UNICODE) != 0);
+            } else if( version == 1 ) {
+                node = readString( buffer, bufferIndex, len, (flags2 & FLAGS2_UNICODE) != 0);
+            }
+
+            return size;
+        }
+
+        public String toString() {
+            return new String( "Referral[" +
+                "version=" + version + ",size=" + size +
+                ",serverType=" + serverType + ",flags=" + flags +
+                ",proximity=" + proximity + ",ttl=" + ttl +
+                ",pathOffset=" + pathOffset + ",altPathOffset=" + altPathOffset +
+                ",nodeOffset=" + nodeOffset + ",path=" + path + ",altPath=" + altPath +
+                ",node=" + node + "]" );
+        }
+    }
+
+    int pathConsumed;
+    int numReferrals;
+    int flags;
+    Referral referral;
+
+    Trans2GetDfsReferralResponse() {
+        subCommand = SmbComTransaction.TRANS2_GET_DFS_REFERRAL;
+    }
+
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        int start = bufferIndex;
+
+        pathConsumed = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+            /* Samba 2.2.8a will reply with Unicode paths even though
+             * ASCII is negotiated so we must use flags2 (probably
+             * should anyway).
+             */
+        if((flags2 & FLAGS2_UNICODE) != 0) {
+            pathConsumed /= 2;
+        }
+        numReferrals = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        flags = readInt2( buffer, bufferIndex );
+        bufferIndex += 4;
+
+        referral = new Referral();
+        while( numReferrals-- > 0 ) { 
+            bufferIndex += referral.readWireFormat( buffer, bufferIndex, len );
+        }
+        if (referral.path != null && referral.path.charAt( pathConsumed - 1 ) == '\\' ) {
+            pathConsumed--;
+        }
+
+        return bufferIndex - start;
+    }
+    public String toString() {
+        return new String( "Trans2GetDfsReferralResponse[" +
+            super.toString() + ",pathConsumed=" + pathConsumed +
+            ",numReferrals=" + numReferrals + ",flags=" + flags +
+            "," + referral + "]" );
+    }
 }
index 0c860f3..c3ec7ff 100644 (file)
 
 package jcifs.smb;
 
+import jcifs.util.Hexdump;
+
 class Trans2QueryFSInformation extends SmbComTransaction {
 
-       int informationLevel;
+    private int informationLevel;
 
-       Trans2QueryFSInformation( int informationLevel ) {
-               command = SMB_COM_TRANSACTION2;
-               subCommand = TRANS2_QUERY_FS_INFORMATION;
-               this.informationLevel = informationLevel;
-               totalParameterCount = 2;
-               totalDataCount = 0;
-               maxParameterCount = 0;
-               maxDataCount = 800;
-               maxSetupCount = 0;
-       }
+    Trans2QueryFSInformation( int informationLevel ) {
+        command = SMB_COM_TRANSACTION2;
+        subCommand = TRANS2_QUERY_FS_INFORMATION;
+        this.informationLevel = informationLevel;
+        totalParameterCount = 2;
+        totalDataCount = 0;
+        maxParameterCount = 0;
+        maxDataCount = 800;
+        maxSetupCount = 0;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = subCommand;
-               dst[dstIndex++] = (byte)0x00;
-               return 2;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = subCommand;
+        dst[dstIndex++] = (byte)0x00;
+        return 2;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               writeInt2( informationLevel, dst, dstIndex );
-               dstIndex += 2;
+        writeInt2( informationLevel, dst, dstIndex );
+        dstIndex += 2;
 
-               /* windows98 has what appears to be another 4 0's followed by the share
-                * name as a zero terminated ascii string "\TMP" + '\0'
-                *
-                * As is this works, but it deviates from the spec section 4.1.6.6 but
-                * maybe I should put it in. Wonder what NT does?
-                */
+        /* windows98 has what appears to be another 4 0's followed by the share
+         * name as a zero terminated ascii string "\TMP" + '\0'
+         *
+         * As is this works, but it deviates from the spec section 4.1.6.6 but
+         * maybe I should put it in. Wonder what NT does?
+         */
 
-               return dstIndex - start;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "Trans2QueryFSInformation[" + super.toString() +
-                       ",informationLevel=0x" + Log.getHexString( informationLevel, 3 ) + "]" );
-       }
+        return dstIndex - start;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "Trans2QueryFSInformation[" + super.toString() +
+            ",informationLevel=0x" + Hexdump.toHexString( informationLevel, 3 ) + "]" );
+    }
 }
index 5f31222..5d11e16 100644 (file)
@@ -22,115 +22,116 @@ import java.io.UnsupportedEncodingException;
 
 class Trans2QueryFSInformationResponse extends SmbComTransactionResponse {
 
-       // information levels
-       static final int SMB_INFO_ALLOCATION = 1;
-       static final int SMB_QUERY_FS_SIZE_INFO = 0x103;
-
-       class SmbInfoAllocation implements AllocInfo {
-               long alloc;                  // Also handles SmbQueryFSSizeInfo
-               long free;
-               int sectPerAlloc;
-               int bytesPerSect;
-
-               public long getCapacity() {
-                       return alloc * sectPerAlloc * bytesPerSect;
-               }
-               public long getFree() {
-                       return free * sectPerAlloc * bytesPerSect;
-               }
-               public String toString() {
-                       return new String( "SmbInfoAllocation[" +
-                               "alloc=" + alloc + ",free=" + free +
-                               ",sectPerAlloc=" + sectPerAlloc +
-                               ",bytesPerSect=" + bytesPerSect + "]" );
-               }
-       }
-
-       int informationLevel;
-       AllocInfo info;
-
-       Trans2QueryFSInformationResponse( int informationLevel ) {
-               this.informationLevel = informationLevel;
-               command = SMB_COM_TRANSACTION2;
-               subCommand = SmbComTransaction.TRANS2_QUERY_FS_INFORMATION;
-       }
-
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               switch( informationLevel ) {
-                       case SMB_INFO_ALLOCATION:
-                               return readSmbInfoAllocationWireFormat( buffer, bufferIndex );
-                       case SMB_QUERY_FS_SIZE_INFO:
-                               return readSmbQueryFSSizeInfoWireFormat( buffer, bufferIndex );
-                       default:
-                               return 0;
-               }
-       }
-
-       int readSmbInfoAllocationWireFormat( byte[] buffer, int bufferIndex ) {
-               int start = bufferIndex;
-
-               SmbInfoAllocation info = new SmbInfoAllocation();
-
-               bufferIndex += 4; // skip idFileSystem
-
-               info.sectPerAlloc = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-
-               info.alloc = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-
-               info.free = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-
-               info.bytesPerSect = readInt2( buffer, bufferIndex );
-               bufferIndex += 4;
-
-               this.info = info;
-
-               return bufferIndex - start;
-       }
-       int readSmbQueryFSSizeInfoWireFormat( byte[] buffer, int bufferIndex ) {
-               int start = bufferIndex;
-
-               SmbInfoAllocation info = new SmbInfoAllocation();
-
-               info.alloc = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-               info.alloc |= readInt4( buffer, bufferIndex ) << 32L;
-               bufferIndex += 4;
-
-               info.free = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-               info.free |= readInt4( buffer, bufferIndex ) << 32L;
-               bufferIndex += 4;
-
-               info.sectPerAlloc = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-
-               info.bytesPerSect = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-
-               this.info = info;
-
-               return bufferIndex - start;
-       }
-       public String toString() {
-               return new String( "Trans2QueryFSInformationResponse[" +
-                       super.toString() + "]" );
-       }
+    // information levels
+    static final int SMB_INFO_ALLOCATION = 1;
+    static final int SMB_QUERY_FS_SIZE_INFO = 0x103;
+
+    class SmbInfoAllocation implements AllocInfo {
+        long alloc;                  // Also handles SmbQueryFSSizeInfo
+        long free;
+        int sectPerAlloc;
+        int bytesPerSect;
+
+        public long getCapacity() {
+            return alloc * sectPerAlloc * bytesPerSect;
+        }
+        public long getFree() {
+            return free * sectPerAlloc * bytesPerSect;
+        }
+        public String toString() {
+            return new String( "SmbInfoAllocation[" +
+                "alloc=" + alloc + ",free=" + free +
+                ",sectPerAlloc=" + sectPerAlloc +
+                ",bytesPerSect=" + bytesPerSect + "]" );
+        }
+    }
+
+    private int informationLevel;
+
+    AllocInfo info;
+
+    Trans2QueryFSInformationResponse( int informationLevel ) {
+        this.informationLevel = informationLevel;
+        command = SMB_COM_TRANSACTION2;
+        subCommand = SmbComTransaction.TRANS2_QUERY_FS_INFORMATION;
+    }
+
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        switch( informationLevel ) {
+            case SMB_INFO_ALLOCATION:
+                return readSmbInfoAllocationWireFormat( buffer, bufferIndex );
+            case SMB_QUERY_FS_SIZE_INFO:
+                return readSmbQueryFSSizeInfoWireFormat( buffer, bufferIndex );
+            default:
+                return 0;
+        }
+    }
+
+    int readSmbInfoAllocationWireFormat( byte[] buffer, int bufferIndex ) {
+        int start = bufferIndex;
+
+        SmbInfoAllocation info = new SmbInfoAllocation();
+
+        bufferIndex += 4; // skip idFileSystem
+
+        info.sectPerAlloc = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+
+        info.alloc = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+
+        info.free = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+
+        info.bytesPerSect = readInt2( buffer, bufferIndex );
+        bufferIndex += 4;
+
+        this.info = info;
+
+        return bufferIndex - start;
+    }
+    int readSmbQueryFSSizeInfoWireFormat( byte[] buffer, int bufferIndex ) {
+        int start = bufferIndex;
+
+        SmbInfoAllocation info = new SmbInfoAllocation();
+
+        info.alloc = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+        info.alloc |= readInt4( buffer, bufferIndex ) << 32L;
+        bufferIndex += 4;
+
+        info.free = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+        info.free |= readInt4( buffer, bufferIndex ) << 32L;
+        bufferIndex += 4;
+
+        info.sectPerAlloc = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+
+        info.bytesPerSect = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+
+        this.info = info;
+
+        return bufferIndex - start;
+    }
+    public String toString() {
+        return new String( "Trans2QueryFSInformationResponse[" +
+            super.toString() + "]" );
+    }
 }
index 1432e05..37cc5d3 100644 (file)
 
 package jcifs.smb;
 
+import jcifs.util.Hexdump;
+
 class Trans2QueryPathInformation extends SmbComTransaction {
 
-       int informationLevel;
+    private int informationLevel;
 
-       Trans2QueryPathInformation( String filename, int informationLevel ) {
-               path = filename;
-               this.informationLevel = informationLevel;
-               command = SMB_COM_TRANSACTION2;
-               subCommand = TRANS2_QUERY_PATH_INFORMATION;
-               totalDataCount = 0;
-               maxParameterCount = 2;
-               maxDataCount = 40;
-               maxSetupCount = (byte)0x00;
-       }
+    Trans2QueryPathInformation( String filename, int informationLevel ) {
+        path = filename;
+        this.informationLevel = informationLevel;
+        command = SMB_COM_TRANSACTION2;
+        subCommand = TRANS2_QUERY_PATH_INFORMATION;
+        totalDataCount = 0;
+        maxParameterCount = 2;
+        maxDataCount = 40;
+        maxSetupCount = (byte)0x00;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = subCommand;
-               dst[dstIndex++] = (byte)0x00;
-               return 2;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = subCommand;
+        dst[dstIndex++] = (byte)0x00;
+        return 2;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               writeInt2( informationLevel, dst, dstIndex );
-               dstIndex += 2;
-               dst[dstIndex++] = (byte)0x00;
-               dst[dstIndex++] = (byte)0x00;
-               dst[dstIndex++] = (byte)0x00;
-               dst[dstIndex++] = (byte)0x00;
-               dstIndex += writeString( path, dst, dstIndex );
+        writeInt2( informationLevel, dst, dstIndex );
+        dstIndex += 2;
+        dst[dstIndex++] = (byte)0x00;
+        dst[dstIndex++] = (byte)0x00;
+        dst[dstIndex++] = (byte)0x00;
+        dst[dstIndex++] = (byte)0x00;
+        dstIndex += writeString( path, dst, dstIndex );
 
-               return dstIndex - start;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "Trans2QueryPathInformation[" + super.toString() +
-                       ",informationLevel=0x" + Log.getHexString( informationLevel, 3 ) +
-                       ",filename=" + path + "]" );
-       }
+        return dstIndex - start;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "Trans2QueryPathInformation[" + super.toString() +
+            ",informationLevel=0x" + Hexdump.toHexString( informationLevel, 3 ) +
+            ",filename=" + path + "]" );
+    }
 }
index a78e667..8c4d041 100644 (file)
 package jcifs.smb;
 
 import java.util.Date;
+import jcifs.util.Hexdump;
 
 class Trans2QueryPathInformationResponse extends SmbComTransactionResponse {
 
-       // information levels
-       static final int SMB_QUERY_FILE_BASIC_INFO    = 0x101;
-       static final int SMB_QUERY_FILE_STANDARD_INFO = 0x102;
+    // information levels
+    static final int SMB_QUERY_FILE_BASIC_INFO    = 0x101;
+    static final int SMB_QUERY_FILE_STANDARD_INFO = 0x102;
 
-       class SmbQueryFileBasicInfo implements Info {
-               long createTime;
-               long lastAccessTime;
-               long lastWriteTime;
-               long changeTime;
-               int attributes;
+    class SmbQueryFileBasicInfo implements Info {
+        long createTime;
+        long lastAccessTime;
+        long lastWriteTime;
+        long changeTime;
+        int attributes;
 
-               public int getAttributes() {
-                       return attributes;
-               }
-               public long getCreateTime() {
-                       return createTime;
-               }
-               public long getLastWriteTime() {
-                       return lastWriteTime;
-               }
-               public long getSize() {
-                       return 0L;
-               }
-               public String toString() {
-                       return new String( "SmbQueryFileBasicInfo[" +
-                               "createTime=" + new Date( createTime ) +
-                               ",lastAccessTime=" + new Date( lastAccessTime ) +
-                               ",lastWriteTime=" + new Date( lastWriteTime ) +
-                               ",changeTime=" + new Date( changeTime ) +
-                               ",attributes=0x" + Log.getHexString( attributes, 4 ) + "]" );
-               }
-       }
-       class SmbQueryFileStandardInfo implements Info {
-               long allocationSize;
-               long endOfFile;
-               int numberOfLinks;
-               boolean deletePending;
-               boolean directory;
+        public int getAttributes() {
+            return attributes;
+        }
+        public long getCreateTime() {
+            return createTime;
+        }
+        public long getLastWriteTime() {
+            return lastWriteTime;
+        }
+        public long getSize() {
+            return 0L;
+        }
+        public String toString() {
+            return new String( "SmbQueryFileBasicInfo[" +
+                "createTime=" + new Date( createTime ) +
+                ",lastAccessTime=" + new Date( lastAccessTime ) +
+                ",lastWriteTime=" + new Date( lastWriteTime ) +
+                ",changeTime=" + new Date( changeTime ) +
+                ",attributes=0x" + Hexdump.toHexString( attributes, 4 ) + "]" );
+        }
+    }
+    class SmbQueryFileStandardInfo implements Info {
+        long allocationSize;
+        long endOfFile;
+        int numberOfLinks;
+        boolean deletePending;
+        boolean directory;
 
-               public int getAttributes() {
-                       return 0;
-               }
-               public long getCreateTime() {
-                       return 0L;
-               }
-               public long getLastWriteTime() {
-                       return 0L;
-               }
-               public long getSize() {
-                       return endOfFile;
-               }
-               public String toString() {
-                       return new String( "SmbQueryInfoStandard[" +
-                               "allocationSize=" + allocationSize +
-                               ",endOfFile=" + endOfFile +
-                               ",numberOfLinks=" + numberOfLinks +
-                               ",deletePending=" + deletePending +
-                               ",directory=" + directory + "]" );
-               }
-       }
+        public int getAttributes() {
+            return 0;
+        }
+        public long getCreateTime() {
+            return 0L;
+        }
+        public long getLastWriteTime() {
+            return 0L;
+        }
+        public long getSize() {
+            return endOfFile;
+        }
+        public String toString() {
+            return new String( "SmbQueryInfoStandard[" +
+                "allocationSize=" + allocationSize +
+                ",endOfFile=" + endOfFile +
+                ",numberOfLinks=" + numberOfLinks +
+                ",deletePending=" + deletePending +
+                ",directory=" + directory + "]" );
+        }
+    }
 
-       int informationLevel;
-       Info info;
+    private int informationLevel;
 
-       Trans2QueryPathInformationResponse( int informationLevel ) {
-               this.informationLevel = informationLevel;
-               subCommand = SmbComTransaction.TRANS2_QUERY_PATH_INFORMATION;
-       }
+    Info info;
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               // observed two zero bytes here with at least win98
-               return 2;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               switch( informationLevel ) {
-                       case SMB_QUERY_FILE_BASIC_INFO:
-                               return readSmbQueryFileBasicInfoWireFormat( buffer, bufferIndex );
-                       case SMB_QUERY_FILE_STANDARD_INFO:
-                               return readSmbQueryFileStandardInfoWireFormat( buffer, bufferIndex );
-                       default:
-                               return 0;
-               }
-       }
-       int readSmbQueryFileStandardInfoWireFormat( byte[] buffer, int bufferIndex ) {
-               int start = bufferIndex;
+    Trans2QueryPathInformationResponse( int informationLevel ) {
+        this.informationLevel = informationLevel;
+        subCommand = SmbComTransaction.TRANS2_QUERY_PATH_INFORMATION;
+    }
 
-               SmbQueryFileStandardInfo info = new SmbQueryFileStandardInfo();
-               info.allocationSize = readLong( buffer, bufferIndex );
-               bufferIndex += 8;
-               info.endOfFile = readLong( buffer, bufferIndex );
-               bufferIndex += 8;
-               info.numberOfLinks = readInt4( buffer, bufferIndex );
-               bufferIndex += 4;
-               info.deletePending = ( buffer[bufferIndex++] & 0xFF ) > 0;
-               info.directory = ( buffer[bufferIndex++] & 0xFF ) > 0;
-               this.info = info;
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        // observed two zero bytes here with at least win98
+        return 2;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        switch( informationLevel ) {
+            case SMB_QUERY_FILE_BASIC_INFO:
+                return readSmbQueryFileBasicInfoWireFormat( buffer, bufferIndex );
+            case SMB_QUERY_FILE_STANDARD_INFO:
+                return readSmbQueryFileStandardInfoWireFormat( buffer, bufferIndex );
+            default:
+                return 0;
+        }
+    }
+    int readSmbQueryFileStandardInfoWireFormat( byte[] buffer, int bufferIndex ) {
+        int start = bufferIndex;
 
-               return bufferIndex - start;
-       }
-       int readSmbQueryFileBasicInfoWireFormat( byte[] buffer, int bufferIndex ) {
-               int start = bufferIndex;
+        SmbQueryFileStandardInfo info = new SmbQueryFileStandardInfo();
+        info.allocationSize = readInt8( buffer, bufferIndex );
+        bufferIndex += 8;
+        info.endOfFile = readInt8( buffer, bufferIndex );
+        bufferIndex += 8;
+        info.numberOfLinks = readInt4( buffer, bufferIndex );
+        bufferIndex += 4;
+        info.deletePending = ( buffer[bufferIndex++] & 0xFF ) > 0;
+        info.directory = ( buffer[bufferIndex++] & 0xFF ) > 0;
+        this.info = info;
 
-               SmbQueryFileBasicInfo info = new SmbQueryFileBasicInfo();
-               info.createTime = readTime( buffer, bufferIndex );
-               bufferIndex += 8;
-               info.lastAccessTime = readTime( buffer, bufferIndex );
-               bufferIndex += 8;
-               info.lastWriteTime = readTime( buffer, bufferIndex );
-               bufferIndex += 8;
-               info.changeTime = readTime( buffer, bufferIndex );
-               bufferIndex += 8;
-               info.attributes = readInt2( buffer, bufferIndex );
-               bufferIndex += 2;
-               this.info = info;
+        return bufferIndex - start;
+    }
+    int readSmbQueryFileBasicInfoWireFormat( byte[] buffer, int bufferIndex ) {
+        int start = bufferIndex;
 
-               return bufferIndex - start;
-       }
-       public String toString() {
-               return new String( "Trans2QueryPathInformationResponse[" +
-                       super.toString() + "]" );
-       }
+        SmbQueryFileBasicInfo info = new SmbQueryFileBasicInfo();
+        info.createTime = readTime( buffer, bufferIndex );
+        bufferIndex += 8;
+        info.lastAccessTime = readTime( buffer, bufferIndex );
+        bufferIndex += 8;
+        info.lastWriteTime = readTime( buffer, bufferIndex );
+        bufferIndex += 8;
+        info.changeTime = readTime( buffer, bufferIndex );
+        bufferIndex += 8;
+        info.attributes = readInt2( buffer, bufferIndex );
+        bufferIndex += 2;
+        this.info = info;
+
+        return bufferIndex - start;
+    }
+    public String toString() {
+        return new String( "Trans2QueryPathInformationResponse[" +
+            super.toString() + "]" );
+    }
 }
index ff0975a..08a3017 100644 (file)
@@ -20,70 +20,70 @@ package jcifs.smb;
 
 class Trans2SetFileInformation extends SmbComTransaction {
 
-       static final int SMB_FILE_BASIC_INFO = 0x101;
+    static final int SMB_FILE_BASIC_INFO = 0x101;
 
-       int fid;
-       int attributes;
-       long createTime, lastWriteTime;
+    private int fid;
+    private int attributes;
+    private long createTime, lastWriteTime;
 
-       Trans2SetFileInformation( int fid, int attributes, long createTime, long lastWriteTime ) {
-               this.fid = fid;
-               this.attributes = attributes;
-               this.createTime = createTime;
-               this.lastWriteTime = lastWriteTime;
-               command = SMB_COM_TRANSACTION2;
-               subCommand = TRANS2_SET_FILE_INFORMATION;
-               maxParameterCount = 6;
-               maxDataCount = 0;
-               maxSetupCount = (byte)0x00;
-       }
+    Trans2SetFileInformation( int fid, int attributes, long createTime, long lastWriteTime ) {
+        this.fid = fid;
+        this.attributes = attributes;
+        this.createTime = createTime;
+        this.lastWriteTime = lastWriteTime;
+        command = SMB_COM_TRANSACTION2;
+        subCommand = TRANS2_SET_FILE_INFORMATION;
+        maxParameterCount = 6;
+        maxDataCount = 0;
+        maxSetupCount = (byte)0x00;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = subCommand;
-               dst[dstIndex++] = (byte)0x00;
-               return 2;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = subCommand;
+        dst[dstIndex++] = (byte)0x00;
+        return 2;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               writeInt2( fid, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( SMB_FILE_BASIC_INFO, dst, dstIndex );
-               dstIndex += 2;
-               writeInt2( 0, dst, dstIndex );
-               dstIndex += 2;
+        writeInt2( fid, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( SMB_FILE_BASIC_INFO, dst, dstIndex );
+        dstIndex += 2;
+        writeInt2( 0, dst, dstIndex );
+        dstIndex += 2;
 
-               return dstIndex - start;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               int start = dstIndex;
+        return dstIndex - start;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        int start = dstIndex;
 
-               writeTime( createTime, dst, dstIndex ); dstIndex += 8;
-               writeInt8( 0L, dst, dstIndex ); dstIndex += 8;
-               writeTime( lastWriteTime, dst, dstIndex ); dstIndex += 8;
-               writeInt8( 0L, dst, dstIndex ); dstIndex += 8;
+        writeTime( createTime, dst, dstIndex ); dstIndex += 8;
+        writeInt8( 0L, dst, dstIndex ); dstIndex += 8;
+        writeTime( lastWriteTime, dst, dstIndex ); dstIndex += 8;
+        writeInt8( 0L, dst, dstIndex ); dstIndex += 8;
 /* Samba 2.2.7 needs ATTR_NORMAL
  */
-               writeInt2( 0x80 | attributes, dst, dstIndex ); dstIndex += 2; 
-                                                                               /* 6 zeros observed with NT */
-               writeInt8( 0L, dst, dstIndex ); dstIndex += 6;
+        writeInt2( 0x80 | attributes, dst, dstIndex ); dstIndex += 2; 
+                                        /* 6 zeros observed with NT */
+        writeInt8( 0L, dst, dstIndex ); dstIndex += 6;
 
-                               /* Also observed 4 byte alignment but we stick
-                                * with the default for jCIFS which is 2 */
+                /* Also observed 4 byte alignment but we stick
+                 * with the default for jCIFS which is 2 */
 
-               return dstIndex - start;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "Trans2SetFileInformation[" + super.toString() +
-                       ",fid=" + fid + "]" );
-       }
+        return dstIndex - start;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "Trans2SetFileInformation[" + super.toString() +
+            ",fid=" + fid + "]" );
+    }
 }
index 503191a..c67e892 100644 (file)
@@ -20,30 +20,30 @@ package jcifs.smb;
 
 class Trans2SetFileInformationResponse extends SmbComTransactionResponse {
 
-       Trans2SetFileInformationResponse() {
-               subCommand = SmbComTransaction.TRANS2_SET_FILE_INFORMATION;
-       }
+    Trans2SetFileInformationResponse() {
+        subCommand = SmbComTransaction.TRANS2_SET_FILE_INFORMATION;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "Trans2SetFileInformationResponse[" +
-                       super.toString() + "]" );
-       }
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "Trans2SetFileInformationResponse[" +
+            super.toString() + "]" );
+    }
 }
index daaec80..6a838e1 100644 (file)
@@ -20,54 +20,54 @@ package jcifs.smb;
 
 class TransCallNamedPipe extends SmbComTransaction {
 
-       byte[] pipeData;
-       int pipeDataOff, pipeDataLen;
+    private byte[] pipeData;
+    private int pipeDataOff, pipeDataLen;
 
-       TransCallNamedPipe( String pipeName, byte[] data, int off, int len ) {
-               name = pipeName;
-               pipeData = data;
-               pipeDataOff = off;
-               pipeDataLen = len;
-               command = SMB_COM_TRANSACTION;
-               subCommand = TRANS_CALL_NAMED_PIPE;
-               timeout = 0xFFFFFFFF;
-               maxParameterCount = 0;
-               maxDataCount = 0xFFFF;
-               maxSetupCount = (byte)0x00;
-               setupCount = 2;
-       }
+    TransCallNamedPipe( String pipeName, byte[] data, int off, int len ) {
+        name = pipeName;
+        pipeData = data;
+        pipeDataOff = off;
+        pipeDataLen = len;
+        command = SMB_COM_TRANSACTION;
+        subCommand = TRANS_CALL_NAMED_PIPE;
+        timeout = 0xFFFFFFFF;
+        maxParameterCount = 0;
+        maxDataCount = 0xFFFF;
+        maxSetupCount = (byte)0x00;
+        setupCount = 2;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = subCommand;
-               dst[dstIndex++] = (byte)0x00;
-               // this says "Transaction priority" in netmon
-               dst[dstIndex++] = (byte)0x00; // no FID
-               dst[dstIndex++] = (byte)0x00;
-               return 4;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               if(( dst.length - dstIndex ) < pipeDataLen ) {
-                       Log.println( Log.WARNINGS, "smb warning",
-                                                       "TransCallNamedPipe data too long for buffer" );
-                       return 0;
-               }
-               System.arraycopy( pipeData, pipeDataOff, dst, dstIndex, pipeDataLen );
-               return pipeDataLen;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "TransCallNamedPipe[" + super.toString() +
-                       ",pipeName=" + name + "]" );
-       }
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = subCommand;
+        dst[dstIndex++] = (byte)0x00;
+        // this says "Transaction priority" in netmon
+        dst[dstIndex++] = (byte)0x00; // no FID
+        dst[dstIndex++] = (byte)0x00;
+        return 4;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        if(( dst.length - dstIndex ) < pipeDataLen ) {
+            if( log.level > 2 )
+                log.println( "TransCallNamedPipe data too long for buffer" );
+            return 0;
+        }
+        System.arraycopy( pipeData, pipeDataOff, dst, dstIndex, pipeDataLen );
+        return pipeDataLen;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "TransCallNamedPipe[" + super.toString() +
+            ",pipeName=" + name + "]" );
+    }
 }
index 661ff77..dbffa44 100644 (file)
@@ -20,38 +20,38 @@ package jcifs.smb;
 
 class TransCallNamedPipeResponse extends SmbComTransactionResponse {
 
-       SmbNamedPipe pipe;
+    private SmbNamedPipe pipe;
 
-       TransCallNamedPipeResponse( SmbNamedPipe pipe ) {
-               this.pipe = pipe;
-       }
+    TransCallNamedPipeResponse( SmbNamedPipe pipe ) {
+        this.pipe = pipe;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               if( pipe.pipeIn != null ) {
-                       TransactNamedPipeInputStream in = (TransactNamedPipeInputStream)pipe.pipeIn;
-                       synchronized( in.lock ) {
-                               in.receive( buffer, bufferIndex, len );
-                               in.lock.notify();
-                       }
-               }
-               return len;
-       }
-       public String toString() {
-               return new String( "TransCallNamedPipeResponse[" + super.toString() + "]" );
-       }
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        if( pipe.pipeIn != null ) {
+            TransactNamedPipeInputStream in = (TransactNamedPipeInputStream)pipe.pipeIn;
+            synchronized( in.lock ) {
+                in.receive( buffer, bufferIndex, len );
+                in.lock.notify();
+            }
+        }
+        return len;
+    }
+    public String toString() {
+        return new String( "TransCallNamedPipeResponse[" + super.toString() + "]" );
+    }
 }
index fb712fb..5ed7f90 100644 (file)
@@ -20,44 +20,44 @@ package jcifs.smb;
 
 class TransPeekNamedPipe extends SmbComTransaction {
 
-       int fid;
+    private int fid;
 
-       TransPeekNamedPipe( String pipeName, int fid ) {
-               name = pipeName;
-               this.fid = fid;
-               command = SMB_COM_TRANSACTION;
-               subCommand = TRANS_PEEK_NAMED_PIPE;
-               timeout = 0xFFFFFFFF;
-               maxParameterCount = 6;
-               maxDataCount = 1;
-               maxSetupCount = (byte)0x00;
-               setupCount = 2;
-       }
+    TransPeekNamedPipe( String pipeName, int fid ) {
+        name = pipeName;
+        this.fid = fid;
+        command = SMB_COM_TRANSACTION;
+        subCommand = TRANS_PEEK_NAMED_PIPE;
+        timeout = 0xFFFFFFFF;
+        maxParameterCount = 6;
+        maxDataCount = 1;
+        maxSetupCount = (byte)0x00;
+        setupCount = 2;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = subCommand;
-               dst[dstIndex++] = (byte)0x00;
-               // this says "Transaction priority" in netmon
-               writeInt2( fid, dst, dstIndex );
-               return 4;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "TransPeekNamedPipe[" + super.toString() +
-                       ",pipeName=" + name + "]" );
-       }
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = subCommand;
+        dst[dstIndex++] = (byte)0x00;
+        // this says "Transaction priority" in netmon
+        writeInt2( fid, dst, dstIndex );
+        return 4;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "TransPeekNamedPipe[" + super.toString() +
+            ",pipeName=" + name + "]" );
+    }
 }
index 5e59af0..8b935da 100644 (file)
@@ -20,40 +20,42 @@ package jcifs.smb;
 
 class TransPeekNamedPipeResponse extends SmbComTransactionResponse {
 
-       static final int STATUS_DISCONNECTED = 1;
-       static final int STATUS_LISTENING = 2;
-       static final int STATUS_CONNECTION_OK = 3;
-       static final int STATUS_SERVER_END_CLOSED = 4;
+    private SmbNamedPipe pipe;
+    private int head;
 
-       SmbNamedPipe pipe;
-       int available, head, status;
+    static final int STATUS_DISCONNECTED = 1;
+    static final int STATUS_LISTENING = 2;
+    static final int STATUS_CONNECTION_OK = 3;
+    static final int STATUS_SERVER_END_CLOSED = 4;
 
-       TransPeekNamedPipeResponse( SmbNamedPipe pipe ) {
-               this.pipe = pipe;
-       }
+    int status, available;
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               available = readInt2( buffer, bufferIndex ); bufferIndex += 2;
-               head = readInt2( buffer, bufferIndex ); bufferIndex += 2;
-               status = readInt2( buffer, bufferIndex );
-               return 6;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "TransPeekNamedPipeResponse[" + super.toString() + "]" );
-       }
+    TransPeekNamedPipeResponse( SmbNamedPipe pipe ) {
+        this.pipe = pipe;
+    }
+
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        available = readInt2( buffer, bufferIndex ); bufferIndex += 2;
+        head = readInt2( buffer, bufferIndex ); bufferIndex += 2;
+        status = readInt2( buffer, bufferIndex );
+        return 6;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "TransPeekNamedPipeResponse[" + super.toString() + "]" );
+    }
 }
index 378658f..b0f1358 100644 (file)
@@ -20,53 +20,53 @@ package jcifs.smb;
 
 class TransTransactNamedPipe extends SmbComTransaction {
 
-       byte[] pipeData;
-       int pipeFid, pipeDataOff, pipeDataLen;
+    private byte[] pipeData;
+    private int pipeFid, pipeDataOff, pipeDataLen;
 
-       TransTransactNamedPipe( int fid, byte[] data, int off, int len ) {
-               pipeFid = fid;
-               pipeData = data;
-               pipeDataOff = off;
-               pipeDataLen = len;
-               command = SMB_COM_TRANSACTION;
-               subCommand = TRANS_TRANSACT_NAMED_PIPE;
-               maxParameterCount = 0;
-               maxDataCount = 0xFFFF;
-               maxSetupCount = (byte)0x00;
-               setupCount = 2;
-               name = "\\PIPE\\";
-       }
+    TransTransactNamedPipe( int fid, byte[] data, int off, int len ) {
+        pipeFid = fid;
+        pipeData = data;
+        pipeDataOff = off;
+        pipeDataLen = len;
+        command = SMB_COM_TRANSACTION;
+        subCommand = TRANS_TRANSACT_NAMED_PIPE;
+        maxParameterCount = 0;
+        maxDataCount = 0xFFFF;
+        maxSetupCount = (byte)0x00;
+        setupCount = 2;
+        name = "\\PIPE\\";
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = subCommand;
-               dst[dstIndex++] = (byte)0x00;
-               writeInt2( pipeFid, dst, dstIndex );
-               dstIndex += 2;
-               return 4;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               if(( dst.length - dstIndex ) < pipeDataLen ) {
-                       Log.println( Log.WARNINGS, "smb warning",
-                                                       "TransTransactNamedPipe data too long for buffer" );
-                       return 0;
-               }
-               System.arraycopy( pipeData, pipeDataOff, dst, dstIndex, pipeDataLen );
-               return pipeDataLen;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "TransTransactNamedPipe[" + super.toString() +
-                       ",pipeFid=" + pipeFid + "]" );
-       }
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = subCommand;
+        dst[dstIndex++] = (byte)0x00;
+        writeInt2( pipeFid, dst, dstIndex );
+        dstIndex += 2;
+        return 4;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        if(( dst.length - dstIndex ) < pipeDataLen ) {
+            if( log.level > 2 )
+                log.println( "TransTransactNamedPipe data too long for buffer" );
+            return 0;
+        }
+        System.arraycopy( pipeData, pipeDataOff, dst, dstIndex, pipeDataLen );
+        return pipeDataLen;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "TransTransactNamedPipe[" + super.toString() +
+            ",pipeFid=" + pipeFid + "]" );
+    }
 }
index 9d91c6c..9dd16d0 100644 (file)
@@ -20,38 +20,38 @@ package jcifs.smb;
 
 class TransTransactNamedPipeResponse extends SmbComTransactionResponse {
 
-       SmbNamedPipe pipe;
+    private SmbNamedPipe pipe;
 
-       TransTransactNamedPipeResponse( SmbNamedPipe pipe ) {
-               this.pipe = pipe;
-       }
+    TransTransactNamedPipeResponse( SmbNamedPipe pipe ) {
+        this.pipe = pipe;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               if( pipe.pipeIn != null ) {
-                       TransactNamedPipeInputStream in = (TransactNamedPipeInputStream)pipe.pipeIn;
-                       synchronized( in.lock ) {
-                               in.receive( buffer, bufferIndex, len );
-                               in.lock.notify();
-                       }
-               }
-               return len;
-       }
-       public String toString() {
-               return new String( "TransTransactNamedPipeResponse[" + super.toString() + "]" );
-       }
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        if( pipe.pipeIn != null ) {
+            TransactNamedPipeInputStream in = (TransactNamedPipeInputStream)pipe.pipeIn;
+            synchronized( in.lock ) {
+                in.receive( buffer, bufferIndex, len );
+                in.lock.notify();
+            }
+        }
+        return len;
+    }
+    public String toString() {
+        return new String( "TransTransactNamedPipeResponse[" + super.toString() + "]" );
+    }
 }
index 365221e..fcc8368 100644 (file)
@@ -20,41 +20,41 @@ package jcifs.smb;
 
 class TransWaitNamedPipe extends SmbComTransaction {
 
-       TransWaitNamedPipe( String pipeName ) {
-               name = pipeName;
-               command = SMB_COM_TRANSACTION;
-               subCommand = TRANS_WAIT_NAMED_PIPE;
-               timeout = 0xFFFFFFFF;
-               maxParameterCount = 0;
-               maxDataCount = 0;
-               maxSetupCount = (byte)0x00;
-               setupCount = 2;
-       }
+    TransWaitNamedPipe( String pipeName ) {
+        name = pipeName;
+        command = SMB_COM_TRANSACTION;
+        subCommand = TRANS_WAIT_NAMED_PIPE;
+        timeout = 0xFFFFFFFF;
+        maxParameterCount = 0;
+        maxDataCount = 0;
+        maxSetupCount = (byte)0x00;
+        setupCount = 2;
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               dst[dstIndex++] = subCommand;
-               dst[dstIndex++] = (byte)0x00;
-               dst[dstIndex++] = (byte)0x00; // no FID
-               dst[dstIndex++] = (byte)0x00;
-               return 4;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "TransWaitNamedPipe[" + super.toString() +
-                       ",pipeName=" + name + "]" );
-       }
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        dst[dstIndex++] = subCommand;
+        dst[dstIndex++] = (byte)0x00;
+        dst[dstIndex++] = (byte)0x00; // no FID
+        dst[dstIndex++] = (byte)0x00;
+        return 4;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "TransWaitNamedPipe[" + super.toString() +
+            ",pipeName=" + name + "]" );
+    }
 }
index 1ab947a..9186286 100644 (file)
@@ -20,30 +20,30 @@ package jcifs.smb;
 
 class TransWaitNamedPipeResponse extends SmbComTransactionResponse {
 
-       // not much to this one is there :~)
+    // not much to this one is there :~)
 
-       TransWaitNamedPipeResponse() {
-       }
+    TransWaitNamedPipeResponse() {
+    }
 
-       int writeSetupWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeParametersWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int writeDataWireFormat( byte[] dst, int dstIndex ) {
-               return 0;
-       }
-       int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
-               return 0;
-       }
-       public String toString() {
-               return new String( "TransWaitNamedPipeResponse[" + super.toString() + "]" );
-       }
+    int writeSetupWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeParametersWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int writeDataWireFormat( byte[] dst, int dstIndex ) {
+        return 0;
+    }
+    int readSetupWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readParametersWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    int readDataWireFormat( byte[] buffer, int bufferIndex, int len ) {
+        return 0;
+    }
+    public String toString() {
+        return new String( "TransWaitNamedPipeResponse[" + super.toString() + "]" );
+    }
 }
index 367f14c..377d678 100644 (file)
@@ -23,108 +23,109 @@ import java.io.IOException;
 
 class TransactNamedPipeInputStream extends InputStream {
 
-       static final int INIT_PIPE_SIZE = 4096;
+    private static final int INIT_PIPE_SIZE = 4096;
 
-       SmbNamedPipe pipe;
-       byte[] pipe_buf = new byte[INIT_PIPE_SIZE];
-       int beg_idx, nxt_idx, used;
-       Object lock;
+    private SmbNamedPipe pipe;
+    private byte[] pipe_buf = new byte[INIT_PIPE_SIZE];
+    private int beg_idx, nxt_idx, used;
 
-       TransactNamedPipeInputStream( SmbNamedPipe pipe ) {
-               this.pipe = pipe;
-               lock = new Object();
-       }
-       public void close() throws IOException {
-               pipe.close();
-       }
-       public int read() throws IOException {
-               int result = -1;
+    Object lock;
 
-               synchronized( lock ) {
-                       try {
-                               while( used == 0 ) {
-                                       lock.wait();
-                               }
-                       } catch( InterruptedException ie ) {
-                               throw new IOException( ie.getMessage() );
-                       }
-                       result = pipe_buf[beg_idx] & 0xFF;
-                       beg_idx = ( beg_idx + 1 ) % pipe_buf.length;
-               }
-               return result;
-       }
-       public int read( byte[] b ) throws IOException {
-               return read( b, 0, b.length );
-       }
-       public int read( byte[] b, int off, int len ) throws IOException {
-               int result = -1;
-               int i;
+    TransactNamedPipeInputStream( SmbNamedPipe pipe ) {
+        this.pipe = pipe;
+        lock = new Object();
+    }
+    public void close() throws IOException {
+        pipe.close();
+    }
+    public int read() throws IOException {
+        int result = -1;
 
-               if( len <= 0 ) {
-                       return 0;
-               }
-               synchronized( lock ) {
-                       try {
-                               while( used == 0 ) {
-                                       lock.wait();
-                               }
-                       } catch( InterruptedException ie ) {
-                               throw new IOException( ie.getMessage() );
-                       }
-                       i = pipe_buf.length - beg_idx;
-                       result = len > used ? used : len;
-                       if( used > i && result > i ) {
-                               System.arraycopy( pipe_buf, beg_idx, b, off, i );
-                               off += i;
-                               System.arraycopy( pipe_buf, 0, b, off, result - i );
-                       } else {
-                               System.arraycopy( pipe_buf, beg_idx, b, off, result );
-                       }
-                       used -= result;
-                       beg_idx = ( beg_idx + result ) % pipe_buf.length;
-               }
-               return result;
-       }
-       public int available() throws IOException {
-               Log.println( Log.WARNINGS, "Named Pipe warning",
-                               "available does not apply to TRANSACT Named Pipes" );
-               return 0;
-       }
-       int receive( byte[] b, int off, int len ) {
-               int i;
+        synchronized( lock ) {
+            try {
+                while( used == 0 ) {
+                    lock.wait();
+                }
+            } catch( InterruptedException ie ) {
+                throw new IOException( ie.getMessage() );
+            }
+            result = pipe_buf[beg_idx] & 0xFF;
+            beg_idx = ( beg_idx + 1 ) % pipe_buf.length;
+        }
+        return result;
+    }
+    public int read( byte[] b ) throws IOException {
+        return read( b, 0, b.length );
+    }
+    public int read( byte[] b, int off, int len ) throws IOException {
+        int result = -1;
+        int i;
 
-               if( len > ( pipe_buf.length - used )) {
-                       byte[] tmp;
-                       int new_size;
+        if( len <= 0 ) {
+            return 0;
+        }
+        synchronized( lock ) {
+            try {
+                while( used == 0 ) {
+                    lock.wait();
+                }
+            } catch( InterruptedException ie ) {
+                throw new IOException( ie.getMessage() );
+            }
+            i = pipe_buf.length - beg_idx;
+            result = len > used ? used : len;
+            if( used > i && result > i ) {
+                System.arraycopy( pipe_buf, beg_idx, b, off, i );
+                off += i;
+                System.arraycopy( pipe_buf, 0, b, off, result - i );
+            } else {
+                System.arraycopy( pipe_buf, beg_idx, b, off, result );
+            }
+            used -= result;
+            beg_idx = ( beg_idx + result ) % pipe_buf.length;
+        }
+        return result;
+    }
+    public int available() throws IOException {
+        if( pipe.log.level > 2 )
+            pipe.log.println( "Named Pipe available() does not apply to TRANSACT Named Pipes" );
+        return 0;
+    }
+    int receive( byte[] b, int off, int len ) {
+        int i;
 
-                       new_size = pipe_buf.length * 2;
-                       if( len > ( new_size - used )) {
-                               new_size = len + used;
-                       }
-                       tmp = pipe_buf;
-                       pipe_buf = new byte[new_size];
-                       i = tmp.length - beg_idx;
-                       if( used > i ) {
-                               System.arraycopy( tmp, beg_idx, pipe_buf, 0, i );
-                               System.arraycopy( tmp, 0, pipe_buf, i, used - i ); 
-                               nxt_idx = used;
-                       } else {
-                               System.arraycopy( tmp, beg_idx, pipe_buf, 0, used );
-                       }
-                       beg_idx = 0;
-                       tmp = null;
-               }
+        if( len > ( pipe_buf.length - used )) {
+            byte[] tmp;
+            int new_size;
 
-               i = pipe_buf.length - nxt_idx;
-               if( len > i ) {
-                       System.arraycopy( b, off, pipe_buf, nxt_idx, i );
-                       off += i;
-                       System.arraycopy( b, off, pipe_buf, 0, len - i ); 
-               } else {
-                       System.arraycopy( b, off, pipe_buf, nxt_idx, len );
-               }
-               nxt_idx = ( nxt_idx + len ) % pipe_buf.length;
-               used += len;
-               return len;
-       }
+            new_size = pipe_buf.length * 2;
+            if( len > ( new_size - used )) {
+                new_size = len + used;
+            }
+            tmp = pipe_buf;
+            pipe_buf = new byte[new_size];
+            i = tmp.length - beg_idx;
+            if( used > i ) {
+                System.arraycopy( tmp, beg_idx, pipe_buf, 0, i );
+                System.arraycopy( tmp, 0, pipe_buf, i, used - i ); 
+                nxt_idx = used;
+            } else {
+                System.arraycopy( tmp, beg_idx, pipe_buf, 0, used );
+            }
+            beg_idx = 0;
+            tmp = null;
+        }
+
+        i = pipe_buf.length - nxt_idx;
+        if( len > i ) {
+            System.arraycopy( b, off, pipe_buf, nxt_idx, i );
+            off += i;
+            System.arraycopy( b, off, pipe_buf, 0, len - i ); 
+        } else {
+            System.arraycopy( b, off, pipe_buf, nxt_idx, len );
+        }
+        nxt_idx = ( nxt_idx + len ) % pipe_buf.length;
+        used += len;
+        return len;
+    }
 }
index c5f8fbc..adfa884 100644 (file)
@@ -23,41 +23,41 @@ import java.io.IOException;
 
 class TransactNamedPipeOutputStream extends OutputStream {
 
-       String path;
-       SmbNamedPipe pipe;
-       byte[] tmp = new byte[1];
-       
-       TransactNamedPipeOutputStream( SmbNamedPipe pipe ) throws IOException {
-               this.pipe = pipe;
-               path = pipe.unc;
-       }
+    private String path;
+    private SmbNamedPipe pipe;
+    private byte[] tmp = new byte[1];
 
-       public void close() throws IOException {
-               pipe.close();
-       }
-       public void write( int b ) throws IOException {
-               tmp[0] = (byte)b;
-               write( tmp, 0, 1 );
-       }
-       public void write( byte[] b ) throws IOException {
-               write( b, 0, b.length );
-       }
-       public void write( byte[] b, int off, int len ) throws IOException {
-               if( len < 0 ) {
-                       len = 0;
-               }
+    TransactNamedPipeOutputStream( SmbNamedPipe pipe ) throws IOException {
+        this.pipe = pipe;
+        path = pipe.unc;
+    }
 
-               if(( pipe.pipeType & SmbNamedPipe.PIPE_TYPE_CALL ) ==
-                                                                                                       SmbNamedPipe.PIPE_TYPE_CALL ) {
-                       pipe.sendTransaction( new TransWaitNamedPipe( path ),
-                                                                               new TransWaitNamedPipeResponse() );
-                       pipe.sendTransaction( new TransCallNamedPipe( path, b, off, len ),
-                                                                               new TransCallNamedPipeResponse( pipe ));
-               } else if(( pipe.pipeType & SmbNamedPipe.PIPE_TYPE_TRANSACT ) ==
-                                                                                                       SmbNamedPipe.PIPE_TYPE_TRANSACT ) {
-                       pipe.open(( pipe.pipeType & 0xFF0000 ) | SmbFile.O_EXCL, SmbFile.ATTR_NORMAL, 0 );
-                       pipe.sendTransaction( new TransTransactNamedPipe( pipe.fid, b, off, len ),
-                                                                               new TransTransactNamedPipeResponse( pipe ));
-               }
-       }
+    public void close() throws IOException {
+        pipe.close();
+    }
+    public void write( int b ) throws IOException {
+        tmp[0] = (byte)b;
+        write( tmp, 0, 1 );
+    }
+    public void write( byte[] b ) throws IOException {
+        write( b, 0, b.length );
+    }
+    public void write( byte[] b, int off, int len ) throws IOException {
+        if( len < 0 ) {
+            len = 0;
+        }
+
+        if(( pipe.pipeType & SmbNamedPipe.PIPE_TYPE_CALL ) ==
+                                                    SmbNamedPipe.PIPE_TYPE_CALL ) {
+            pipe.sendTransaction( new TransWaitNamedPipe( path ),
+                                        new TransWaitNamedPipeResponse() );
+            pipe.sendTransaction( new TransCallNamedPipe( path, b, off, len ),
+                                        new TransCallNamedPipeResponse( pipe ));
+        } else if(( pipe.pipeType & SmbNamedPipe.PIPE_TYPE_TRANSACT ) ==
+                                                    SmbNamedPipe.PIPE_TYPE_TRANSACT ) {
+            pipe.open(( pipe.pipeType & 0xFF0000 ) | SmbFile.O_EXCL, SmbFile.ATTR_NORMAL, 0 );
+            pipe.sendTransaction( new TransTransactNamedPipe( pipe.fid, b, off, len ),
+                                        new TransTransactNamedPipeResponse( pipe ));
+        }
+    }
 }
diff --git a/src/jcifs/smb/WinError.java b/src/jcifs/smb/WinError.java
new file mode 100644 (file)
index 0000000..c154fc2
--- /dev/null
@@ -0,0 +1,58 @@
+/* jcifs smb client library in Java
+ * Copyright (C) 2004  "Michael B. Allen" <jcifs at samba dot org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package jcifs.smb;
+
+public interface WinError {
+
+    /* Don't bother to edit this. Everthing within the interface
+     * block is automatically generated from the ntstatus package.
+     */
+
+    public static final int ERROR_SUCCESS = 0;
+    public static final int ERROR_REQ_NOT_ACCEP = 71;
+    public static final int ERROR_BAD_PIPE = 230;
+    public static final int ERROR_PIPE_BUSY = 231;
+    public static final int ERROR_NO_DATA = 232;
+    public static final int ERROR_PIPE_NOT_CONNECTED = 233;
+    public static final int ERROR_MORE_DATA = 234;
+    public static final int ERROR_NO_BROWSER_SERVERS_FOUND = 6118;
+
+    static final int[] WINERR_CODES = {
+        ERROR_SUCCESS,
+        ERROR_REQ_NOT_ACCEP,
+        ERROR_BAD_PIPE,
+        ERROR_PIPE_BUSY,
+        ERROR_NO_DATA,
+        ERROR_PIPE_NOT_CONNECTED,
+        ERROR_MORE_DATA,
+        ERROR_NO_BROWSER_SERVERS_FOUND
+    };
+
+    static final String[] WINERR_MESSAGES = {
+        "The operation completed successfully.",
+        "No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept.",
+        "The pipe state is invalid.",
+        "All pipe instances are busy.",
+        "The pipe is being closed.",
+        "No process is on the other end of the pipe.",
+        "More data is available.",
+        "The list of servers for this workgroup is not currently available."
+    };
+}
+
index a539146..6623a76 100644 (file)
@@ -20,75 +20,75 @@ package jcifs.util;
 
 public class Base64 {
 
-       private static final String ALPHABET =
-                       "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+    private static final String ALPHABET =
+            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 
-       /**
-        * Base-64 encodes the supplied block of data.  Line wrapping is not
-        * applied on output.
-        *
-        * @param bytes The block of data that is to be Base-64 encoded.
-        * @return A <code>String</code> containing the encoded data.
-        */
-       public static String encode(byte[] bytes) {
-               int length = bytes.length;
-               if (length == 0) return "";
-               StringBuffer buffer =
-                               new StringBuffer((int) Math.ceil((double) length / 3d) * 4);
-               int remainder = length % 3;
-               length -= remainder;
-               int block;
-               int i = 0;
-               while (i < length) {
-                       block = ((bytes[i++] & 0xff) << 16) | ((bytes[i++] & 0xff) << 8) |
-                                       (bytes[i++] & 0xff);
-                       buffer.append(ALPHABET.charAt(block >>> 18));
-                       buffer.append(ALPHABET.charAt((block >>> 12) & 0x3f));
-                       buffer.append(ALPHABET.charAt((block >>> 6) & 0x3f));
-                       buffer.append(ALPHABET.charAt(block & 0x3f));
-               }
-               if (remainder == 0) return buffer.toString();
-               if (remainder == 1) {
-                       block = (bytes[i] & 0xff) << 4;
-                       buffer.append(ALPHABET.charAt(block >>> 6));
-                       buffer.append(ALPHABET.charAt(block & 0x3f));
-                       buffer.append("==");
-                       return buffer.toString();
-               }
-               block = (((bytes[i++] & 0xff) << 8) | ((bytes[i]) & 0xff)) << 2;
-               buffer.append(ALPHABET.charAt(block >>> 12));
-               buffer.append(ALPHABET.charAt((block >>> 6) & 0x3f));
-               buffer.append(ALPHABET.charAt(block & 0x3f));
-               buffer.append("=");
-               return buffer.toString();
-       }
+    /**
+     * Base-64 encodes the supplied block of data.  Line wrapping is not
+     * applied on output.
+     *
+     * @param bytes The block of data that is to be Base-64 encoded.
+     * @return A <code>String</code> containing the encoded data.
+     */
+    public static String encode(byte[] bytes) {
+        int length = bytes.length;
+        if (length == 0) return "";
+        StringBuffer buffer =
+                new StringBuffer((int) Math.ceil((double) length / 3d) * 4);
+        int remainder = length % 3;
+        length -= remainder;
+        int block;
+        int i = 0;
+        while (i < length) {
+            block = ((bytes[i++] & 0xff) << 16) | ((bytes[i++] & 0xff) << 8) |
+                    (bytes[i++] & 0xff);
+            buffer.append(ALPHABET.charAt(block >>> 18));
+            buffer.append(ALPHABET.charAt((block >>> 12) & 0x3f));
+            buffer.append(ALPHABET.charAt((block >>> 6) & 0x3f));
+            buffer.append(ALPHABET.charAt(block & 0x3f));
+        }
+        if (remainder == 0) return buffer.toString();
+        if (remainder == 1) {
+            block = (bytes[i] & 0xff) << 4;
+            buffer.append(ALPHABET.charAt(block >>> 6));
+            buffer.append(ALPHABET.charAt(block & 0x3f));
+            buffer.append("==");
+            return buffer.toString();
+        }
+        block = (((bytes[i++] & 0xff) << 8) | ((bytes[i]) & 0xff)) << 2;
+        buffer.append(ALPHABET.charAt(block >>> 12));
+        buffer.append(ALPHABET.charAt((block >>> 6) & 0x3f));
+        buffer.append(ALPHABET.charAt(block & 0x3f));
+        buffer.append("=");
+        return buffer.toString();
+    }
 
-       /**
-        * Decodes the supplied Base-64 encoded string.
-        *
-        * @param string The Base-64 encoded string that is to be decoded.
-        * @return A <code>byte[]</code> containing the decoded data block.
-        */
-       public static byte[] decode(String string) {
-               int length = string.length();
-               if (length == 0) return new byte[0];
-               int pad = (string.charAt(length - 2) == '=') ? 2 :
-                               (string.charAt(length - 1) == '=') ? 1 : 0;
-               int size = length * 3 / 4 - pad;
-               byte[] buffer = new byte[size];
-               int block;
-               int i = 0;
-               int index = 0;
-               while (i < length) {
-                       block = (ALPHABET.indexOf(string.charAt(i++)) & 0xff) << 18 |
-                                       (ALPHABET.indexOf(string.charAt(i++)) & 0xff) << 12 |
-                                       (ALPHABET.indexOf(string.charAt(i++)) & 0xff) << 6 |
-                                       (ALPHABET.indexOf(string.charAt(i++)) & 0xff);
-                       buffer[index++] = (byte) (block >>> 16);
-                       if (index < size) buffer[index++] = (byte) ((block >>> 8) & 0xff);
-                       if (index < size) buffer[index++] = (byte) (block & 0xff);
-               }
-               return buffer;
-       }
+    /**
+     * Decodes the supplied Base-64 encoded string.
+     *
+     * @param string The Base-64 encoded string that is to be decoded.
+     * @return A <code>byte[]</code> containing the decoded data block.
+     */
+    public static byte[] decode(String string) {
+        int length = string.length();
+        if (length == 0) return new byte[0];
+        int pad = (string.charAt(length - 2) == '=') ? 2 :
+                (string.charAt(length - 1) == '=') ? 1 : 0;
+        int size = length * 3 / 4 - pad;
+        byte[] buffer = new byte[size];
+        int block;
+        int i = 0;
+        int index = 0;
+        while (i < length) {
+            block = (ALPHABET.indexOf(string.charAt(i++)) & 0xff) << 18 |
+                    (ALPHABET.indexOf(string.charAt(i++)) & 0xff) << 12 |
+                    (ALPHABET.indexOf(string.charAt(i++)) & 0xff) << 6 |
+                    (ALPHABET.indexOf(string.charAt(i++)) & 0xff);
+            buffer[index++] = (byte) (block >>> 16);
+            if (index < size) buffer[index++] = (byte) ((block >>> 8) & 0xff);
+            if (index < size) buffer[index++] = (byte) (block & 0xff);
+        }
+        return buffer;
+    }
 
 }
diff --git a/src/jcifs/util/Config.java b/src/jcifs/util/Config.java
deleted file mode 100644 (file)
index cd75b40..0000000
+++ /dev/null
@@ -1,229 +0,0 @@
-/* jcifs smb client library in Java
- * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-package jcifs.util;
-
-import java.util.Properties;
-import java.util.Enumeration;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-/**
- * This class uses a static {@link jcifs.util.PropertiesTree} to act
- * as a cental repository of configuration information. It cannot be
- * instantiated. Similar to <code>System</code> properties the namespace
- * is global therefore property names should be unique. Before use,
- * the <code>load</code> method should be called with the name of a
- * <code>PropertiesTree</code> file(or <code>null</code> indicating no
- * file) to initialize the <code>Config</code>. The <code>System</code>
- * properties will then populate the <code>Config</code> as well potentially
- * overwriting properties from the file. Thus properties provided on the
- * commandline with the <code>-Dproperty.name=value</code> VM parameter
- * will override properties from the configuration file.
- */
-
-public class Config {
-
-       // supress javadoc constructor summary by removing 'protected'
-       Config() {}
-
-       /**
-        * The static <code>PropertiesTree</code>.
-        */
-
-       protected static PropertiesTree properties = new PropertiesTree();
-
-       /**
-        * Load the <code>Config</code> with properties from the stream
-        * <code>in</code> which should be in <code>PropertiesTree</code>
-        * format. See <a href="../../../properties.html">More About
-        * PropertiesTree and it's File Format</code>.
-        */
-
-       public static void load( InputStream in ) throws IOException {
-               Properties sys;
-
-               if( in != null ) {
-                       properties.load( in );
-               }
-
-               sys = System.getProperties();
-               for( Enumeration e = sys.propertyNames(); e.hasMoreElements(); ) {
-                       String key = (String)e.nextElement();
-                       String val = (String)sys.getProperty( key );
-                       if( key != null && val != null ) {
-                               try {
-                                       properties.put( key, val );
-                               } catch( IllegalArgumentException iae ) {
-                               }
-                       }
-               }
-       }
-
-       /**
-        * List the properties in the <code>Code</code>.
-        */
-
-       public static void list( PrintStream out ) throws IOException {
-               properties.list( out );
-       }
-
-       /**
-        * Add a property. If the property already
-        * exists and it is a <code>PropertiesTree</code> an
-        * <code>IllegalArgumentException</code> will be thrown to indicate
-        * that an entire branch of the tree cannot be overwritten. If
-        * however the node is a leaf property, it will be overwritten
-        * and the old value returned as a <code>String</code>.
-        */
-
-       public static String setProperty( String key, String value ) {
-               return (String)properties.put( key, value );
-       }
-
-       /**
-        * Retrieve a property as an <code>Object</code>. Possible
-        * types are <code>String</code> if the property is a leaf node,
-        * or a <code>PropertiesTree</code> if key resolves to a parent node,
-        * or <code>null</code> otherwise.
-        */
-
-       public static Object get( String key ) {
-               return properties.get( key );
-       }
-
-       /**
-        * Retrieve a <code>String</code>. If the key cannot be found,
-        * the provided <code>def</code> default parameter will be returned.
-        */
-
-       public static String getProperty( String key, String def ) {
-               String result = null;
-               Object obj = get( key );
-               if( obj != null && obj instanceof String ) {
-                       result = (String)obj;
-               }
-               return obj == null ? def : result;
-       }
-
-       /**
-        * Retrieve a <code>String</code>. If the property is not found, <code>null</code> is returned.
-        */
-
-       public static String getProperty( String key ) {
-               String result = null;
-               Object obj = get( key );
-               if( obj != null && obj instanceof String ) {
-                       result = (String)obj;
-               }
-               return result;
-       }
-
-       /**
-        * Retrieve an <code>int</code>. If the key does not exist or
-        * cannot be converted to an <code>int</code>, the provided default
-        * argument will be returned.
-        */
-
-       public static int getInt( String key, int def ) {
-               Object obj = get( key );
-               if( obj != null && obj instanceof String ) {
-                       try {
-                               def = Integer.parseInt( (String)obj );
-                       } catch( NumberFormatException nfe ) {
-                               Log.printStackTrace( "configuration warning", nfe );
-                       }
-               }
-               return def;
-       }
-
-       /**
-        * Retrieve an <code>int</code>. If the property is not found, <code>-1</code> is returned.
-        */
-
-       public static int getInt( String key ) {
-               int result = -1;
-               Object obj = get( key );
-               if( obj != null && obj instanceof String ) {
-                       try {
-                               result = Integer.parseInt( (String)obj );
-                       } catch( NumberFormatException nfe ) {
-                               Log.printStackTrace( "configuration warning", nfe );
-                       }
-               }
-               return result;
-       }
-
-       /**
-        * Retrieve a <code>long</code>. If the key does not exist or
-        * cannot be converted to a <code>long</code>, the provided default
-        * argument will be returned.
-        */
-
-       public static long getLong( String key, long def ) {
-               Object obj = get( key );
-               if( obj != null && obj instanceof String ) {
-                       try {
-                               def = Long.parseLong( (String)obj );
-                       } catch( NumberFormatException nfe ) {
-                               Log.printStackTrace( "configuration warning", nfe );
-                       }
-               }
-               return def;
-       }
-
-       /** 
-        * Retrieve an <code>InetAddress</code>. If the address is not
-        * an IP address and cannot be resolved <code>null</code> will
-        * be returned.
-        */
-
-       public static InetAddress getInetAddress( String key, InetAddress def ) {
-               String addr = getProperty( key );
-               if( addr != null ) {
-                       try {
-                               def = InetAddress.getByName( addr );
-                       } catch( UnknownHostException uhe ) {
-                       }
-               }
-               return def;
-       }
-
-       /**
-        * Retrieve a boolean value. If the property is not found, the value of <code>def</code> is returned.
-        */
-
-       public static boolean getBoolean( String key, boolean def ) {
-               String b = getProperty( key );
-               if( b != null ) {
-                       def = b.toLowerCase().equals( "true" );
-               }
-               return def;
-       }
-
-       /**
-        * Print all properties through the {@link jcifs.util.Log} class with the mask <code>Log.WARNINGS</code>.
-        */
-
-       public static void printProperties( String msg ) {
-               Log.printProperties( Log.WARNINGS, msg, properties );
-       }
-}
index 08a47b3..fbb8bf3 100644 (file)
@@ -84,217 +84,217 @@ public class DES   {
     }
 
     // Constructor, byte-array key.
-    public DES( byte[] key )   {
-               if( key.length == 7 ) {
-                       byte[] key8 = new byte[8];
-                       makeSMBKey( key, key8 );
-                       setKey( key8 );
-               } else {
-               setKey( key );
-               }
-       }
+    public DES( byte[] key )    {
+        if( key.length == 7 ) {
+            byte[] key8 = new byte[8];
+            makeSMBKey( key, key8 );
+            setKey( key8 );
+        } else {
+            setKey( key );
+        }
+    }
 
 
     public static void makeSMBKey(byte[] key7, byte[] key8) {
 
-           int i;
-
-           key8[0] = (byte) ( ( key7[0] >> 1) & 0xff);
-           key8[1] = (byte)(( ((key7[0] & 0x01) << 6) | (((key7[1] & 0xff)>>2) & 0xff)) & 0xff );
-           key8[2] = (byte)(( ((key7[1] & 0x03) << 5) | (((key7[2] & 0xff)>>3) & 0xff)) & 0xff );
-           key8[3] = (byte)(( ((key7[2] & 0x07) << 4) | (((key7[3] & 0xff)>>4) & 0xff)) & 0xff );
-           key8[4] = (byte)(( ((key7[3] & 0x0F) << 3) | (((key7[4] & 0xff)>>5) & 0xff)) & 0xff );
-           key8[5] = (byte)(( ((key7[4] & 0x1F) << 2) | (((key7[5] & 0xff)>>6) & 0xff)) & 0xff );
-           key8[6] = (byte)(( ((key7[5] & 0x3F) << 1) | (((key7[6] & 0xff)>>7) & 0xff)) & 0xff );
-           key8[7] = (byte)(key7[6] & 0x7F);
-           for (i=0;i<8;i++) {
-                   key8[i] = (byte)( key8[i] << 1);
-           }
+        int i;
+
+        key8[0] = (byte) ( ( key7[0] >> 1) & 0xff);
+        key8[1] = (byte)(( ((key7[0] & 0x01) << 6) | (((key7[1] & 0xff)>>2) & 0xff)) & 0xff );
+        key8[2] = (byte)(( ((key7[1] & 0x03) << 5) | (((key7[2] & 0xff)>>3) & 0xff)) & 0xff );
+        key8[3] = (byte)(( ((key7[2] & 0x07) << 4) | (((key7[3] & 0xff)>>4) & 0xff)) & 0xff );
+        key8[4] = (byte)(( ((key7[3] & 0x0F) << 3) | (((key7[4] & 0xff)>>5) & 0xff)) & 0xff );
+        key8[5] = (byte)(( ((key7[4] & 0x1F) << 2) | (((key7[5] & 0xff)>>6) & 0xff)) & 0xff );
+        key8[6] = (byte)(( ((key7[5] & 0x3F) << 1) | (((key7[6] & 0xff)>>7) & 0xff)) & 0xff );
+        key8[7] = (byte)(key7[6] & 0x7F);
+        for (i=0;i<8;i++) {
+            key8[i] = (byte)( key8[i] << 1);
+        }
     }
 
     /// Set the key.
     public void setKey( byte[] key ) {
 
-           // CHECK PAROTY TBD
-           deskey( key, true, encryptKeys );
-           deskey( key, false, decryptKeys );
-       }
+        // CHECK PAROTY TBD
+        deskey( key, true, encryptKeys );
+        deskey( key, false, decryptKeys );
+    }
 
     // Turn an 8-byte key into internal keys.
     private void deskey( byte[] keyBlock, boolean encrypting, int[] KnL ) {
 
-           int i, j, l, m, n;
-           int[] pc1m = new int[56];
-           int[] pcr  = new int[56];
-           int[] kn   = new int[32];
-
-           for ( j = 0; j < 56; ++j )  {
-               l       = pc1[j];
-               m       = l & 07;
-               pc1m[j] = ( (keyBlock[l >>> 3] & bytebit[m]) != 0 )? 1: 0;
-           }
-
-           for ( i = 0; i < 16; ++i ) {
-
-               if ( encrypting )
-                       m = i << 1;
-               else
-                       m = (15-i) << 1;
-               n = m+1;
-               kn[m] = kn[n] = 0;
-               for ( j = 0; j < 28; ++j ) {
-                       l = j+totrot[i];
-                       if ( l < 28 )
-                           pcr[j] = pc1m[l];
-                       else
-                           pcr[j] = pc1m[l-28];
-                   }
-               for ( j=28; j < 56; ++j ) {
-                       l = j+totrot[i];
-                       if ( l < 56 )
-                           pcr[j] = pc1m[l];
-                       else
-                           pcr[j] = pc1m[l-28];
-                   }
-               for ( j = 0; j < 24; ++j ) {
-                       if ( pcr[pc2[j]] != 0 )
-                           kn[m] |= bigbyte[j];
-                       if ( pcr[pc2[j+24]] != 0 )
-                           kn[n] |= bigbyte[j];
-                   }
-           }
-           cookey( kn, KnL );
-       }
-
-    private void cookey( int[] raw, int KnL[] )        {
-           int raw0, raw1;
-           int rawi, KnLi;
-           int i;
-
-           for ( i = 0, rawi = 0, KnLi = 0; i < 16; ++i )   {
-               raw0 = raw[rawi++];
-               raw1 = raw[rawi++];
-               KnL[KnLi]  = (raw0 & 0x00fc0000) <<   6;
-               KnL[KnLi] |= (raw0 & 0x00000fc0) <<  10;
-               KnL[KnLi] |= (raw1 & 0x00fc0000) >>> 10;
-               KnL[KnLi] |= (raw1 & 0x00000fc0) >>>  6;
-               ++KnLi;
-               KnL[KnLi]  = (raw0 & 0x0003f000) <<  12;
-               KnL[KnLi] |= (raw0 & 0x0000003f) <<  16;
-               KnL[KnLi] |= (raw1 & 0x0003f000) >>>  4;
-               KnL[KnLi] |= (raw1 & 0x0000003f);
-               ++KnLi;
-           }
-       }
+        int i, j, l, m, n;
+        int[] pc1m = new int[56];
+        int[] pcr  = new int[56];
+        int[] kn   = new int[32];
+
+        for ( j = 0; j < 56; ++j )  {
+            l       = pc1[j];
+            m       = l & 07;
+            pc1m[j] = ( (keyBlock[l >>> 3] & bytebit[m]) != 0 )? 1: 0;
+        }
+
+        for ( i = 0; i < 16; ++i ) {
+
+            if ( encrypting )
+                m = i << 1;
+            else
+                m = (15-i) << 1;
+            n = m+1;
+            kn[m] = kn[n] = 0;
+            for ( j = 0; j < 28; ++j ) {
+                l = j+totrot[i];
+                if ( l < 28 )
+                    pcr[j] = pc1m[l];
+                else
+                    pcr[j] = pc1m[l-28];
+            }
+            for ( j=28; j < 56; ++j ) {
+                l = j+totrot[i];
+                if ( l < 56 )
+                    pcr[j] = pc1m[l];
+                else
+                    pcr[j] = pc1m[l-28];
+            }
+            for ( j = 0; j < 24; ++j ) {
+                if ( pcr[pc2[j]] != 0 )
+                    kn[m] |= bigbyte[j];
+                if ( pcr[pc2[j+24]] != 0 )
+                    kn[n] |= bigbyte[j];
+            }
+        }
+        cookey( kn, KnL );
+    }
+
+    private void cookey( int[] raw, int KnL[] )     {
+        int raw0, raw1;
+        int rawi, KnLi;
+        int i;
+
+        for ( i = 0, rawi = 0, KnLi = 0; i < 16; ++i )   {
+            raw0 = raw[rawi++];
+            raw1 = raw[rawi++];
+            KnL[KnLi]  = (raw0 & 0x00fc0000) <<   6;
+            KnL[KnLi] |= (raw0 & 0x00000fc0) <<  10;
+            KnL[KnLi] |= (raw1 & 0x00fc0000) >>> 10;
+            KnL[KnLi] |= (raw1 & 0x00000fc0) >>>  6;
+            ++KnLi;
+            KnL[KnLi]  = (raw0 & 0x0003f000) <<  12;
+            KnL[KnLi] |= (raw0 & 0x0000003f) <<  16;
+            KnL[KnLi] |= (raw1 & 0x0003f000) >>>  4;
+            KnL[KnLi] |= (raw1 & 0x0000003f);
+            ++KnLi;
+        }
+    }
 
 
     /// Encrypt a block of eight bytes.
     private void encrypt( byte[] clearText, int clearOff, byte[] cipherText, int cipherOff ) {
 
-           squashBytesToInts( clearText, clearOff, tempInts, 0, 2 );
-           des( tempInts, tempInts, encryptKeys );
-           spreadIntsToBytes( tempInts, 0, cipherText, cipherOff, 2 );
-       }
+        squashBytesToInts( clearText, clearOff, tempInts, 0, 2 );
+        des( tempInts, tempInts, encryptKeys );
+        spreadIntsToBytes( tempInts, 0, cipherText, cipherOff, 2 );
+    }
 
     /// Decrypt a block of eight bytes.
     private void decrypt( byte[] cipherText, int cipherOff, byte[] clearText, int clearOff ) {
 
-           squashBytesToInts( cipherText, cipherOff, tempInts, 0, 2 );
-           des( tempInts, tempInts, decryptKeys );
-           spreadIntsToBytes( tempInts, 0, clearText, clearOff, 2 );
-       }
+        squashBytesToInts( cipherText, cipherOff, tempInts, 0, 2 );
+        des( tempInts, tempInts, decryptKeys );
+        spreadIntsToBytes( tempInts, 0, clearText, clearOff, 2 );
+    }
 
     // The DES function.
     private void des( int[] inInts, int[] outInts, int[] keys ) {
 
-           int fval, work, right, leftt;
-           int round;
-           int keysi = 0;
-
-           leftt = inInts[0];
-           right = inInts[1];
-
-           work   = ((leftt >>>  4) ^ right) & 0x0f0f0f0f;
-           right ^= work;
-           leftt ^= (work << 4);
-
-           work   = ((leftt >>> 16) ^ right) & 0x0000ffff;
-           right ^= work;
-           leftt ^= (work << 16);
-
-           work   = ((right >>>  2) ^ leftt) & 0x33333333;
-           leftt ^= work;
-           right ^= (work << 2);
-
-           work   = ((right >>>  8) ^ leftt) & 0x00ff00ff;
-           leftt ^= work;
-           right ^= (work << 8);
-           right  = (right << 1) | ((right >>> 31) & 1);
-
-           work   = (leftt ^ right) & 0xaaaaaaaa;
-           leftt ^= work;
-           right ^= work;
-           leftt  = (leftt << 1) | ((leftt >>> 31) & 1);
-
-           for ( round = 0; round < 8; ++round )  {
-               work   = (right << 28) | (right >>> 4);
-               work  ^= keys[keysi++];
-               fval   = SP7[ work             & 0x0000003f ];
-               fval  |= SP5[(work >>>  8) & 0x0000003f ];
-               fval  |= SP3[(work >>> 16) & 0x0000003f ];
-               fval  |= SP1[(work >>> 24) & 0x0000003f ];
-               work   = right ^ keys[keysi++];
-               fval  |= SP8[ work         & 0x0000003f ];
-               fval  |= SP6[(work >>>  8) & 0x0000003f ];
-               fval  |= SP4[(work >>> 16) & 0x0000003f ];
-               fval  |= SP2[(work >>> 24) & 0x0000003f ];
-               leftt ^= fval;
-               work   = (leftt << 28) | (leftt >>> 4);
-               work  ^= keys[keysi++];
-               fval   = SP7[ work             & 0x0000003f ];
-               fval  |= SP5[(work >>>  8) & 0x0000003f ];
-               fval  |= SP3[(work >>> 16) & 0x0000003f ];
-               fval  |= SP1[(work >>> 24) & 0x0000003f ];
-               work   = leftt ^ keys[keysi++];
-               fval  |= SP8[ work             & 0x0000003f ];
-               fval  |= SP6[(work >>>  8) & 0x0000003f ];
-               fval  |= SP4[(work >>> 16) & 0x0000003f ];
-               fval  |= SP2[(work >>> 24) & 0x0000003f ];
-               right ^= fval;
-           }
-
-           right  = (right << 31) | (right >>> 1);
-           work   = (leftt ^ right) & 0xaaaaaaaa;
-           leftt ^= work;
-           right ^= work;
-           leftt  = (leftt << 31) | (leftt >>> 1);
-           work   = ((leftt >>>  8) ^ right) & 0x00ff00ff;
-           right ^= work;
-           leftt ^= (work << 8);
-           work   = ((leftt >>>  2) ^ right) & 0x33333333;
-           right ^= work;
-           leftt ^= (work << 2);
-           work   = ((right >>> 16) ^ leftt) & 0x0000ffff;
-           leftt ^= work;
-           right ^= (work << 16);
-           work   = ((right >>>  4) ^ leftt) & 0x0f0f0f0f;
-           leftt ^= work;
-           right ^= (work << 4);
-           outInts[0] = right;
-           outInts[1] = leftt;
-       }
-
-
-       /// Encrypt a block of bytes.
-    public void encrypt( byte[] clearText, byte[] cipherText )         {
-           encrypt( clearText, 0, cipherText, 0 );
-       }
+        int fval, work, right, leftt;
+        int round;
+        int keysi = 0;
+
+        leftt = inInts[0];
+        right = inInts[1];
+
+        work   = ((leftt >>>  4) ^ right) & 0x0f0f0f0f;
+        right ^= work;
+        leftt ^= (work << 4);
+
+        work   = ((leftt >>> 16) ^ right) & 0x0000ffff;
+        right ^= work;
+        leftt ^= (work << 16);
+
+        work   = ((right >>>  2) ^ leftt) & 0x33333333;
+        leftt ^= work;
+        right ^= (work << 2);
+
+        work   = ((right >>>  8) ^ leftt) & 0x00ff00ff;
+        leftt ^= work;
+        right ^= (work << 8);
+        right  = (right << 1) | ((right >>> 31) & 1);
+
+        work   = (leftt ^ right) & 0xaaaaaaaa;
+        leftt ^= work;
+        right ^= work;
+        leftt  = (leftt << 1) | ((leftt >>> 31) & 1);
+
+        for ( round = 0; round < 8; ++round )  {
+            work   = (right << 28) | (right >>> 4);
+            work  ^= keys[keysi++];
+            fval   = SP7[ work         & 0x0000003f ];
+            fval  |= SP5[(work >>>  8) & 0x0000003f ];
+            fval  |= SP3[(work >>> 16) & 0x0000003f ];
+            fval  |= SP1[(work >>> 24) & 0x0000003f ];
+            work   = right ^ keys[keysi++];
+            fval  |= SP8[ work         & 0x0000003f ];
+            fval  |= SP6[(work >>>  8) & 0x0000003f ];
+            fval  |= SP4[(work >>> 16) & 0x0000003f ];
+            fval  |= SP2[(work >>> 24) & 0x0000003f ];
+            leftt ^= fval;
+            work   = (leftt << 28) | (leftt >>> 4);
+            work  ^= keys[keysi++];
+            fval   = SP7[ work         & 0x0000003f ];
+            fval  |= SP5[(work >>>  8) & 0x0000003f ];
+            fval  |= SP3[(work >>> 16) & 0x0000003f ];
+            fval  |= SP1[(work >>> 24) & 0x0000003f ];
+            work   = leftt ^ keys[keysi++];
+            fval  |= SP8[ work         & 0x0000003f ];
+            fval  |= SP6[(work >>>  8) & 0x0000003f ];
+            fval  |= SP4[(work >>> 16) & 0x0000003f ];
+            fval  |= SP2[(work >>> 24) & 0x0000003f ];
+            right ^= fval;
+        }
+
+        right  = (right << 31) | (right >>> 1);
+        work   = (leftt ^ right) & 0xaaaaaaaa;
+        leftt ^= work;
+        right ^= work;
+        leftt  = (leftt << 31) | (leftt >>> 1);
+        work   = ((leftt >>>  8) ^ right) & 0x00ff00ff;
+        right ^= work;
+        leftt ^= (work << 8);
+        work   = ((leftt >>>  2) ^ right) & 0x33333333;
+        right ^= work;
+        leftt ^= (work << 2);
+        work   = ((right >>> 16) ^ leftt) & 0x0000ffff;
+        leftt ^= work;
+        right ^= (work << 16);
+        work   = ((right >>>  4) ^ leftt) & 0x0f0f0f0f;
+        leftt ^= work;
+        right ^= (work << 4);
+        outInts[0] = right;
+        outInts[1] = leftt;
+    }
+
+
+    /// Encrypt a block of bytes.
+    public void encrypt( byte[] clearText, byte[] cipherText )  {
+        encrypt( clearText, 0, cipherText, 0 );
+    }
 
     /// Decrypt a block of bytes.
     public void decrypt( byte[] cipherText, byte[] clearText ) {
 
-           decrypt( cipherText, 0, clearText, 0 );
-       }
+        decrypt( cipherText, 0, clearText, 0 );
+    }
 
     /**
      * encrypts an array where the length must be a multiple of 8
@@ -342,210 +342,210 @@ public class DES   {
     // Tables, permutations, S-boxes, etc.
 
     private static byte[] bytebit = {
-           (byte)0x80, (byte)0x40, (byte)0x20, (byte)0x10,
-           (byte)0x08, (byte)0x04, (byte)0x02, (byte)0x01
-       };
+        (byte)0x80, (byte)0x40, (byte)0x20, (byte)0x10,
+        (byte)0x08, (byte)0x04, (byte)0x02, (byte)0x01
+    };
     private static int[] bigbyte = {
-           0x800000, 0x400000, 0x200000, 0x100000,
-           0x080000, 0x040000, 0x020000, 0x010000,
-           0x008000, 0x004000, 0x002000, 0x001000,
-           0x000800, 0x000400, 0x000200, 0x000100,
-           0x000080, 0x000040, 0x000020, 0x000010,
-           0x000008, 0x000004, 0x000002, 0x000001
-       };
+        0x800000, 0x400000, 0x200000, 0x100000,
+        0x080000, 0x040000, 0x020000, 0x010000,
+        0x008000, 0x004000, 0x002000, 0x001000,
+        0x000800, 0x000400, 0x000200, 0x000100,
+        0x000080, 0x000040, 0x000020, 0x000010,
+        0x000008, 0x000004, 0x000002, 0x000001
+    };
     private static byte[] pc1 = {
         (byte)56, (byte)48, (byte)40, (byte)32, (byte)24, (byte)16, (byte) 8,
         (byte) 0, (byte)57, (byte)49, (byte)41, (byte)33, (byte)25, (byte)17,
-           (byte) 9, (byte) 1, (byte)58, (byte)50, (byte)42, (byte)34, (byte)26,
+        (byte) 9, (byte) 1, (byte)58, (byte)50, (byte)42, (byte)34, (byte)26,
         (byte)18, (byte)10, (byte) 2, (byte)59, (byte)51, (byte)43, (byte)35,
-           (byte)62, (byte)54, (byte)46, (byte)38, (byte)30, (byte)22, (byte)14,
+        (byte)62, (byte)54, (byte)46, (byte)38, (byte)30, (byte)22, (byte)14,
         (byte) 6, (byte)61, (byte)53, (byte)45, (byte)37, (byte)29, (byte)21,
-           (byte)13, (byte) 5, (byte)60, (byte)52, (byte)44, (byte)36, (byte)28,
+        (byte)13, (byte) 5, (byte)60, (byte)52, (byte)44, (byte)36, (byte)28,
         (byte)20, (byte)12, (byte) 4, (byte)27, (byte)19, (byte)11, (byte)3
-       };
+    };
     private static int[] totrot = {
         1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28
-       };
+    };
 
     private static byte[] pc2 = {
-           (byte)13, (byte)16, (byte)10, (byte)23, (byte) 0, (byte) 4,
-           (byte) 2, (byte)27, (byte)14, (byte) 5, (byte)20, (byte) 9,
-           (byte)22, (byte)18, (byte)11, (byte)3 , (byte)25, (byte) 7,
-           (byte)15, (byte) 6, (byte)26, (byte)19, (byte)12, (byte) 1,
-           (byte)40, (byte)51, (byte)30, (byte)36, (byte)46, (byte)54,
-           (byte)29, (byte)39, (byte)50, (byte)44, (byte)32, (byte)47,
-           (byte)43, (byte)48, (byte)38, (byte)55, (byte)33, (byte)52,
-           (byte)45, (byte)41, (byte)49, (byte)35, (byte)28, (byte)31,
-       };
+        (byte)13, (byte)16, (byte)10, (byte)23, (byte) 0, (byte) 4,
+        (byte) 2, (byte)27, (byte)14, (byte) 5, (byte)20, (byte) 9,
+        (byte)22, (byte)18, (byte)11, (byte)3 , (byte)25, (byte) 7,
+        (byte)15, (byte) 6, (byte)26, (byte)19, (byte)12, (byte) 1,
+        (byte)40, (byte)51, (byte)30, (byte)36, (byte)46, (byte)54,
+        (byte)29, (byte)39, (byte)50, (byte)44, (byte)32, (byte)47,
+        (byte)43, (byte)48, (byte)38, (byte)55, (byte)33, (byte)52,
+        (byte)45, (byte)41, (byte)49, (byte)35, (byte)28, (byte)31,
+    };
 
     private static int[] SP1 = {
         0x01010400, 0x00000000, 0x00010000, 0x01010404,
-           0x01010004, 0x00010404, 0x00000004, 0x00010000,
-           0x00000400, 0x01010400, 0x01010404, 0x00000400,
-           0x01000404, 0x01010004, 0x01000000, 0x00000004,
-           0x00000404, 0x01000400, 0x01000400, 0x00010400,
-           0x00010400, 0x01010000, 0x01010000, 0x01000404,
-           0x00010004, 0x01000004, 0x01000004, 0x00010004,
-           0x00000000, 0x00000404, 0x00010404, 0x01000000,
-           0x00010000, 0x01010404, 0x00000004, 0x01010000,
-           0x01010400, 0x01000000, 0x01000000, 0x00000400,
-           0x01010004, 0x00010000, 0x00010400, 0x01000004,
-           0x00000400, 0x00000004, 0x01000404, 0x00010404,
-           0x01010404, 0x00010004, 0x01010000, 0x01000404,
-           0x01000004, 0x00000404, 0x00010404, 0x01010400,
-           0x00000404, 0x01000400, 0x01000400, 0x00000000,
-           0x00010004, 0x00010400, 0x00000000, 0x01010004
-       };
+        0x01010004, 0x00010404, 0x00000004, 0x00010000,
+        0x00000400, 0x01010400, 0x01010404, 0x00000400,
+        0x01000404, 0x01010004, 0x01000000, 0x00000004,
+        0x00000404, 0x01000400, 0x01000400, 0x00010400,
+        0x00010400, 0x01010000, 0x01010000, 0x01000404,
+        0x00010004, 0x01000004, 0x01000004, 0x00010004,
+        0x00000000, 0x00000404, 0x00010404, 0x01000000,
+        0x00010000, 0x01010404, 0x00000004, 0x01010000,
+        0x01010400, 0x01000000, 0x01000000, 0x00000400,
+        0x01010004, 0x00010000, 0x00010400, 0x01000004,
+        0x00000400, 0x00000004, 0x01000404, 0x00010404,
+        0x01010404, 0x00010004, 0x01010000, 0x01000404,
+        0x01000004, 0x00000404, 0x00010404, 0x01010400,
+        0x00000404, 0x01000400, 0x01000400, 0x00000000,
+        0x00010004, 0x00010400, 0x00000000, 0x01010004
+    };
     private static int[] SP2 = {
-           0x80108020, 0x80008000, 0x00008000, 0x00108020,
-           0x00100000, 0x00000020, 0x80100020, 0x80008020,
-           0x80000020, 0x80108020, 0x80108000, 0x80000000,
-           0x80008000, 0x00100000, 0x00000020, 0x80100020,
-           0x00108000, 0x00100020, 0x80008020, 0x00000000,
-           0x80000000, 0x00008000, 0x00108020, 0x80100000,
-           0x00100020, 0x80000020, 0x00000000, 0x00108000,
-           0x00008020, 0x80108000, 0x80100000, 0x00008020,
-           0x00000000, 0x00108020, 0x80100020, 0x00100000,
-           0x80008020, 0x80100000, 0x80108000, 0x00008000,
-           0x80100000, 0x80008000, 0x00000020, 0x80108020,
-           0x00108020, 0x00000020, 0x00008000, 0x80000000,
-           0x00008020, 0x80108000, 0x00100000, 0x80000020,
-           0x00100020, 0x80008020, 0x80000020, 0x00100020,
-           0x00108000, 0x00000000, 0x80008000, 0x00008020,
-           0x80000000, 0x80100020, 0x80108020, 0x00108000
-       };
+        0x80108020, 0x80008000, 0x00008000, 0x00108020,
+        0x00100000, 0x00000020, 0x80100020, 0x80008020,
+        0x80000020, 0x80108020, 0x80108000, 0x80000000,
+        0x80008000, 0x00100000, 0x00000020, 0x80100020,
+        0x00108000, 0x00100020, 0x80008020, 0x00000000,
+        0x80000000, 0x00008000, 0x00108020, 0x80100000,
+        0x00100020, 0x80000020, 0x00000000, 0x00108000,
+        0x00008020, 0x80108000, 0x80100000, 0x00008020,
+        0x00000000, 0x00108020, 0x80100020, 0x00100000,
+        0x80008020, 0x80100000, 0x80108000, 0x00008000,
+        0x80100000, 0x80008000, 0x00000020, 0x80108020,
+        0x00108020, 0x00000020, 0x00008000, 0x80000000,
+        0x00008020, 0x80108000, 0x00100000, 0x80000020,
+        0x00100020, 0x80008020, 0x80000020, 0x00100020,
+        0x00108000, 0x00000000, 0x80008000, 0x00008020,
+        0x80000000, 0x80100020, 0x80108020, 0x00108000
+    };
     private static int[] SP3 = {
-           0x00000208, 0x08020200, 0x00000000, 0x08020008,
-           0x08000200, 0x00000000, 0x00020208, 0x08000200,
-           0x00020008, 0x08000008, 0x08000008, 0x00020000,
-           0x08020208, 0x00020008, 0x08020000, 0x00000208,
-           0x08000000, 0x00000008, 0x08020200, 0x00000200,
-           0x00020200, 0x08020000, 0x08020008, 0x00020208,
-           0x08000208, 0x00020200, 0x00020000, 0x08000208,
-           0x00000008, 0x08020208, 0x00000200, 0x08000000,
-           0x08020200, 0x08000000, 0x00020008, 0x00000208,
-           0x00020000, 0x08020200, 0x08000200, 0x00000000,
-           0x00000200, 0x00020008, 0x08020208, 0x08000200,
-           0x08000008, 0x00000200, 0x00000000, 0x08020008,
-           0x08000208, 0x00020000, 0x08000000, 0x08020208,
-           0x00000008, 0x00020208, 0x00020200, 0x08000008,
-           0x08020000, 0x08000208, 0x00000208, 0x08020000,
-           0x00020208, 0x00000008, 0x08020008, 0x00020200
-       };
+        0x00000208, 0x08020200, 0x00000000, 0x08020008,
+        0x08000200, 0x00000000, 0x00020208, 0x08000200,
+        0x00020008, 0x08000008, 0x08000008, 0x00020000,
+        0x08020208, 0x00020008, 0x08020000, 0x00000208,
+        0x08000000, 0x00000008, 0x08020200, 0x00000200,
+        0x00020200, 0x08020000, 0x08020008, 0x00020208,
+        0x08000208, 0x00020200, 0x00020000, 0x08000208,
+        0x00000008, 0x08020208, 0x00000200, 0x08000000,
+        0x08020200, 0x08000000, 0x00020008, 0x00000208,
+        0x00020000, 0x08020200, 0x08000200, 0x00000000,
+        0x00000200, 0x00020008, 0x08020208, 0x08000200,
+        0x08000008, 0x00000200, 0x00000000, 0x08020008,
+        0x08000208, 0x00020000, 0x08000000, 0x08020208,
+        0x00000008, 0x00020208, 0x00020200, 0x08000008,
+        0x08020000, 0x08000208, 0x00000208, 0x08020000,
+        0x00020208, 0x00000008, 0x08020008, 0x00020200
+    };
     private static int[] SP4 = {
-           0x00802001, 0x00002081, 0x00002081, 0x00000080,
-           0x00802080, 0x00800081, 0x00800001, 0x00002001,
-           0x00000000, 0x00802000, 0x00802000, 0x00802081,
-           0x00000081, 0x00000000, 0x00800080, 0x00800001,
-           0x00000001, 0x00002000, 0x00800000, 0x00802001,
-           0x00000080, 0x00800000, 0x00002001, 0x00002080,
-           0x00800081, 0x00000001, 0x00002080, 0x00800080,
-           0x00002000, 0x00802080, 0x00802081, 0x00000081,
-           0x00800080, 0x00800001, 0x00802000, 0x00802081,
-           0x00000081, 0x00000000, 0x00000000, 0x00802000,
-           0x00002080, 0x00800080, 0x00800081, 0x00000001,
-           0x00802001, 0x00002081, 0x00002081, 0x00000080,
-           0x00802081, 0x00000081, 0x00000001, 0x00002000,
-           0x00800001, 0x00002001, 0x00802080, 0x00800081,
-           0x00002001, 0x00002080, 0x00800000, 0x00802001,
-           0x00000080, 0x00800000, 0x00002000, 0x00802080
-       };
+        0x00802001, 0x00002081, 0x00002081, 0x00000080,
+        0x00802080, 0x00800081, 0x00800001, 0x00002001,
+        0x00000000, 0x00802000, 0x00802000, 0x00802081,
+        0x00000081, 0x00000000, 0x00800080, 0x00800001,
+        0x00000001, 0x00002000, 0x00800000, 0x00802001,
+        0x00000080, 0x00800000, 0x00002001, 0x00002080,
+        0x00800081, 0x00000001, 0x00002080, 0x00800080,
+        0x00002000, 0x00802080, 0x00802081, 0x00000081,
+        0x00800080, 0x00800001, 0x00802000, 0x00802081,
+        0x00000081, 0x00000000, 0x00000000, 0x00802000,
+        0x00002080, 0x00800080, 0x00800081, 0x00000001,
+        0x00802001, 0x00002081, 0x00002081, 0x00000080,
+        0x00802081, 0x00000081, 0x00000001, 0x00002000,
+        0x00800001, 0x00002001, 0x00802080, 0x00800081,
+        0x00002001, 0x00002080, 0x00800000, 0x00802001,
+        0x00000080, 0x00800000, 0x00002000, 0x00802080
+    };
     private static int[] SP5 = {
-           0x00000100, 0x02080100, 0x02080000, 0x42000100,
-           0x00080000, 0x00000100, 0x40000000, 0x02080000,
-           0x40080100, 0x00080000, 0x02000100, 0x40080100,
-           0x42000100, 0x42080000, 0x00080100, 0x40000000,
-           0x02000000, 0x40080000, 0x40080000, 0x00000000,
-           0x40000100, 0x42080100, 0x42080100, 0x02000100,
-           0x42080000, 0x40000100, 0x00000000, 0x42000000,
-           0x02080100, 0x02000000, 0x42000000, 0x00080100,
-           0x00080000, 0x42000100, 0x00000100, 0x02000000,
-           0x40000000, 0x02080000, 0x42000100, 0x40080100,
-           0x02000100, 0x40000000, 0x42080000, 0x02080100,
-           0x40080100, 0x00000100, 0x02000000, 0x42080000,
-           0x42080100, 0x00080100, 0x42000000, 0x42080100,
-           0x02080000, 0x00000000, 0x40080000, 0x42000000,
-           0x00080100, 0x02000100, 0x40000100, 0x00080000,
-           0x00000000, 0x40080000, 0x02080100, 0x40000100
-       };
+        0x00000100, 0x02080100, 0x02080000, 0x42000100,
+        0x00080000, 0x00000100, 0x40000000, 0x02080000,
+        0x40080100, 0x00080000, 0x02000100, 0x40080100,
+        0x42000100, 0x42080000, 0x00080100, 0x40000000,
+        0x02000000, 0x40080000, 0x40080000, 0x00000000,
+        0x40000100, 0x42080100, 0x42080100, 0x02000100,
+        0x42080000, 0x40000100, 0x00000000, 0x42000000,
+        0x02080100, 0x02000000, 0x42000000, 0x00080100,
+        0x00080000, 0x42000100, 0x00000100, 0x02000000,
+        0x40000000, 0x02080000, 0x42000100, 0x40080100,
+        0x02000100, 0x40000000, 0x42080000, 0x02080100,
+        0x40080100, 0x00000100, 0x02000000, 0x42080000,
+        0x42080100, 0x00080100, 0x42000000, 0x42080100,
+        0x02080000, 0x00000000, 0x40080000, 0x42000000,
+        0x00080100, 0x02000100, 0x40000100, 0x00080000,
+        0x00000000, 0x40080000, 0x02080100, 0x40000100
+    };
     private static int[] SP6 = {
-           0x20000010, 0x20400000, 0x00004000, 0x20404010,
-           0x20400000, 0x00000010, 0x20404010, 0x00400000,
-           0x20004000, 0x00404010, 0x00400000, 0x20000010,
-           0x00400010, 0x20004000, 0x20000000, 0x00004010,
-           0x00000000, 0x00400010, 0x20004010, 0x00004000,
-           0x00404000, 0x20004010, 0x00000010, 0x20400010,
-           0x20400010, 0x00000000, 0x00404010, 0x20404000,
-           0x00004010, 0x00404000, 0x20404000, 0x20000000,
-           0x20004000, 0x00000010, 0x20400010, 0x00404000,
-           0x20404010, 0x00400000, 0x00004010, 0x20000010,
-           0x00400000, 0x20004000, 0x20000000, 0x00004010,
-           0x20000010, 0x20404010, 0x00404000, 0x20400000,
-           0x00404010, 0x20404000, 0x00000000, 0x20400010,
-           0x00000010, 0x00004000, 0x20400000, 0x00404010,
-           0x00004000, 0x00400010, 0x20004010, 0x00000000,
-           0x20404000, 0x20000000, 0x00400010, 0x20004010
-       };
+        0x20000010, 0x20400000, 0x00004000, 0x20404010,
+        0x20400000, 0x00000010, 0x20404010, 0x00400000,
+        0x20004000, 0x00404010, 0x00400000, 0x20000010,
+        0x00400010, 0x20004000, 0x20000000, 0x00004010,
+        0x00000000, 0x00400010, 0x20004010, 0x00004000,
+        0x00404000, 0x20004010, 0x00000010, 0x20400010,
+        0x20400010, 0x00000000, 0x00404010, 0x20404000,
+        0x00004010, 0x00404000, 0x20404000, 0x20000000,
+        0x20004000, 0x00000010, 0x20400010, 0x00404000,
+        0x20404010, 0x00400000, 0x00004010, 0x20000010,
+        0x00400000, 0x20004000, 0x20000000, 0x00004010,
+        0x20000010, 0x20404010, 0x00404000, 0x20400000,
+        0x00404010, 0x20404000, 0x00000000, 0x20400010,
+        0x00000010, 0x00004000, 0x20400000, 0x00404010,
+        0x00004000, 0x00400010, 0x20004010, 0x00000000,
+        0x20404000, 0x20000000, 0x00400010, 0x20004010
+    };
     private static int[] SP7 = {
-           0x00200000, 0x04200002, 0x04000802, 0x00000000,
-           0x00000800, 0x04000802, 0x00200802, 0x04200800,
-           0x04200802, 0x00200000, 0x00000000, 0x04000002,
-           0x00000002, 0x04000000, 0x04200002, 0x00000802,
-           0x04000800, 0x00200802, 0x00200002, 0x04000800,
-           0x04000002, 0x04200000, 0x04200800, 0x00200002,
-           0x04200000, 0x00000800, 0x00000802, 0x04200802,
-           0x00200800, 0x00000002, 0x04000000, 0x00200800,
-           0x04000000, 0x00200800, 0x00200000, 0x04000802,
-           0x04000802, 0x04200002, 0x04200002, 0x00000002,
-           0x00200002, 0x04000000, 0x04000800, 0x00200000,
-           0x04200800, 0x00000802, 0x00200802, 0x04200800,
-           0x00000802, 0x04000002, 0x04200802, 0x04200000,
-           0x00200800, 0x00000000, 0x00000002, 0x04200802,
-           0x00000000, 0x00200802, 0x04200000, 0x00000800,
-           0x04000002, 0x04000800, 0x00000800, 0x00200002
-       };
+        0x00200000, 0x04200002, 0x04000802, 0x00000000,
+        0x00000800, 0x04000802, 0x00200802, 0x04200800,
+        0x04200802, 0x00200000, 0x00000000, 0x04000002,
+        0x00000002, 0x04000000, 0x04200002, 0x00000802,
+        0x04000800, 0x00200802, 0x00200002, 0x04000800,
+        0x04000002, 0x04200000, 0x04200800, 0x00200002,
+        0x04200000, 0x00000800, 0x00000802, 0x04200802,
+        0x00200800, 0x00000002, 0x04000000, 0x00200800,
+        0x04000000, 0x00200800, 0x00200000, 0x04000802,
+        0x04000802, 0x04200002, 0x04200002, 0x00000002,
+        0x00200002, 0x04000000, 0x04000800, 0x00200000,
+        0x04200800, 0x00000802, 0x00200802, 0x04200800,
+        0x00000802, 0x04000002, 0x04200802, 0x04200000,
+        0x00200800, 0x00000000, 0x00000002, 0x04200802,
+        0x00000000, 0x00200802, 0x04200000, 0x00000800,
+        0x04000002, 0x04000800, 0x00000800, 0x00200002
+    };
     private static int[] SP8 = {
-           0x10001040, 0x00001000, 0x00040000, 0x10041040,
-           0x10000000, 0x10001040, 0x00000040, 0x10000000,
-           0x00040040, 0x10040000, 0x10041040, 0x00041000,
-           0x10041000, 0x00041040, 0x00001000, 0x00000040,
-           0x10040000, 0x10000040, 0x10001000, 0x00001040,
-           0x00041000, 0x00040040, 0x10040040, 0x10041000,
-           0x00001040, 0x00000000, 0x00000000, 0x10040040,
-           0x10000040, 0x10001000, 0x00041040, 0x00040000,
-           0x00041040, 0x00040000, 0x10041000, 0x00001000,
-           0x00000040, 0x10040040, 0x00001000, 0x00041040,
-           0x10001000, 0x00000040, 0x10000040, 0x10040000,
-           0x10040040, 0x10000000, 0x00040000, 0x10001040,
-           0x00000000, 0x10041040, 0x00040040, 0x10000040,
-           0x10040000, 0x10001000, 0x10001040, 0x00000000,
-           0x10041040, 0x00041000, 0x00041000, 0x00001040,
-           0x00001040, 0x00040040, 0x10000000, 0x10041000
-       };
+        0x10001040, 0x00001000, 0x00040000, 0x10041040,
+        0x10000000, 0x10001040, 0x00000040, 0x10000000,
+        0x00040040, 0x10040000, 0x10041040, 0x00041000,
+        0x10041000, 0x00041040, 0x00001000, 0x00000040,
+        0x10040000, 0x10000040, 0x10001000, 0x00001040,
+        0x00041000, 0x00040040, 0x10040040, 0x10041000,
+        0x00001040, 0x00000000, 0x00000000, 0x10040040,
+        0x10000040, 0x10001000, 0x00041040, 0x00040000,
+        0x00041040, 0x00040000, 0x10041000, 0x00001000,
+        0x00000040, 0x10040040, 0x00001000, 0x00041040,
+        0x10001000, 0x00000040, 0x10000040, 0x10040000,
+        0x10040040, 0x10000000, 0x00040000, 0x10001040,
+        0x00000000, 0x10041040, 0x00040040, 0x10000040,
+        0x10040000, 0x10001000, 0x10001040, 0x00000000,
+        0x10041040, 0x00041000, 0x00041000, 0x00001040,
+        0x00001040, 0x00040040, 0x10000000, 0x10041000
+    };
 
 
  /// Squash bytes down to ints.
     public static void squashBytesToInts( byte[] inBytes, int inOff, int[] outInts,
                                            int outOff, int intLen ) {
 
-           for ( int i = 0; i < intLen; ++i )
-               outInts[outOff + i] =
-                       ( ( inBytes[inOff + i * 4    ] & 0xff ) << 24 ) |
-                       ( ( inBytes[inOff + i * 4 + 1] & 0xff ) << 16 ) |
-                       ( ( inBytes[inOff + i * 4 + 2] & 0xff ) <<  8 ) |
-                        ( inBytes[inOff + i * 4 + 3] & 0xff );
+        for ( int i = 0; i < intLen; ++i )
+            outInts[outOff + i] =
+                ( ( inBytes[inOff + i * 4    ] & 0xff ) << 24 ) |
+                ( ( inBytes[inOff + i * 4 + 1] & 0xff ) << 16 ) |
+                ( ( inBytes[inOff + i * 4 + 2] & 0xff ) <<  8 ) |
+                 ( inBytes[inOff + i * 4 + 3] & 0xff );
     }
 
     /// Spread ints into bytes.
     public static void spreadIntsToBytes( int[] inInts, int inOff, byte[] outBytes,
                                          int outOff, int intLen ) {
 
-           for ( int i = 0; i < intLen; ++i ) {
+        for ( int i = 0; i < intLen; ++i ) {
 
-               outBytes[outOff + i * 4    ] = (byte) ( inInts[inOff + i] >>> 24 );
-               outBytes[outOff + i * 4 + 1] = (byte) ( inInts[inOff + i] >>> 16 );
-               outBytes[outOff + i * 4 + 2] = (byte) ( inInts[inOff + i] >>>  8 );
-               outBytes[outOff + i * 4 + 3] = (byte)   inInts[inOff + i];
-           }
+            outBytes[outOff + i * 4    ] = (byte) ( inInts[inOff + i] >>> 24 );
+            outBytes[outOff + i * 4 + 1] = (byte) ( inInts[inOff + i] >>> 16 );
+            outBytes[outOff + i * 4 + 2] = (byte) ( inInts[inOff + i] >>>  8 );
+            outBytes[outOff + i * 4 + 3] = (byte)   inInts[inOff + i];
+        }
     }
 }
index f82cc48..9361291 100644 (file)
@@ -28,275 +28,275 @@ import java.io.IOException;
 
 public class Encdec {
 
-       public static final long MILLISECONDS_BETWEEN_1970_AND_1601 = 11644473600000L;
-       public static final long SEC_BETWEEEN_1904_AND_1970 = 2082844800L;
-       public static final int TIME_1970_SEC_32BE = 1;
-       public static final int TIME_1970_SEC_32LE = 2;
-       public static final int TIME_1904_SEC_32BE = 3;
-       public static final int TIME_1904_SEC_32LE = 4;
-       public static final int TIME_1601_NANOS_64LE = 5;
-       public static final int TIME_1601_NANOS_64BE = 6;
-       public static final int TIME_1970_MILLIS_64BE = 7;
-       public static final int TIME_1970_MILLIS_64LE = 8;
+    public static final long MILLISECONDS_BETWEEN_1970_AND_1601 = 11644473600000L;
+    public static final long SEC_BETWEEEN_1904_AND_1970 = 2082844800L;
+    public static final int TIME_1970_SEC_32BE = 1;
+    public static final int TIME_1970_SEC_32LE = 2;
+    public static final int TIME_1904_SEC_32BE = 3;
+    public static final int TIME_1904_SEC_32LE = 4;
+    public static final int TIME_1601_NANOS_64LE = 5;
+    public static final int TIME_1601_NANOS_64BE = 6;
+    public static final int TIME_1970_MILLIS_64BE = 7;
+    public static final int TIME_1970_MILLIS_64LE = 8;
 
-       /* Encode integers
-        */
+    /* Encode integers
+     */
 
-       public static int enc_uint16be( short s, byte[] dst, int di ) {
-               dst[di++] = (byte)((s >> 8) & 0xFF);
-               dst[di] = (byte)(s & 0xFF);
-               return 2;
-       }
-       public static int enc_uint32be( int i, byte[] dst, int di ) {
-               dst[di++] = (byte)((i >> 24) & 0xFF);
-               dst[di++] = (byte)((i >> 16) & 0xFF);
-               dst[di++] = (byte)((i >> 8) & 0xFF);
-               dst[di] = (byte)(i & 0xFF);
-               return 4;
-       }
-       public static int enc_uint16le( short s, byte[] dst, int di )
-       {
-               dst[di++] = (byte)(s & 0xFF);
-               dst[di] = (byte)((s >> 8) & 0xFF);
-               return 2;
-       }
-       public static int enc_uint32le( int i, byte[] dst, int di )
-       {
-               dst[di++] = (byte)(i & 0xFF);
-               dst[di++] = (byte)((i >> 8) & 0xFF);
-               dst[di++] = (byte)((i >> 16) & 0xFF);
-               dst[di] = (byte)((i >> 24) & 0xFF);
-               return 4;
-       }
+    public static int enc_uint16be( short s, byte[] dst, int di ) {
+        dst[di++] = (byte)((s >> 8) & 0xFF);
+        dst[di] = (byte)(s & 0xFF);
+        return 2;
+    }
+    public static int enc_uint32be( int i, byte[] dst, int di ) {
+        dst[di++] = (byte)((i >> 24) & 0xFF);
+        dst[di++] = (byte)((i >> 16) & 0xFF);
+        dst[di++] = (byte)((i >> 8) & 0xFF);
+        dst[di] = (byte)(i & 0xFF);
+        return 4;
+    }
+    public static int enc_uint16le( short s, byte[] dst, int di )
+    {
+        dst[di++] = (byte)(s & 0xFF);
+        dst[di] = (byte)((s >> 8) & 0xFF);
+        return 2;
+    }
+    public static int enc_uint32le( int i, byte[] dst, int di )
+    {
+        dst[di++] = (byte)(i & 0xFF);
+        dst[di++] = (byte)((i >> 8) & 0xFF);
+        dst[di++] = (byte)((i >> 16) & 0xFF);
+        dst[di] = (byte)((i >> 24) & 0xFF);
+        return 4;
+    }
 
-       /* Decode integers
-        */
+    /* Decode integers
+     */
 
-       public static short dec_uint16be( byte[] src, int si )
-       {
-               return (short)(((src[si] & 0xFF) << 8) | (src[si + 1] & 0xFF));
-       }
-       public static int dec_uint32be( byte[] src, int si )
-       {
-               return ((src[si] & 0xFF) << 24) | ((src[si + 1] & 0xFF) << 16) |
-                  ((src[si + 2] & 0xFF) << 8) | (src[si + 3] & 0xFF);
-       }
-       public static short dec_uint16le( byte[] src, int si )
-       {
-               return (short)((src[si] & 0xFF) | ((src[si + 1] & 0xFF) << 8));
-       }
-       public static int dec_uint32le( byte[] src, int si )
-       {
-               return (src[si] & 0xFF) | ((src[si + 1] & 0xFF) << 8) |
-                  ((src[si + 2] & 0xFF) << 16) | ((src[si + 3] & 0xFF) << 24);
-       }
+    public static short dec_uint16be( byte[] src, int si )
+    {
+        return (short)(((src[si] & 0xFF) << 8) | (src[si + 1] & 0xFF));
+    }
+    public static int dec_uint32be( byte[] src, int si )
+    {
+        return ((src[si] & 0xFF) << 24) | ((src[si + 1] & 0xFF) << 16) |
+               ((src[si + 2] & 0xFF) << 8) | (src[si + 3] & 0xFF);
+    }
+    public static short dec_uint16le( byte[] src, int si )
+    {
+        return (short)((src[si] & 0xFF) | ((src[si + 1] & 0xFF) << 8));
+    }
+    public static int dec_uint32le( byte[] src, int si )
+    {
+        return (src[si] & 0xFF) | ((src[si + 1] & 0xFF) << 8) |
+               ((src[si + 2] & 0xFF) << 16) | ((src[si + 3] & 0xFF) << 24);
+    }
 
-       /* Encode and decode 64 bit integers
-        */
+    /* Encode and decode 64 bit integers
+     */
 
-       public static int enc_uint64be( long l, byte[] dst, int di )
-       {
-               enc_uint32be( (int)(l & 0xFFFFFFFFL), dst, di + 4 );
-               enc_uint32be( (int)(( l >> 32L ) & 0xFFFFFFFFL), dst, di );
-               return 8;
-       }
-       public static int enc_uint64le( long l, byte[] dst, int di )
-       {
-               enc_uint32le( (int)(l & 0xFFFFFFFFL), dst, di );
-               enc_uint32le( (int)(( l >> 32L ) & 0xFFFFFFFFL), dst, di + 4 );
-               return 8;
-       }
-       public static long dec_uint64be( byte[] src, int si )
-       {
-               long l;
-               l = dec_uint32be( src, si ) & 0xFFFFFFFFL;
-               l <<= 32L;
-               l |= dec_uint32be( src, si + 4 ) & 0xFFFFFFFFL;
-               return l;
-       }
-       public static long dec_uint64le( byte[] src, int si )
-       {
-               long l;
-               l = dec_uint32le( src, si + 4 ) & 0xFFFFFFFFL;
-               l <<= 32L;
-               l |= dec_uint32le( src, si ) & 0xFFFFFFFFL;
-               return l;
-       }
+    public static int enc_uint64be( long l, byte[] dst, int di )
+    {
+        enc_uint32be( (int)(l & 0xFFFFFFFFL), dst, di + 4 );
+        enc_uint32be( (int)(( l >> 32L ) & 0xFFFFFFFFL), dst, di );
+        return 8;
+    }
+    public static int enc_uint64le( long l, byte[] dst, int di )
+    {
+        enc_uint32le( (int)(l & 0xFFFFFFFFL), dst, di );
+        enc_uint32le( (int)(( l >> 32L ) & 0xFFFFFFFFL), dst, di + 4 );
+        return 8;
+    }
+    public static long dec_uint64be( byte[] src, int si )
+    {
+        long l;
+        l = dec_uint32be( src, si ) & 0xFFFFFFFFL;
+        l <<= 32L;
+        l |= dec_uint32be( src, si + 4 ) & 0xFFFFFFFFL;
+        return l;
+    }
+    public static long dec_uint64le( byte[] src, int si )
+    {
+        long l;
+        l = dec_uint32le( src, si + 4 ) & 0xFFFFFFFFL;
+        l <<= 32L;
+        l |= dec_uint32le( src, si ) & 0xFFFFFFFFL;
+        return l;
+    }
 
-       /* Encode floats
-        */
+    /* Encode floats
+     */
 
-       public static int enc_floatle( float f, byte[] dst, int di )
-       {
-               return enc_uint32le( Float.floatToIntBits( f ), dst, di );
-       }
-       public static int enc_floatbe( float f, byte[] dst, int di )
-       {
-               return enc_uint32be( Float.floatToIntBits( f ), dst, di );
-       }
+    public static int enc_floatle( float f, byte[] dst, int di )
+    {
+        return enc_uint32le( Float.floatToIntBits( f ), dst, di );
+    }
+    public static int enc_floatbe( float f, byte[] dst, int di )
+    {
+        return enc_uint32be( Float.floatToIntBits( f ), dst, di );
+    }
 
-       /* Decode floating point numbers
-        */
+    /* Decode floating point numbers
+     */
 
-       public static float dec_floatle( byte[] src, int si )
-       {
-               return Float.intBitsToFloat( dec_uint32le( src, si ));
-       }
-       public static float dec_floatbe( byte[] src, int si )
-       {
-               return Float.intBitsToFloat( dec_uint32be( src, si ));
-       }
+    public static float dec_floatle( byte[] src, int si )
+    {
+        return Float.intBitsToFloat( dec_uint32le( src, si ));
+    }
+    public static float dec_floatbe( byte[] src, int si )
+    {
+        return Float.intBitsToFloat( dec_uint32be( src, si ));
+    }
 
-       /* Encode and decode doubles
-        */
+    /* Encode and decode doubles
+     */
 
-       public static int enc_doublele( double d, byte[] dst, int di )
-       {
-               return enc_uint64le( Double.doubleToLongBits( d ), dst, di );
-       }
-       public static int enc_doublebe( double d, byte[] dst, int di )
-       {
-               return enc_uint64be( Double.doubleToLongBits( d ), dst, di );
-       }
-       public static double dec_doublele( byte[] src, int si )
-       {
-               return Double.longBitsToDouble( dec_uint64le( src, si ));
-       }
-       public static double dec_doublebe( byte[] src, int si )
-       {
-               return Double.longBitsToDouble( dec_uint64be( src, si ));
-       }
+    public static int enc_doublele( double d, byte[] dst, int di )
+    {
+        return enc_uint64le( Double.doubleToLongBits( d ), dst, di );
+    }
+    public static int enc_doublebe( double d, byte[] dst, int di )
+    {
+        return enc_uint64be( Double.doubleToLongBits( d ), dst, di );
+    }
+    public static double dec_doublele( byte[] src, int si )
+    {
+        return Double.longBitsToDouble( dec_uint64le( src, si ));
+    }
+    public static double dec_doublebe( byte[] src, int si )
+    {
+        return Double.longBitsToDouble( dec_uint64be( src, si ));
+    }
 
-       /* Encode times
-        */
+    /* Encode times
+     */
 
-       public static int enc_time( Date date, byte[] dst, int di, int enc )
-       {
-               long t;
+    public static int enc_time( Date date, byte[] dst, int di, int enc )
+    {
+        long t;
 
-               switch( enc ) {
-                       case TIME_1970_SEC_32BE:
-                               return enc_uint32be( (int)(date.getTime() / 1000L), dst, di );
-                       case TIME_1970_SEC_32LE:
-                               return enc_uint32le( (int)(date.getTime() / 1000L), dst, di );
-                       case TIME_1904_SEC_32BE:
-                               return enc_uint32be( (int)((date.getTime() / 1000L +
-                                       SEC_BETWEEEN_1904_AND_1970) & 0xFFFFFFFF), dst, di );
-                       case TIME_1904_SEC_32LE:
-                               return enc_uint32le( (int)((date.getTime() / 1000L +
-                                       SEC_BETWEEEN_1904_AND_1970) & 0xFFFFFFFF), dst, di );
-                       case TIME_1601_NANOS_64BE:
-                               t = (date.getTime() + MILLISECONDS_BETWEEN_1970_AND_1601) * 10000L;
-                               return enc_uint64be( t, dst, di );
-                       case TIME_1601_NANOS_64LE:
-                               t = (date.getTime() + MILLISECONDS_BETWEEN_1970_AND_1601) * 10000L;
-                               return enc_uint64le( t, dst, di );
-                       case TIME_1970_MILLIS_64BE:
-                               return enc_uint64be( date.getTime(), dst, di );
-                       case TIME_1970_MILLIS_64LE:
-                               return enc_uint64le( date.getTime(), dst, di );
-                       default:
-                               throw new IllegalArgumentException( "Unsupported time encoding" );
-               }
-       }
+        switch( enc ) {
+            case TIME_1970_SEC_32BE:
+                return enc_uint32be( (int)(date.getTime() / 1000L), dst, di );
+            case TIME_1970_SEC_32LE:
+                return enc_uint32le( (int)(date.getTime() / 1000L), dst, di );
+            case TIME_1904_SEC_32BE:
+                return enc_uint32be( (int)((date.getTime() / 1000L +
+                    SEC_BETWEEEN_1904_AND_1970) & 0xFFFFFFFF), dst, di );
+            case TIME_1904_SEC_32LE:
+                return enc_uint32le( (int)((date.getTime() / 1000L +
+                    SEC_BETWEEEN_1904_AND_1970) & 0xFFFFFFFF), dst, di );
+            case TIME_1601_NANOS_64BE:
+                t = (date.getTime() + MILLISECONDS_BETWEEN_1970_AND_1601) * 10000L;
+                return enc_uint64be( t, dst, di );
+            case TIME_1601_NANOS_64LE:
+                t = (date.getTime() + MILLISECONDS_BETWEEN_1970_AND_1601) * 10000L;
+                return enc_uint64le( t, dst, di );
+            case TIME_1970_MILLIS_64BE:
+                return enc_uint64be( date.getTime(), dst, di );
+            case TIME_1970_MILLIS_64LE:
+                return enc_uint64le( date.getTime(), dst, di );
+            default:
+                throw new IllegalArgumentException( "Unsupported time encoding" );
+        }
+    }
 
-       /* Decode times
-        */
+    /* Decode times
+     */
 
-       public static Date dec_time( byte[] src, int si, int enc )
-       {
-               long t;
-       
-               switch( enc ) {
-                       case TIME_1970_SEC_32BE:
-                               return new Date( dec_uint32be( src, si ) * 1000L );
-                       case TIME_1970_SEC_32LE:
-                               return new Date( dec_uint32le( src, si ) * 1000L );
-                       case TIME_1904_SEC_32BE:
-                               return new Date((( dec_uint32be( src, si ) & 0xFFFFFFFFL) -
-                                       SEC_BETWEEEN_1904_AND_1970 ) * 1000L );
-                       case TIME_1904_SEC_32LE:
-                               return new Date((( dec_uint32le( src, si ) & 0xFFFFFFFFL) -
-                                       SEC_BETWEEEN_1904_AND_1970 ) * 1000L );
-                       case TIME_1601_NANOS_64BE:
-                               t = dec_uint64be( src, si );
-                               return new Date( t / 10000L - MILLISECONDS_BETWEEN_1970_AND_1601);
-                       case TIME_1601_NANOS_64LE:
-                               t = dec_uint64le( src, si );
-                               return new Date( t / 10000L - MILLISECONDS_BETWEEN_1970_AND_1601);
-                       case TIME_1970_MILLIS_64BE:
-                               return new Date( dec_uint64be( src, si ));
-                       case TIME_1970_MILLIS_64LE:
-                               return new Date( dec_uint64le( src, si ));
-                       default:
-                               throw new IllegalArgumentException( "Unsupported time encoding" );
-               }
-       }
+    public static Date dec_time( byte[] src, int si, int enc )
+    {
+        long t;
+    
+        switch( enc ) {
+            case TIME_1970_SEC_32BE:
+                return new Date( dec_uint32be( src, si ) * 1000L );
+            case TIME_1970_SEC_32LE:
+                return new Date( dec_uint32le( src, si ) * 1000L );
+            case TIME_1904_SEC_32BE:
+                return new Date((( dec_uint32be( src, si ) & 0xFFFFFFFFL) -
+                    SEC_BETWEEEN_1904_AND_1970 ) * 1000L );
+            case TIME_1904_SEC_32LE:
+                return new Date((( dec_uint32le( src, si ) & 0xFFFFFFFFL) -
+                    SEC_BETWEEEN_1904_AND_1970 ) * 1000L );
+            case TIME_1601_NANOS_64BE:
+                t = dec_uint64be( src, si );
+                return new Date( t / 10000L - MILLISECONDS_BETWEEN_1970_AND_1601);
+            case TIME_1601_NANOS_64LE:
+                t = dec_uint64le( src, si );
+                return new Date( t / 10000L - MILLISECONDS_BETWEEN_1970_AND_1601);
+            case TIME_1970_MILLIS_64BE:
+                return new Date( dec_uint64be( src, si ));
+            case TIME_1970_MILLIS_64LE:
+                return new Date( dec_uint64le( src, si ));
+            default:
+                throw new IllegalArgumentException( "Unsupported time encoding" );
+        }
+    }
 
-       public static int enc_utf8( String str, byte[] dst, int di, int dlim ) throws IOException {
-               int start = di, ch;
-               int strlen = str.length();
+    public static int enc_utf8( String str, byte[] dst, int di, int dlim ) throws IOException {
+        int start = di, ch;
+        int strlen = str.length();
 
-               for( int i = 0; di < dlim && i < strlen; i++ ) {
-                       ch = str.charAt( i );
-                       if ((ch >= 0x0001) && (ch <= 0x007F)) {
-                               dst[di++] = (byte)ch;
-                       } else if (ch > 0x07FF) {
-                               if((dlim - di) < 3 ) {
-                                       break;
-                               }
-                               dst[di++] = (byte)(0xE0 | ((ch >> 12) & 0x0F)); 
-                               dst[di++] = (byte)(0x80 | ((ch >>  6) & 0x3F)); 
-                               dst[di++] = (byte)(0x80 | ((ch >>  0) & 0x3F)); 
-                       } else {
-                               if((dlim - di) < 2 ) {
-                                       break;
-                               }
-                               dst[di++] = (byte)(0xC0 | ((ch >>  6) & 0x1F)); 
-                               dst[di++] = (byte)(0x80 | ((ch >>  0) & 0x3F)); 
-                       }
-               }
+        for( int i = 0; di < dlim && i < strlen; i++ ) {
+            ch = str.charAt( i );
+            if ((ch >= 0x0001) && (ch <= 0x007F)) {
+                dst[di++] = (byte)ch;
+            } else if (ch > 0x07FF) {
+                if((dlim - di) < 3 ) {
+                    break;
+                }
+                dst[di++] = (byte)(0xE0 | ((ch >> 12) & 0x0F)); 
+                dst[di++] = (byte)(0x80 | ((ch >>  6) & 0x3F)); 
+                dst[di++] = (byte)(0x80 | ((ch >>  0) & 0x3F)); 
+            } else {
+                if((dlim - di) < 2 ) {
+                    break;
+                }
+                dst[di++] = (byte)(0xC0 | ((ch >>  6) & 0x1F)); 
+                dst[di++] = (byte)(0x80 | ((ch >>  0) & 0x3F)); 
+            }
+        }
 
-               return di - start;
-       }
-       public static String dec_utf8( byte[] src, int si, int slim ) throws IOException {
-               char[] uni = new char[slim - si];
-               int ui = 0, ch;
+        return di - start;
+    }
+    public static String dec_utf8( byte[] src, int si, int slim ) throws IOException {
+        char[] uni = new char[slim - si];
+        int ui = 0, ch;
 
-               for( ui = 0; si < slim && (ch = src[si++] & 0xFF) != 0; ui++ ) {
-                       if( ch < 0x80 ) {
-                               uni[ui] = (char)ch;
-                       } else if((ch & 0xE0) == 0xC0 ) {
-                               if((slim - si) < 2 ) {
-                                       break;
-                               }
-                               uni[ui] = (char)((ch & 0x1F) << 6);
-                               ch = src[si++] & 0xFF;
-                               uni[ui] |= ch & 0x3F;
-                               if ((ch & 0xC0) != 0x80 || uni[ui] < 0x80 ) {
-                                       throw new IOException( "Invalid UTF-8 sequence" );
-                               }
-                       } else if((ch & 0xF0) == 0xE0 ) {
-                               if((slim - si) < 3 ) {
-                                       break;
-                               }
-                               uni[ui]  = (char)((ch & 0x0F) << 12);
-                               ch = src[si++] & 0xFF;
-                               if ((ch & 0xC0) != 0x80 ) {
-                                       throw new IOException( "Invalid UTF-8 sequence" );
-                               } else {
-                                       uni[ui] |= (ch & 0x3F) << 6;
-                                       ch = src[si++] & 0xFF;
-                                       uni[ui] |=  ch & 0x3F;
-                                       if ((ch & 0xC0) != 0x80 || uni[ui] < 0x800) {
-                                               throw new IOException( "Invalid UTF-8 sequence" );
-                                       }
-                               }
-                       } else {
-                               throw new IOException( "Unsupported UTF-8 sequence" );
-                       }
-               }
+        for( ui = 0; si < slim && (ch = src[si++] & 0xFF) != 0; ui++ ) {
+            if( ch < 0x80 ) {
+                uni[ui] = (char)ch;
+            } else if((ch & 0xE0) == 0xC0 ) {
+                if((slim - si) < 2 ) {
+                    break;
+                }
+                uni[ui] = (char)((ch & 0x1F) << 6);
+                ch = src[si++] & 0xFF;
+                uni[ui] |= ch & 0x3F;
+                if ((ch & 0xC0) != 0x80 || uni[ui] < 0x80 ) {
+                    throw new IOException( "Invalid UTF-8 sequence" );
+                }
+            } else if((ch & 0xF0) == 0xE0 ) {
+                if((slim - si) < 3 ) {
+                    break;
+                }
+                uni[ui]  = (char)((ch & 0x0F) << 12);
+                ch = src[si++] & 0xFF;
+                if ((ch & 0xC0) != 0x80 ) {
+                    throw new IOException( "Invalid UTF-8 sequence" );
+                } else {
+                    uni[ui] |= (ch & 0x3F) << 6;
+                    ch = src[si++] & 0xFF;
+                    uni[ui] |=  ch & 0x3F;
+                    if ((ch & 0xC0) != 0x80 || uni[ui] < 0x800) {
+                        throw new IOException( "Invalid UTF-8 sequence" );
+                    }
+                }
+            } else {
+                throw new IOException( "Unsupported UTF-8 sequence" );
+            }
+        }
 
-               return new String( uni, 0, ui );
-       }
+        return new String( uni, 0, ui );
+    }
 }
index 11c6d38..5a3093f 100644 (file)
@@ -28,89 +28,89 @@ import java.security.MessageDigest;
  */ 
 public class HMACT64 extends MessageDigest implements Cloneable {
 
-       private static final int BLOCK_LENGTH = 64;
-
-       private static final byte IPAD = (byte) 0x36;
-
-       private static final byte OPAD = (byte) 0x5c;
-
-       private MessageDigest md5;
-
-       private byte[] ipad = new byte[BLOCK_LENGTH];
-
-       private byte[] opad = new byte[BLOCK_LENGTH];
-
-       /**
-        * Creates an HMACT64 instance which uses the given secret key material.
-        *
-        * @param key The key material to use in hashing.
-        */
-       public HMACT64(byte[] key) {
-               super("HMACT64");
-               int length = Math.min(key.length, BLOCK_LENGTH);
-               for (int i = 0; i < length; i++) {
-                       ipad[i] = (byte) (key[i] ^ IPAD);
-                       opad[i] = (byte) (key[i] ^ OPAD);
-               }
-               for (int i = length; i < BLOCK_LENGTH; i++) {
-                       ipad[i] = IPAD;
-                       opad[i] = OPAD;
-               }
-               try {
-                       md5 = MessageDigest.getInstance("MD5");
-               } catch (Exception ex) {
-                       throw new IllegalStateException(ex.getMessage());
-               }
-               engineReset();
-       }
-
-       private HMACT64(HMACT64 hmac) throws CloneNotSupportedException {
-               super("HMACT64");
-               this.ipad = hmac.ipad;
-               this.opad = hmac.opad;
-               this.md5 = (MessageDigest) hmac.md5.clone();
-       }
-
-       public Object clone() {
-               try {
-                       return new HMACT64(this);
-               } catch (CloneNotSupportedException ex) {
-                       throw new IllegalStateException(ex.getMessage());
-               }
-       }
-
-       protected byte[] engineDigest() {
-               byte[] digest = md5.digest();
-               md5.update(opad);
-               return md5.digest(digest);
-       }
-
-       protected int engineDigest(byte[] buf, int offset, int len) {
-               byte[] digest = md5.digest();
-               md5.update(opad);
-               md5.update(digest);
-               try {
-                       return md5.digest(buf, offset, len);
-               } catch (Exception ex) {
-                       throw new IllegalStateException();
-               }
-       }
-
-       protected int engineGetDigestLength() {
-               return md5.getDigestLength();
-       }
-
-       protected void engineReset() {
-               md5.reset();
-               md5.update(ipad);
-       }
-
-       protected void engineUpdate(byte b) {
-               md5.update(b);
-       }
-
-       protected void engineUpdate(byte[] input, int offset, int len) {
-               md5.update(input, offset, len);
-       }
+    private static final int BLOCK_LENGTH = 64;
+
+    private static final byte IPAD = (byte) 0x36;
+
+    private static final byte OPAD = (byte) 0x5c;
+
+    private MessageDigest md5;
+
+    private byte[] ipad = new byte[BLOCK_LENGTH];
+
+    private byte[] opad = new byte[BLOCK_LENGTH];
+
+    /**
+     * Creates an HMACT64 instance which uses the given secret key material.
+     *
+     * @param key The key material to use in hashing.
+     */
+    public HMACT64(byte[] key) {
+        super("HMACT64");
+        int length = Math.min(key.length, BLOCK_LENGTH);
+        for (int i = 0; i < length; i++) {
+            ipad[i] = (byte) (key[i] ^ IPAD);
+            opad[i] = (byte) (key[i] ^ OPAD);
+        }
+        for (int i = length; i < BLOCK_LENGTH; i++) {
+            ipad[i] = IPAD;
+            opad[i] = OPAD;
+        }
+        try {
+            md5 = MessageDigest.getInstance("MD5");
+        } catch (Exception ex) {
+            throw new IllegalStateException(ex.getMessage());
+        }
+        engineReset();
+    }
+
+    private HMACT64(HMACT64 hmac) throws CloneNotSupportedException {
+        super("HMACT64");
+        this.ipad = hmac.ipad;
+        this.opad = hmac.opad;
+        this.md5 = (MessageDigest) hmac.md5.clone();
+    }
+
+    public Object clone() {
+        try {
+            return new HMACT64(this);
+        } catch (CloneNotSupportedException ex) {
+            throw new IllegalStateException(ex.getMessage());
+        }
+    }
+
+    protected byte[] engineDigest() {
+        byte[] digest = md5.digest();
+        md5.update(opad);
+        return md5.digest(digest);
+    }
+
+    protected int engineDigest(byte[] buf, int offset, int len) {
+        byte[] digest = md5.digest();
+        md5.update(opad);
+        md5.update(digest);
+        try {
+            return md5.digest(buf, offset, len);
+        } catch (Exception ex) {
+            throw new IllegalStateException();
+        }
+    }
+
+    protected int engineGetDigestLength() {
+        return md5.getDigestLength();
+    }
+
+    protected void engineReset() {
+        md5.reset();
+        md5.update(ipad);
+    }
+
+    protected void engineUpdate(byte b) {
+        md5.update(b);
+    }
+
+    protected void engineUpdate(byte[] input, int offset, int len) {
+        md5.update(input, offset, len);
+    }
 
 }
diff --git a/src/jcifs/util/Hexdump.java b/src/jcifs/util/Hexdump.java
new file mode 100644 (file)
index 0000000..95a783c
--- /dev/null
@@ -0,0 +1,154 @@
+/* jcifs smb client library in Java
+ * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
+ *                     "Christopher R. Hertel" <jcifs at samba dot org>
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package jcifs.util;
+
+import java.io.OutputStream;
+import java.io.PrintStream;
+
+/**
+ */
+
+public class Hexdump {
+
+    private static final String NL = System.getProperty( "line.separator" );
+    private static final int NL_LENGTH = NL.length();
+
+    private static final char[] SPACE_CHARS = {
+        ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
+        ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
+        ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
+    };
+
+    public static final char[] HEX_DIGITS = { 
+        '0', '1', '2', '3', '4', '5',
+        '6', '7', '8', '9', 'A', 'B',
+        'C', 'D', 'E', 'F'
+    };
+
+/** 
+ * Generate "hexdump" output of the buffer at src like the following:
+ *
+ * <p><blockquote><pre>
+ * 00000: 04 d2 29 00 00 01 00 00 00 00 00 01 20 45 47 46  |..)......... EGF|
+ * 00010: 43 45 46 45 45 43 41 43 41 43 41 43 41 43 41 43  |CEFEECACACACACAC|
+ * 00020: 41 43 41 43 41 43 41 43 41 43 41 41 44 00 00 20  |ACACACACACAAD.. |
+ * 00030: 00 01 c0 0c 00 20 00 01 00 00 00 00 00 06 20 00  |..... ........ .|
+ * 00040: ac 22 22 e1                                      |."".            |
+ * </blockquote></pre>
+ */
+
+    public static void hexdump( PrintStream ps, byte[] src, int srcIndex, int length ) {
+        int s = length % 16;
+        int r = ( s == 0 ) ? length / 16 : length / 16 + 1;
+        char[] c = new char[r * (74 + NL_LENGTH)];
+        char[] d = new char[16];
+        int i;
+        int si = 0;
+        int ci = 0;
+
+        do {
+            toHexChars( si, c, ci, 5 );
+            ci += 5;
+            c[ci++] = ':';
+            do {
+                if( si == length ) {
+                    int n = 16 - s;
+                    System.arraycopy( SPACE_CHARS, 0, c, ci, n * 3 );
+                    ci += n * 3;
+                    System.arraycopy( SPACE_CHARS, 0, d, s, n );
+                    break;
+                }
+                c[ci++] = ' ';
+                i = src[srcIndex + si] & 0xFF;
+                toHexChars( i, c, ci, 2 );
+                ci += 2; 
+                if( i < 0 || Character.isISOControl( (char)i )) {
+                    d[si % 16] = '.';
+                } else {
+                    d[si % 16] = (char)i;
+                }
+            } while(( ++si % 16 ) != 0 );
+            c[ci++] = ' ';
+            c[ci++] = ' ';
+            c[ci++] = '|';
+            System.arraycopy( d, 0, c, ci, 16 );
+            ci += 16;
+            c[ci++] = '|';
+            NL.getChars( 0, NL_LENGTH, c, ci );
+            ci += NL_LENGTH;
+        } while( si < length );
+
+        ps.println( c );
+    }
+
+/** 
+ * This is an alternative to the <code>java.lang.Integer.toHexString</cod>
+ * method. It is an efficient relative that also will pad the left side so
+ * that the result is <code>size</code> digits.
+ */ 
+    public static String toHexString( int val, int size ) {
+        char[] c = new char[size];
+        toHexChars( val, c, 0, size );
+        return new String( c );
+    }
+    public static String toHexString( long val, int size ) {
+        char[] c = new char[size];
+        toHexChars( val, c, 0, size );
+        return new String( c );
+    }
+    public static String toHexString( byte[] src, int srcIndex, int size ) {
+        char[] c = new char[size];
+        size = ( size % 2 == 0 ) ? size / 2 : size / 2 + 1;
+        for( int i = 0, j = 0; i < size; i++ ) {
+            c[j++] = HEX_DIGITS[(src[i] >> 4 ) & 0x0F];
+            if( j == c.length ) {
+                break;
+            }
+            c[j++] = HEX_DIGITS[src[i] & 0x0F];
+        }
+        return new String( c );
+    }
+
+/** 
+ * This is the same as {@link jcifs.util.Log#toHexString(int val, int
+ * size)} but provides a more practical form when trying to avoid {@link
+ * java.lang.String} concatenation and {@link java.lang.StringBuffer}.
+ */ 
+
+    public static void toHexChars( int val, char dst[], int dstIndex, int size ) {
+        while( size > 0 ) {
+            dst[dstIndex + size - 1] = HEX_DIGITS[val & 0x000F];
+            if( val != 0 ) {
+                val >>>= 4;
+            }
+            size--;
+        }
+    }
+    public static void toHexChars( long val, char dst[], int dstIndex, int size ) {
+        while( size > 0 ) {
+            dst[dstIndex + size - 1] = HEX_DIGITS[(int)( val & 0x000FL )];
+            if( val != 0 ) {
+                val >>>= 4;
+            }
+            size--;
+        }
+    }
+}
+
diff --git a/src/jcifs/util/Log.java b/src/jcifs/util/Log.java
deleted file mode 100644 (file)
index 4db4ac2..0000000
+++ /dev/null
@@ -1,499 +0,0 @@
-/* jcifs smb client library in Java
- * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
- *                     "Christopher R. Hertel" <jcifs at samba dot org>
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-package jcifs.util;
-
-import java.io.Writer;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.Properties;
-
-/**
- * This log utility uses a combination of bit mask control and io stream
- * functionality. All methods check the mask with the mask passed as a
- * parameter to see if any further worki (logging) should be performed. This
- * provides explicit control at runtime over what is logged. The IO stream
- * model allows the {@link java.io.PrintWriter} to be set and provides
- * many of the common {@link java.io.PrintWriter} methods that are usefull
- * for streams.
- *
- * <p>Three example log entries follow:
- *
- * <blockquote><pre>
- * Jul 7 19:17:40.999 - smb tree connect warning 
- *  path=\\140.240.194.37\IPC$
- * Jul 7 19:17:41.069 - datagram packet sent to: cranes.campus.foo.br/140.240.194.37
- * 00000: 00 06 01 10 00 01 00 00 00 00 00 00 20 43 4B 41  |............ CKA|
- * 00010: 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41  |AAAAAAAAAAAAAAAA|
- * 00020: 41 41 41 41 41 41 41 41 41 41 41 41 41 00 00 21  |AAAAAAAAAAAAA..!|
- * 00030: 00 01                                            |..              |
- * Jul 7 19:17:47.087 - SmbFile exception
- * java.net.UnknownHostException: no name with type 0x20 with no scope for host 140.240.194.37
- *     at jcifs.netbios.NbtAddress.getAllByAddress(NbtAddress.java:618)
- *     at jcifs.smb.SmbFile.list(SmbFile.java:700)
- *     at List.main(List.java:30)
- * </pre></blockquote>
- * 
- * To use this logging facility simply add any
- * <code>Log.println</code>, <code>Log.printHexDump</code>,
- * <code>Log.printStackTrace</code>, or derived methods throughout
- * your code and set a suitable mask with <code>Log.setMask</code>. For
- * example the following mask might be set at the very beginning of your
- * program:
- * 
- * <p><blockquote><pre>
- * Log.setMask(( Log.EXCEPTIONS | foo.Log.ALL ) & ~foo.Log.LOGINS );
- * </pre></blockquote>
- *
- * This would write the stack traces from <code>Log.printStackTrace</code>
- * calls and all logging for package <code>foo</code> with the exception
- * of logging associated with the <code>LOGINS</code> mask. The following
- * is an example of using the <code>Log.println</code> method:
- *
- * <p><blockquote><pre>
- * Log.println( Log.WARNINGS, "smb tree connect warning", " path=" + path );
- * </pre></blockquote>
- *
- * <p>Masks can be combined and subtracted with one another using
- * bitwise operators. To combine two masks use the bitwise OR operator
- * <code>|</code>. The bitwise AND operator <code>&amp;</code> together with
- * bitwise NOT <code>~</code> can be used to turn off masks.
- *
- * <p>If bit manipulation is not familiar, use the <code>addMask</code>
- * and <code>subtractMask</code> methods. The equivalent of the first code
- * sample would be:
- *
- * <p><blockquote><pre>
- * Log.addMask( Log.EXCEPTIONS );
- * Log.addMask( foo.Log.ALL );
- * Log.subtractMask( foo.Log.LOGINS );
- * </pre></blockquote>
- *
- * <p>Note: When defining a new mask, one must take care not to use bits
- * that are already being used by another package. In the future, masks
- * may be statically assigned during class initialization.
- *
- * @see       jcifs.util.LogWriter
- * @see       jcifs.netbios.Log
- * @see       jcifs.smb.Log
- */
-
-public class Log {
-
-    // supress javadoc constructor summary by removing 'protected'
-    protected Log() {}
-
-    private static final char[] hexChars = { 
-        '0', '1', '2', '3', '4', '5',
-        '6', '7', '8', '9', 'A', 'B',
-        'C', 'D', 'E', 'F'
-    };
-    private static final char[] spaceChars = {
-        ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
-        ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
-        ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '
-    };
-
-/**
- * The systems line separator.
- */
-
-    public static final String NL = System.getProperty( "line.separator" );
-
-/**
- * The systems line separator length.
- */
-
-    public static final int NL_LENGTH = NL.length();
-
-/**
- * Mask to indicate that no messages should be logged(not even exceptions).
- */
-
-    public static final int NONE        = 0x00000000;
-
-/**
- * Log all messages.
- */
-
-    public static final int ALL            = 0xFFFFFFFF;
-
-/** 
- * This is the default mask. However, be aware that specifying a
- * mask without adding this mask will result in exceptions not being
- * logged. One should always add this EXCEPTIONS mask to the {@link
- * jcifs.util.Log#setMask(int mask)} expression unless you are explicitly
- * trying to suppress them. Of course only exceptions that go through
- * the {@link jcifs.util.Log#printStackTrace(String desc, Throwable t )}
- * facility can be filtered out.
- */
-
-    public static final int EXCEPTIONS    = 0x10000001;
-
-/**
- * <b>Depricated</b> <i>The jCIFS package no longer uses the
- * <code>CRITICAL_EXCEPTIONS</code> mask. It was invented to compensate
- * for a deficiency in jCIFS that has since been resolved. It will be
- * removed in the next release.</i>
- * <p>
- * Log only critical exceptions. All exceptions logged with
- * <code>printStackTrace</code> are considered critical. Exceptions are not
- * critical if they are logged with the <code>NON_CRITICAL_EXCEPTIONS</code>
- * mask.
- */
-
-       public static final int CRITICAL_EXCEPTIONS = 0x00000001;
-
-/**
- * <b>Depricated</b> <i>The jCIFS package no longer uses the
- * <code>NON_CRITICAL_EXCEPTIONS</code> mask. It was invented to compensate
- * for a deficiency in jCIFS that has since been resolved. It will be
- * removed in the next release.</i>
- * <p>
- * Log non-critical exceptions. The <code>EXCEPTIONS</code> mask consists of both critical and non-critical exceptions.
- */
-
-       public static final int NON_CRITICAL_EXCEPTIONS = 0x10000000;
-
-/**
- * Log warning messages.
- */
-
-    public static final int WARNINGS    = 0x00000002;
-
-/** 
- * Use this mask while actively debugging your code. It is
- * an alternative for the popular <code>System.out.println( "MADE
- * IT!" )</code> statement but can be supressed.
- */
-
-    public static final int DEBUGGING    = 0x00000004;
-
-/** 
- * This controls wheather or not {@link jcifs.util.Log#printHexDump}
- * messages are logged.
- */ 
-
-    public static final int HEX_DUMPS    = 0x00000008;
-
-/** 
- * The shared output stream of all <code>Log</code> classes. The
- * defualt is <code>System.err</code>.
- * <p>
- * <i>This was changed from System.out in jcifs-0.7.0b</i>
- */
-
-    protected static LogWriter out = new LogWriter( System.err );
-
-/** 
- * This is the integer mask that controls what is logged. It is shared
- * by all Log classes. The default mask is <code>EXCEPTIONS</code>
- * which consists of <code>CRITICAL_EXCEPTIONS</code> and
- * <code>NON_CRITICAL_EXCEPTIONS</code>.
- */ 
-
-    protected static int mask = EXCEPTIONS;
-
-    // Setting Methods
-
-/** 
- * Specify an {@link java.io.OutputStream} to be used as the underlying
- * stream. The default <code>OutputStream</code> is
- * <code>System.out</code>. Specify a different stream such as a
- * <code>FileOutputStream</code> perhaps to divert <i>all</i> logging
- * output to a different stream.
- * 
- * @param out the stream to which logging messages are written
- */
-
-    public static void setPrintWriter( OutputStream out ) {
-        Log.out = new LogWriter( out );
-    }
-
-/** 
- * This controls what is passed to {@link java.text.SimpleDateFormat} to
- * control what the timestamp looks like in the log stream. For example, a
- * format of <code>"EEE, MMM d, h:mm:ss a"</code> would generate timestamps
- * that read <code>Tue, Mar 14, 4:57:02 PM</code>. This is a whistle.
- *
- * @param the format string
- * @see   java.util.SimpleDateFormat
- */ 
-
-    public static void setDateFormat( String format ) {
-        out.setDateFormat( format );
-    }
-
-/** 
- * Set the mask used to screen all calls to logging methods. The idea
- * here is that the mask can be specified as an arithmetic expression
- * to provide a crude but effective syslog style way to dictate what is
- * logged. For example:
- * <p><blockquote><pre>
- *  setMask( Log.EXCEPTIONS +
- *           Log.HEX_DUMPS +
- *           jcifs.netbios.Log.PACKET_DATA );
- *
- *  setMask( Log.ALL - jcifs.netbios.Log.PACKET_DIAGRAMS );
- * </pre></blockquote>
- */ 
-
-    public static void setMask( int mask ) {
-        Log.mask = mask;
-    }
-       public static boolean isSet( int mask ) {
-               return ( Log.mask & mask ) == mask;
-       }
-       public static void addMask( int mask ) {
-               Log.mask |= mask;
-       }
-       public static void subtractMask( int mask ) {
-               Log.mask &= ~mask;
-       }
-
-/** 
- * Provides standard way to log any {@link java.lang.Throwable} object like
- * an {@link java.lang.Exception}.
- */
-       public static void printStackTrace( String desc, Throwable t ) {
-        if(( CRITICAL_EXCEPTIONS & mask ) != 0 )
-            out.printStackTrace( desc, t );
-    }
-       public static void printStackTrace( int type, String desc, Throwable t ) {
-        if(( type & mask ) != 0 )
-            out.printStackTrace( desc, t );
-    }
-
-    // Output Methods Used Only By This Package
-/** 
- * Hex dumps are ubiquitous enough to provide a standard and easy-to-use
- * method for logging them. All that is required to use this is setting
- * the mask for {@link jcifs.util.Log#HEX_DUMPS}. The hex dump output is
- * represended in the standard form and is quite efficient. Many mega bytes
- * of source data could be dumped to a file without worry.
- * 
- * <p><blockquote><pre>
- * 00000: 04 d2 29 00 00 01 00 00 00 00 00 01 20 45 47 46  |..)......... EGF|
- * 00010: 43 45 46 45 45 43 41 43 41 43 41 43 41 43 41 43  |CEFEECACACACACAC|
- * 00020: 41 43 41 43 41 43 41 43 41 43 41 41 44 00 00 20  |ACACACACACAAD.. |
- * 00030: 00 01 c0 0c 00 20 00 01 00 00 00 00 00 06 20 00  |..... ........ .|
- * 00040: ac 22 22 e1                                      |."".            |
- * </blockquote></pre>
- */
-
-       public static void printHexDump( String desc, byte[] src ) {
-               printHexDump( desc, src, 0, src.length );
-       }
-    public static void printHexDump( PrintStream ps, String desc, byte[] src, int srcIndex, int length ) {
-        ps.println( desc );
-               printHexDump( ps, src, srcIndex, length );
-       }
-    public static void printHexDump( PrintStream ps, byte[] src, int srcIndex, int length ) {
-        int s = length % 16;
-        int r = ( s == 0 ) ? length / 16 : length / 16 + 1;
-        char[] c = new char[r * (74 + NL_LENGTH)];
-        char[] d = new char[16];
-        int i;
-        int si = 0;
-        int ci = 0;
-        do {
-            toHexChars( si, c, ci, 5 );
-            ci += 5;
-            c[ci++] = ':';
-            do {
-                if( si == length ) {
-                    int n = 16 - s;
-                    System.arraycopy( spaceChars, 0, c, ci, n * 3 );
-                    ci += n * 3;
-                    System.arraycopy( spaceChars, 0, d, s, n );
-                    break;
-                }
-                c[ci++] = ' ';
-                i = src[srcIndex + si] & 0xFF;
-                toHexChars( i, c, ci, 2 );
-                ci += 2; 
-                if( i < 0 || Character.isISOControl( (char)i )) {
-                    d[si % 16] = '.';
-                } else {
-                    d[si % 16] = (char)i;
-                }
-            } while(( ++si % 16 ) != 0 );
-            c[ci++] = ' ';
-            c[ci++] = ' ';
-            c[ci++] = '|';
-            System.arraycopy( d, 0, c, ci, 16 );
-            ci += 16;
-            c[ci++] = '|';
-            NL.getChars( 0, NL_LENGTH, c, ci );
-            ci += NL_LENGTH;
-        } while( si < length );
-        ps.println( c );
-       }
-    public static void printHexDump( String desc, byte[] src, int srcIndex, int length ) {
-        if(( HEX_DUMPS & mask ) == 0 || length == 0 ) {
-            return;
-        }
-        int s = length % 16;
-        int r = ( s == 0 ) ? length / 16 : length / 16 + 1;
-        char[] c = new char[r * (74 + NL_LENGTH)];
-        char[] d = new char[16];
-        int i;
-        int si = 0;
-        int ci = 0;
-        do {
-            toHexChars( si, c, ci, 5 );
-            ci += 5;
-            c[ci++] = ':';
-            do {
-                if( si == length ) {
-                    int n = 16 - s;
-                    System.arraycopy( spaceChars, 0, c, ci, n * 3 );
-                    ci += n * 3;
-                    System.arraycopy( spaceChars, 0, d, s, n );
-                    break;
-                }
-                c[ci++] = ' ';
-                i = src[srcIndex + si] & 0xFF;
-                toHexChars( i, c, ci, 2 );
-                ci += 2; 
-                if( i < 0 || Character.isISOControl( (char)i )) {
-                    d[si % 16] = '.';
-                } else {
-                    d[si % 16] = (char)i;
-                }
-            } while(( ++si % 16 ) != 0 );
-            c[ci++] = ' ';
-            c[ci++] = ' ';
-            c[ci++] = '|';
-            System.arraycopy( d, 0, c, ci, 16 );
-            ci += 16;
-            c[ci++] = '|';
-            NL.getChars( 0, NL_LENGTH, c, ci );
-            ci += NL_LENGTH;
-        } while( si < length );
-        out.println( desc, c );
-    }
-
-/** 
- * This is an alternative to the <code>java.lang.Integer.toHexString</cod>
- * method. It is an efficient relative that also will pad the left side so
- * that the result is <code>size</code> digits.
- */ 
-
-    public static String getHexString( int val, int size ) {
-        char[] c = new char[size];
-        toHexChars( val, c, 0, size );
-        return new String( c );
-    }
-    public static String getHexString( long val, int size ) {
-        char[] c = new char[size];
-        toHexChars( val, c, 0, size );
-        return new String( c );
-    }
-
-       public static String getHexString( byte[] src, int srcIndex, int size ) {
-               char[] c = new char[size];
-               size = ( size % 2 == 0 ) ? size / 2 : size / 2 + 1;
-               for( int i = 0, j = 0; i < size; i++ ) {
-                       c[j++] = hexChars[(src[i] >> 4 ) & 0x0F];
-                       if( j == c.length ) {
-                               break;
-                       }
-                       c[j++] = hexChars[src[i] & 0x0F];
-               }
-               return new String( c );
-       }
-
-/** 
- * This is the same as {@link jcifs.util.Log#getHexString(int val, int
- * size)} but provides a more practical form when trying to avoid {@link
- * java.lang.String} concatenation and {@link java.lang.StringBuffer}.
- */ 
-
-    public static void toHexChars( int val, char dst[], int dstIndex, int size ) {
-        while( size > 0 ) {
-            dst[dstIndex + size - 1] = hexChars[val & 0x000F];
-            if( val != 0 ) {
-                val >>>= 4;
-            }
-            size--;
-        }
-    }
-    public static void toHexChars( long val, char dst[], int dstIndex, int size ) {
-        while( size > 0 ) {
-            dst[dstIndex + size - 1] = hexChars[(int)( val & 0x000FL )];
-            if( val != 0 ) {
-                val >>>= 4;
-            }
-            size--;
-        }
-    }
-
-/** 
- * Print an int. The bits of the integer <code>type</code> must match the
- * {@link jcifs.util.Log#mask}.
- */
-
-    public static void println( int type, String desc, int x ) {
-        if(( type & mask ) != 0 )
-            out.println( desc, x );
-    }
-
-/** 
- * Print a char[] array. The bits of the integer <code>type</code> must
- * match the {@link jcifs.util.Log#mask}.
- */
-    public static void println( int type, String desc, char x[] ) {
-        if(( type & mask ) != 0 )
-            out.println( desc, x );
-    }
-
-/** 
- * Print a {@link java.lang.String}. The bits of the integer
- * <code>type</code> must match the {@link jcifs.util.Log#mask}.
- */
-    public static void println( int type, String desc, String x ) {
-        if(( type & mask ) != 0 )
-            out.println( desc, x );
-    }
-
-/** 
- * Print an {@link java.lang.Object}. The bits of the integer
- * <code>type</code> must match the {@link jcifs.util.Log#mask}.
- */
-    public static void println( int type, String desc, Object x ) {
-        if(( type & mask ) != 0 )
-            out.println( desc, x );
-    }
-
-/**
- * Print the contents of a {@link java.util.Properties} object to the
- * log stream using the <code>store</code> method.
- */
-
-       public static void printProperties( int type, String desc, Properties p ) {
-        if(( type & mask ) != 0 )
-            out.printProperties( desc, p );
-       }
-}
-
diff --git a/src/jcifs/util/LogStream.java b/src/jcifs/util/LogStream.java
new file mode 100644 (file)
index 0000000..92e768b
--- /dev/null
@@ -0,0 +1,58 @@
+/* jcifs smb client library in Java
+ * Copyright (C) 2004  "Michael B. Allen" <jcifs at samba dot org>
+ * 
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ * 
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+package jcifs.util;
+
+import java.io.PrintStream;
+
+/**
+0 - nothing
+1 - critical [default]
+2 - basic info can be logged under load
+3 - almost everything
+N - debugging
+ */
+
+public class LogStream extends PrintStream {
+
+    private static LogStream inst;
+
+    public static int level = 1;
+
+    public LogStream( PrintStream stream ) {
+        super( stream );
+    }
+
+    public static void setLevel( int level ) {
+        LogStream.level = level;
+    }
+    /**
+     * This must be called before <tt>getInstance</tt> is called or
+     * it will have no effect.
+     */
+    public static void setInstance( PrintStream stream ) {
+        inst = new LogStream( stream );
+    }
+    public static LogStream getInstance() {
+        if( inst == null ) {
+            setInstance( System.err );
+        }
+        return inst;
+    }
+}
+
diff --git a/src/jcifs/util/LogWriter.java b/src/jcifs/util/LogWriter.java
deleted file mode 100644 (file)
index c232b57..0000000
+++ /dev/null
@@ -1,294 +0,0 @@
-/* jcifs smb client library in Java
- * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-package jcifs.util;
-
-import java.io.*;
-import java.util.GregorianCalendar;
-import java.util.Date;
-import java.text.SimpleDateFormat;
-import java.util.Properties;
-
-/** 
- * This class is basically a {@link java.io.PrintWriter} that prepends
- * a timestamp before each message is written to the underlying
- * stream. The methods for printing are a pertainent subset from {@link
- * java.io.PrintWriter}.
- *
- * @see jcifs.util.Log
- */
-public class LogWriter {
-
-    private Writer out;
-       private OutputStream raw;
-    private PrintWriter eout;
-    private boolean trouble = false;
-    private String lineSeparator;
-
-/**
- * The object used to synchronize operations on this stream
- */
-
-    public Object lock;
-
-/** 
- * Create a new <code>LogWriter</code> instance that uses the specified
- * output stream as it's underlying stream
- */
-    public LogWriter( OutputStream out ) {
-        this.out = new OutputStreamWriter( out );
-               raw = out;
-               this.lock = this;
-        eout = new PrintWriter( out );
-        lineSeparator = System.getProperty( "line.separator" );
-    }
-
-    static String dateString;
-    static GregorianCalendar cal;
-    static SimpleDateFormat sdf;
-
-    static {
-        cal = new GregorianCalendar();
-        setDateFormat( "MMM d HH:mm:ss.SSS" );
-    }
-
-/** 
- * Set the date format used to render the timestamp written with each
- * message.
- * 
- * @param format the format string used
- * @see java.text.SimpleDateFormat
- */
-    public static void setDateFormat( String format ) {
-        sdf = new SimpleDateFormat( format );
-        sdf.setCalendar( cal );
-    }
-
-    private void ensureOpen() throws IOException {
-        if( out == null )
-            throw new IOException( "Stream closed" );
-    }
-
-/**
- * Close the stream
- */
-
-    public void close() {
-        try {
-            synchronized( lock ) {
-                if( out == null )
-                    return;
-                out.close();
-                out = null;
-            }
-        } catch( IOException x ) {
-            trouble = true;
-        }
-    }
-
-/**
- * Flush the stream and check error state
- */
-
-    public boolean checkError() {
-        if( out != null ) {
-            try {
-                synchronized( lock ) {
-                    ensureOpen();
-                    out.flush();
-                }
-            } catch( IOException x ) {
-                trouble = true;
-            }
-        }
-        return trouble;
-    }
-
-/** 
- * Indicate that an error has occured
- */
-
-    public void setError() {
-        trouble = true;
-    }
-
-/**
- * This is a pervasive enough feature for a logging utility that it is
- * built in.
- *
- * @param desc a brief description of the source of the message to follow
- * @param t the <code>Exception</code> to obtain the message to be printed from
- */
-
-    public void printStackTrace( String desc, Throwable t ) {
-        try {
-            synchronized( lock ) {
-                ensureOpen();
-                out.write( sdf.format( new Date() ));
-                out.write( " - " );
-                out.write( desc );
-                out.write( lineSeparator );
-                               eout.flush();
-                out.flush();
-                t.printStackTrace( eout );
-                               eout.flush();
-                out.flush();
-            }
-        } catch( InterruptedIOException x ) {
-            Thread.currentThread().interrupt();
-        } catch( IOException ioe ) {
-            trouble = true;
-        }
-    }
-
-
-
-/** 
- * Print an <code>int</code> to the log stream. Keep in mind that every
- * call to a <code>PrintWriter</code> like method will print a new timestamp.
- * Using several calls together will not concatonate several messages
- * together under one timestamp.
- *
- * @param desc a brief description of the source of the message to follow
- * @param i the <code>int</code> to print
- */
-    public void println( String desc, int i ) {
-        try {
-            synchronized( lock ) {
-                ensureOpen();
-                out.write( sdf.format( new Date() ));
-                out.write( " - " );
-                out.write( desc );
-                out.write( lineSeparator );
-                out.write( Integer.toString( i ));
-                out.write( lineSeparator );
-                out.flush();
-            }
-        } catch( InterruptedIOException x ) {
-            Thread.currentThread().interrupt();
-        } catch( IOException ioe ) {
-            trouble = true;
-        }
-    }
-
-/** 
- * Print an array of <code>char</code> to the log.
- * 
- * @param desc a brief description of the source of the message to follow
- * @param c the message
- */
-    public void println( String desc, char c[] ) {
-        try {
-            synchronized( lock ) {
-                ensureOpen();
-                out.write( sdf.format( new Date() ));
-                out.write( " - " );
-                out.write( desc );
-                out.write( lineSeparator );
-                out.write( c );
-                out.write( lineSeparator );
-                out.flush();
-            }
-        } catch( InterruptedIOException x ) {
-            Thread.currentThread().interrupt();
-        } catch( IOException ioe ) {
-            trouble = true;
-        }
-    }
-
-/** 
- * Print a <code>String</code> to the log.
- * 
- * @param desc a brief description of the source of the message to follow
- * @param s the string message
- */ 
-
-    public void println( String desc, String s ) {
-        try {
-            synchronized( lock ) {
-                ensureOpen();
-                out.write( sdf.format( new Date() ));
-                out.write( " - " );
-                out.write( desc );
-                out.write( lineSeparator );
-                               if( s != null ) {
-                       out.write( s );
-                       out.write( lineSeparator );
-                               }
-                out.flush();
-            }
-        } catch( InterruptedIOException x ) {
-            Thread.currentThread().interrupt();
-        } catch( IOException ioe ) {
-            trouble = true;
-        }
-    }
-
-/** 
- * Print the string representation of an <code>Object</code> to the screen.
- *
- * @param desc a general description of the source of the message
- * @param o the <code>Object</code> to print
- */
-    public void println( String desc, Object o ) {
-        try {
-            synchronized( lock ) {
-                ensureOpen();
-                out.write( sdf.format( new Date() ));
-                out.write( " - " );
-                out.write( desc );
-                out.write( lineSeparator );
-                               if (o != null ) {
-                       out.write( String.valueOf( o ));
-                       out.write( lineSeparator );
-                               }
-                out.flush();
-            }
-        } catch( InterruptedIOException x ) {
-            Thread.currentThread().interrupt();
-        } catch( IOException ioe ) {
-            trouble = true;
-        }
-    }
-/**
- * Print the contents of a {@link java.util.Properties} object to the
- * log stream using the <code>store</code> method.
- */
-
-       public void printProperties( String desc, Properties p ) {
-        try {
-            synchronized( lock ) {
-                ensureOpen();
-                p.save( raw, desc );
-                out.write( lineSeparator );
-                out.flush();
-            }
-        } catch( InterruptedIOException x ) {
-            Thread.currentThread().interrupt();
-        } catch( IOException ioe ) {
-            trouble = true;
-        }
-    }
-}
-
index 3eff0b2..e7e8474 100644 (file)
@@ -23,101 +23,101 @@ import java.io.IOException;
 
 public class MimeMap {
 
-       static final int IN_SIZE = 7000;
+    private static final int IN_SIZE = 7000;
 
-       static final int ST_START = 1;
-       static final int ST_COMM = 2;
-       static final int ST_TYPE = 3;
-       static final int ST_GAP = 4;
-       static final int ST_EXT = 5;
+    private static final int ST_START = 1;
+    private static final int ST_COMM = 2;
+    private static final int ST_TYPE = 3;
+    private static final int ST_GAP = 4;
+    private static final int ST_EXT = 5;
 
-       byte[] in;
-       int inLen;
+    private byte[] in;
+    private int inLen;
 
-       public MimeMap() throws IOException {
-               int n;
+    public MimeMap() throws IOException {
+        int n;
 
-               in = new byte[IN_SIZE];
-               InputStream is = getClass().getClassLoader().getResourceAsStream( "jcifs/util/mime.map" );
+        in = new byte[IN_SIZE];
+        InputStream is = getClass().getClassLoader().getResourceAsStream( "jcifs/util/mime.map" );
 
-               inLen = 0;
-               while(( n = is.read( in, inLen, IN_SIZE - inLen )) != -1 ) {
-                       inLen += n;
-               }
-               if( inLen < 100 || inLen == IN_SIZE ) {
-                       throw new IOException( "Error reading jcifs/util/mime.map resource" );
-               }
-               is.close();
-       }
+        inLen = 0;
+        while(( n = is.read( in, inLen, IN_SIZE - inLen )) != -1 ) {
+            inLen += n;
+        }
+        if( inLen < 100 || inLen == IN_SIZE ) {
+            throw new IOException( "Error reading jcifs/util/mime.map resource" );
+        }
+        is.close();
+    }
 
-       public String getMimeType( String extension ) throws IOException {
-               return getMimeType( extension, "application/octet-stream" );
-       }
-       public String getMimeType( String extension, String def ) throws IOException {
-               int state, t, x, i, off;
-               byte ch;
-               byte[] type = new byte[128];
-               byte[] buf = new byte[16];
-               byte[] ext = extension.toLowerCase().getBytes( "ASCII" );
+    public String getMimeType( String extension ) throws IOException {
+        return getMimeType( extension, "application/octet-stream" );
+    }
+    public String getMimeType( String extension, String def ) throws IOException {
+        int state, t, x, i, off;
+        byte ch;
+        byte[] type = new byte[128];
+        byte[] buf = new byte[16];
+        byte[] ext = extension.toLowerCase().getBytes( "ASCII" );
 
-               state = ST_START;
-               t = x = i = 0;
-               for( off = 0; off < inLen; off++ ) {
-                       ch = in[off];
-                       switch( state ) {
-                               case ST_START:
-                                       if( ch == ' ' || ch == '\t' ) {
-                                               break;
-                                       } else if( ch == '#' ) {
-                                               state = ST_COMM;
-                                               break;
-                                       }
-                                       state = ST_TYPE;
-                               case ST_TYPE:
-                                       if( ch == ' ' || ch == '\t' ) {
-                                               state = ST_GAP;
-                                       } else {
-                                               type[t++] = ch;
-                                       }
-                                       break;
-                               case ST_COMM:
-                                       if( ch == '\n' ) {
-                                               t = x = i = 0;
-                                               state = ST_START;
-                                       }
-                                       break;
-                               case ST_GAP:
-                                       if( ch == ' ' || ch == '\t' ) {
-                                               break;
-                                       }
-                                       state = ST_EXT;
-                               case ST_EXT:
-                                       switch( ch ) {
-                                               case ' ':
-                                               case '\t':
-                                               case '\n':
-                                               case '#':
-                                                       for( i = 0; i < x && x == ext.length && buf[i] == ext[i]; i++ ) {
-                                                               ;
-                                                       }
-                                                       if( i == ext.length ) {
-                                                               return new String( type, 0, t, "ASCII" );
-                                                       }
-                                                       if( ch == '#' ) {
-                                                               state = ST_COMM;
-                                                       } else if( ch == '\n' ) {
-                                                               t = x = i = 0;
-                                                               state = ST_START;
-                                                       }
-                                                       x = 0;
-                                                       break;
-                                               default:
-                                                       buf[x++] = ch;
-                                       }
-                                       break;
-                       }
-               }
-               return def;
-       }
+        state = ST_START;
+        t = x = i = 0;
+        for( off = 0; off < inLen; off++ ) {
+            ch = in[off];
+            switch( state ) {
+                case ST_START:
+                    if( ch == ' ' || ch == '\t' ) {
+                        break;
+                    } else if( ch == '#' ) {
+                        state = ST_COMM;
+                        break;
+                    }
+                    state = ST_TYPE;
+                case ST_TYPE:
+                    if( ch == ' ' || ch == '\t' ) {
+                        state = ST_GAP;
+                    } else {
+                        type[t++] = ch;
+                    }
+                    break;
+                case ST_COMM:
+                    if( ch == '\n' ) {
+                        t = x = i = 0;
+                        state = ST_START;
+                    }
+                    break;
+                case ST_GAP:
+                    if( ch == ' ' || ch == '\t' ) {
+                        break;
+                    }
+                    state = ST_EXT;
+                case ST_EXT:
+                    switch( ch ) {
+                        case ' ':
+                        case '\t':
+                        case '\n':
+                        case '#':
+                            for( i = 0; i < x && x == ext.length && buf[i] == ext[i]; i++ ) {
+                                ;
+                            }
+                            if( i == ext.length ) {
+                                return new String( type, 0, t, "ASCII" );
+                            }
+                            if( ch == '#' ) {
+                                state = ST_COMM;
+                            } else if( ch == '\n' ) {
+                                t = x = i = 0;
+                                state = ST_START;
+                            }
+                            x = 0;
+                            break;
+                        default:
+                            buf[x++] = ch;
+                    }
+                    break;
+            }
+        }
+        return def;
+    }
 }
 
diff --git a/src/jcifs/util/PropertiesTree.java b/src/jcifs/util/PropertiesTree.java
deleted file mode 100644 (file)
index eb41629..0000000
+++ /dev/null
@@ -1,575 +0,0 @@
-/* jcifs smb client library in Java
- * Copyright (C) 2000  "Michael B. Allen" <jcifs at samba dot org>
- * 
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- * 
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Lesser General Public License for more details.
- * 
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-
-package jcifs.util;
-
-import java.util.Properties;
-import java.util.Hashtable;
-import java.util.Vector;
-import java.util.Enumeration;
-import java.io.OutputStream;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.io.IOException;
-import java.util.Date;
-
-/**
- *
- * 
- * This class is backwords compatible with {@link java.util.Properties}
- * however another dimension is added by using the customary dot '.' as
- * an operator to alternativly represent properties as trees. In essance
- * it gives meaning to the '.' used in keys of properties whereas with
- * traditional properties usage of the dot '.' was mearly a convention. This
- * allows applications to organize there data in new ways. The following
- * is an example of the "tagged" output from a PropertiesTree along with
- * traditional output from the same PropertiesTree to
- * it's right. PropertiesTree can load and store
- * both formats at runtime(e.g. load traditional and then store tagged).
- * 
- * <p><table border="1" cellpadding="3" cellspacing="0" width="100%"><tr><td>
- * <pre>
- * #Feed Processor Config
- * #Sun Dec 31 00:48:23 EST 2000
- *
- * proxy=192.168.1.15
- * &lt;net&gt;
- *     username=joe
- *     &lt;smb&gt;
- *         host=doc-storage
- *         username=kelly
- *     &lt;/smb&gt;
- *     &lt;ftp&gt;
- *         host=feed10.research.com
- *     &lt;/ftp&gt;
- * &lt;/net&gt;
- * </pre>
- * 
- * </td><td>
- * 
- * <pre>
- * #Feed Processor Config
- * #Sun Dec 31 00:59:31 EST 2000
- *
- * proxy=192.168.1.15
- * net.username=joe
- * net.smb.host=doc-storage
- * net.smb.username=kelly
- * net.ftp.host=feed10.research.com
- * </pre>
- * 
- * </td></tr></table>
- *
- * <p>In the above example, if <code>getProperty( "net.ftp.username" )</code>
- * was called "joe" would be returned. The <code>get</code> method walks
- * up the tree searching for the first match. So the following:
- * 
- * <pre>
- *     net.ftp.username
- *     net.username
- *     username
- * </pre>
- * 
- * are basically equivalent and thus backwords compatible with
- * java.util.Properties.
- *
- * <p>The benifit of using <code>PropertiesTree</code> as opposed to <code>Properties</code> is that a child property can mask a parent
- * property resulting in sophisticated hierarchial relationships. This is true of the <code>net.smb.username</code> property.
- * It might also be thought of as overloading <code>net.username</code>
- * with <code>net.smb.username</code> but only for the smb branch.
- *
- * <p>See the <a href="../../../properties.html">PropertiesTree</a> document for details.
- */
-
-public class PropertiesTree extends Properties {
-
-       private static final String INDENT = "    ";
-       private static final int TRUNC = 70;
-
-       String label;
-       private PropertiesTree parent;
-
-       private void listTagged( String indent, PrintStream out ) {
-               Vector sections = new Vector(0);
-               for( Enumeration e = keys(); e.hasMoreElements(); ) {
-                       String key = (String)e.nextElement();
-                       Object value = get( key );
-                       if( value instanceof PropertiesTree ) {
-                               sections.addElement( value );
-                       } else {
-                               String s;
-                               s = indent + key + "=" + (String)value;
-                               s = s.length() > TRUNC ? s.substring( 0, TRUNC - 3 ) + "..." : s;
-                               out.println( s );
-                       }
-               }
-               for( Enumeration e1 = sections.elements(); e1.hasMoreElements(); ) {
-                       String s;
-                       PropertiesTree p = (PropertiesTree)e1.nextElement();
-
-                       s = indent + "<" + p.label + ">";
-                       s = s.length() > TRUNC ? s.substring( 0, TRUNC - 3 ) + "..." : s;
-                       out.println( s );
-
-                       p.list0( indent + INDENT, out );
-
-                       s = indent + "</" + p.label + ">";
-                       s = s.length() > TRUNC ? s.substring( 0, TRUNC - 3 ) + "..." : s;
-                       out.println( s );
-               }
-       }
-       private void list0( String prefix, PrintStream out ) {
-               Vector sections = new Vector(0);
-               for( Enumeration e = keys(); e.hasMoreElements(); ) {
-                       String key = (String)e.nextElement();
-                       Object value = get( key );
-                       if( value == null ) {
-                       } else if( value instanceof PropertiesTree ) {
-                               sections.addElement( value );
-                       } else {
-                               if( prefix != null ) {
-                                       key = prefix + "." + key;
-                               }
-                               String s = (String)value;
-                               s = s.length() > TRUNC ? s.substring( 0, TRUNC - 3 ) + "..." : s;
-                               out.println( key + "=" + s );
-                       }
-               }
-               for( Enumeration e1 = sections.elements(); e1.hasMoreElements(); ) {
-                       PropertiesTree p = (PropertiesTree)e1.nextElement();
-                       p.list0( prefix == null ? p.label : prefix + "." + p.label, out );
-               }
-       }
-       private synchronized void saveTagged( String indent, PrintWriter out ) {
-               Vector sections = new Vector(0);
-               for( Enumeration e = keys(); e.hasMoreElements(); ) {
-                       String key = (String)e.nextElement();
-                       Object value = get( key );
-                       if( value == null ) {
-                               value = "";
-                       }
-                       if( value instanceof PropertiesTree ) {
-                               sections.addElement( value );
-                       } else if( value instanceof String ) {
-                               out.print( indent );
-                               out.print( key );
-                               out.write( '=' );
-
-                               String val = (String)value;
-                               int len = val.length();
-                               boolean empty = false;
-
-                               for (int i = 0 ; i < len ; i++) {
-                                       int ch = val.charAt(i);
-
-                                       switch (ch) {
-                                               case '\\': out.write('\\'); out.write('\\'); break;
-                                               case '\t': out.write('\\'); out.write('t'); break;
-                                               case '\n': out.write('\\'); out.write('n'); break;
-                                               case '\r': out.write('\\'); out.write('r'); break;
-
-                                               default:
-                                                       if ((ch < ' ') || (ch >= 127) || (empty && (ch == ' '))) {
-                                                               if( ch > 255 ) {
-                                                                       out.write(ch);
-                                                               } else {
-                                                                       out.write('\\');
-                                                                       out.write('u');
-                                                                       out.write(toHex((ch >> 12) & 0xF));
-                                                                       out.write(toHex((ch >>  8) & 0xF));
-                                                                       out.write(toHex((ch >>  4) & 0xF));
-                                                                       out.write(toHex((ch >>  0) & 0xF));
-                                                               }
-                                                       } else {
-                                                               out.write(ch);
-                                                       }
-                                       }
-                                       empty = false;
-                               }
-                               out.write('\n');
-                               out.flush();
-                       } else {
-                               System.err.println( "error: " + key + "=" + value );
-                       }
-               }
-               for( Enumeration e1 = sections.elements(); e1.hasMoreElements(); ) {
-                       PropertiesTree p = (PropertiesTree)e1.nextElement();
-                       out.println( indent + "<" + p.label + ">" );
-                       p.saveTagged( indent + INDENT, out );
-                       out.println( indent + "</" + p.label + ">" );
-               }
-       }
-       private synchronized void save0( String prefix, PrintWriter out ) {
-               Vector sections = new Vector(0);
-               for( Enumeration e = keys(); e.hasMoreElements(); ) {
-                       String key = (String)e.nextElement();
-                       Object value = get( key );
-                       if( value == null ) {
-                               value = "";
-                       }
-                       if( value instanceof PropertiesTree ) {
-                               sections.addElement( value );
-                       } else if( value instanceof String ) {
-                               if( prefix != null ) {
-                                       out.print( prefix );
-                                       out.write( '.' );
-                               }
-                               out.print( key );
-                               out.write( '=' );
-
-                               String val = (String)value;
-                               int len = val.length();
-                               boolean empty = false;
-
-                               for (int i = 0 ; i < len ; i++) {
-                                       int ch = val.charAt(i);
-
-                                       switch (ch) {
-                                               case '\\': out.write('\\'); out.write('\\'); break;
-                                               case '\t': out.write('\\'); out.write('t'); break;
-                                               case '\n': out.write('\\'); out.write('n'); break;
-                                               case '\r': out.write('\\'); out.write('r'); break;
-
-                                               default:
-                                                       if ((ch < ' ') || (ch >= 127) || (empty && (ch == ' '))) {
-                                                               if( ch > 255 ) {
-                                                                       out.write(ch);
-                                                               } else {
-                                                                       out.write('\\');
-                                                                       out.write('u');
-                                                                       out.write(toHex((ch >> 12) & 0xF));
-                                                                       out.write(toHex((ch >>  8) & 0xF));
-                                                                       out.write(toHex((ch >>  4) & 0xF));
-                                                                       out.write(toHex((ch >>  0) & 0xF));
-                                                               }
-                                                       } else {
-                                                               out.write(ch);
-                                                       }
-                                       }
-                                       empty = false;
-                               }
-                               out.write('\n');
-                               out.flush();
-                       } else {
-                               System.out.println( "error: " + key + "=" + value );
-                       }
-               }
-               for( Enumeration e1 = sections.elements(); e1.hasMoreElements(); ) {
-                       PropertiesTree p = (PropertiesTree)e1.nextElement();
-                       p.save0( prefix == null ? p.label : prefix + "." + p.label, out );
-               }
-       }
-       private static char toHex(int nibble) {
-               return hexDigit[(nibble & 0xF)];
-       }
-       private static char[] hexDigit = {
-               '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
-       };
-
-       /**
-        * Construct an empty properties tree with no values.
-        */
-
-       public PropertiesTree() {
-               this.label = null;
-               this.parent = null;
-       }
-
-       /** 
-        * Put a key and value into the tree. If the key contains a dot
-        * '.', new tree nodes will be automatically created to accomodate.
-        */ 
-
-       public synchronized Object put( Object key, Object value ) {
-               String s = (String)key;
-               String l;
-               Object o;
-               PropertiesTree p;
-               int d;
-               if(( d = s.indexOf( '.' )) > -1 ) {
-                       l = s.substring( 0, d );
-                       o = super.get( l );
-                       if( o != null && o instanceof PropertiesTree ) {
-                               p = (PropertiesTree)o;
-                       } else if( o != null ) {
-                               throw new IllegalArgumentException( "property exists: " +
-                                                                                       l + "=" + (String)o );
-                       } else {
-                               p = new PropertiesTree();
-                               p.label = l;
-                               p.parent = this;
-                               super.put( l, p );
-                       }
-                       return p.put( s.substring( d + 1 ), value );
-               } else {
-                       Object x;
-                       o = super.get( s );
-                       if( o != null && o instanceof PropertiesTree ) {
-                               throw new IllegalArgumentException( "property tree exists: " + s );
-                       }
-                       if( value instanceof PropertiesTree ) {
-                               ((PropertiesTree)value).label = (String)key;
-                               ((PropertiesTree)value).parent = this;
-                       }
-                       x = super.put( key, value );
-                       return x;
-               }
-       }
-
-       /** 
-        * Retrieved the property specified by the key parameter, seraching parent
-        * nodes if necessary.
-        */ 
-
-       public synchronized Object get( Object key ) {
-               String s = (String)key;
-               int d;
-               if(( d = s.indexOf( '.' )) > 0 ) {
-                       Object o = super.get( s.substring( 0, d ));
-                       if( o == null ) {
-                               return get( s.substring( d + 1 ));
-                       } else if( o instanceof PropertiesTree ) {
-                               return ((PropertiesTree)o).get( s.substring( d + 1 ));
-                       }
-               } else {
-                       Object o = super.get( s );
-                       if( o == null && parent != null ) {
-                               return parent.get( s );
-                       } else if( o instanceof PropertiesTree ||
-                                       (  o instanceof String && ((String)o).length() > 0 )) {
-                               return o;
-                       }
-               }
-               return null;
-       }
-
-       /**
-        * Retrieve a property from the tree by searching parent nodes
-        * if necessary and return the value as a String.
-        */
-
-       public String getProperty( String key ) {
-               Object o = get( key );
-               return o == null ? null : (String)o;
-       }
-
-       /** 
-        * Retrieve a property from the tree by searching parent nodes if necessary
-        * and return the value as a String. If the keys value is not found, the
-        * default parameter will be returned.
-        */ 
-
-       public String getProperty( String key, String defaultValue ) {
-               Object o = get( key );
-               return o == null ? defaultValue : (String)o;
-       }
-
-       /** 
-        * List all properties in the traditional output format and truncated to
-        * ensure the contents fit within the display.
-        */ 
-
-       public void list( PrintStream out ) {
-               out.println("-- listing properties tree --");
-               list0( null, out );
-       }
-
-       /** 
-        * Save this properties tree to the specified OutputStream. The header
-        * parameter will be printed at the top as a comment.
-        */ 
-
-       public synchronized void store( OutputStream out, String header ) {
-               store( out, header, false );
-       }
-
-       /** 
-        * Write this properties tree to the specified OutputStream. The header
-        * parameter will be printed at the top as a comment. If the boolean
-        * parameter is true the output will be stored in tagged format as shown
-        * in the example at the top of this page.
-        */ 
-
-       public synchronized void store( OutputStream out, String header, boolean tagged ) {
-               PrintWriter prnt = new PrintWriter( out, true );
-               if( header != null ) {
-                       prnt.write( '#' );
-                       prnt.println( header );
-               }
-               prnt.write( '#' );
-               prnt.println( new Date() );
-               if( tagged ) {
-                       saveTagged( "", prnt );
-               } else {
-                       save0( null, prnt );
-               }
-       }
-
-       /** 
-        * Load all properties from the provided InputStream. The text read may be
-        * either tagged format, traditional format, or a mixture of both.
-        */ 
-
-       public synchronized void load( InputStream in ) throws IOException {
-               int buflen = 80;
-               char[] buf = new char[buflen];
-               int bufindx = 0;
-               boolean intag = false;
-               String section = null;
-
-               int ch = in.read();
-               while( true ) {
-                       switch( ch ) {
-                               case -1:
-                                       if( section != null ) {
-                                               throw new IOException( "expecting end tag" );
-                                       }
-                                       return;
-                               case '<':
-                                       intag = true;
-                                       ch = in.read();
-                                       continue;
-                               case '#':
-                               case ';':
-                                       do {
-                                               ch = in.read();
-                                       } while(( ch >= 0 ) && ( ch != '\n' ) && ( ch != '\r' ));
-                                       continue;
-
-                               case '\n':
-                               case '\r':
-                               case ' ':
-                               case '\t':
-                                       ch = in.read();
-                                       continue;
-                       }
-
-                       bufindx = 0;
-                       while(( ch >= 0 ) && ( ch != '=' ) && ( ch != ':' ) && ( ch != ' ' ) &&
-                                                               ( ch != '\t' ) && ( ch != '\n' ) && ( ch != '\r' )) {
-                               if( intag && ch == '>' ) {
-                                       ch = in.read();
-                                       break;
-                               }
-                               if( bufindx >= buflen ) {
-                                       buflen *= 2;
-                                       char[] nbuf = new char[buflen];
-                                       System.arraycopy( buf, 0, nbuf, 0, buf.length );
-                                       buf = nbuf;
-                               }
-                               buf[bufindx++] = (char)ch;
-                               ch = in.read();
-                       }
-                       String key = new String( buf, 0, bufindx );
-                       if( intag ) {
-                               if( key.startsWith( "/" )) {
-                                       int s;
-                                       // chop off end tag from current section
-                                       if( section != null && section.regionMatches(
-                                                       ( s = section.lastIndexOf( '.' )) + 1, key, 1, key.length() - 1 )) {
-                                               section = s < 1 ? null : section.substring( 0, s );
-                                       } else {
-                                               throw new IOException( "unexpected end tag: </" + key + ">" );
-                                       }
-                               } else {
-                                       section = section == null ? key : section + "." + key;
-                               }
-                               intag = false;
-                               continue;
-                       }
-
-                       while(( ch == ' ' ) || ( ch == '\t' )) {
-                               ch = in.read();
-                       }
-                       if(( ch == '=' ) || ( ch == ':' )) {
-                               ch = in.read();
-                       }
-                       while(( ch == ' ' ) || ( ch == '\t' )) {
-                               ch = in.read();
-                       }
-
-                       bufindx = 0;
-                       while(( ch >= 0 ) && ( ch != '\n' ) && ( ch != '\r' )) {
-                               int next = 0;
-                               if( ch == '\\' ) {
-                                       switch( ch = in.read() ) {
-                                               case '\r':
-                                                       if((( ch = in.read() ) == '\n' ) ||
-                                                                       ( ch == ' ' ) || ( ch == '\t' )) {
-                                                       } else continue;
-                                               case '\n': 
-                                                       while((( ch = in.read() ) == ' ') || ( ch == '\t' ));
-                                                       continue;
-                                               case 't': ch = '\t'; next = in.read(); break;
-                                               case 'n': ch = '\n'; next = in.read(); break;
-                                               case 'r': ch = '\r'; next = in.read(); break;
-                                               case 'u': {
-                                                       while ((ch = in.read()) == 'u');
-                                                       int d = 0;
-                                                       loop:
-                                                               for (int i = 0 ; i < 4 ; i++) {
-                                                                       next = in.read();
-                                                                       switch (ch) {
-                                                                               case '0': case '1': case '2': case '3': case '4':
-                                                                               case '5': case '6': case '7': case '8': case '9':
-                                                                                       d = (d << 4) + ch - '0';
-                                                                                       break;
-                                                                               case 'a': case 'b': case 'c':
-                                                                               case 'd': case 'e': case 'f':
-                                                                                       d = (d << 4) + 10 + ch - 'a';
-                                                                                       break;
-                                                                               case 'A': case 'B': case 'C':
-                                                                               case 'D': case 'E': case 'F':
-                                                                                       d = (d << 4) + 10 + ch - 'A';
-                                                                                       break;
-                                                                               default:
-                                                                                       break loop;
-                                                                       }       
-                                                                       ch = next;
-                                                               }
-                                                               ch = d;
-                                                               break;
-                                               }
-                                               default:
-                                                       next = in.read();
-                                                       break;
-                                       }
-                               } else {
-                                       next = in.read();
-                               }
-                               if (bufindx >= buflen) {
-                                       buflen *= 2;
-                                       char[] nbuf = new char[buflen];
-                                       System.arraycopy(buf, 0, nbuf, 0, buf.length);
-                                       buf = nbuf;
-                               }
-                               buf[bufindx++] = (char)ch;
-                               ch = next;
-                       }
-                       String val = new String(buf, 0, bufindx);
-
-                       if( section != null ) {
-                               put( section + '.' + key, val );
-                       } else {
-                               put( key, val );
-                       }
-               }
-       }
-}