update sharpcifs

This commit is contained in:
Luke Pulverenti 2017-07-08 03:25:24 -04:00
parent a7187180bf
commit 71eb9f143f
220 changed files with 23703 additions and 25613 deletions

View File

@ -228,7 +228,6 @@
<Compile Include="IO\SharpCifs\Smb\WinError.cs" /> <Compile Include="IO\SharpCifs\Smb\WinError.cs" />
<Compile Include="IO\SharpCifs\UniAddress.cs" /> <Compile Include="IO\SharpCifs\UniAddress.cs" />
<Compile Include="IO\SharpCifs\Util\Base64.cs" /> <Compile Include="IO\SharpCifs\Util\Base64.cs" />
<Compile Include="IO\SharpCifs\Util\DbsHelper\Log.cs" />
<Compile Include="IO\SharpCifs\Util\DES.cs" /> <Compile Include="IO\SharpCifs\Util\DES.cs" />
<Compile Include="IO\SharpCifs\Util\Encdec.cs" /> <Compile Include="IO\SharpCifs\Util\Encdec.cs" />
<Compile Include="IO\SharpCifs\Util\Hexdump.cs" /> <Compile Include="IO\SharpCifs\Util\Hexdump.cs" />

View File

@ -21,17 +21,14 @@ namespace SharpCifs.Dcerpc
{ {
public class DcerpcBind : DcerpcMessage public class DcerpcBind : DcerpcMessage
{ {
internal static readonly string[] ResultMessage = internal static readonly string[] ResultMessage = { "0", "DCERPC_BIND_ERR_ABSTRACT_SYNTAX_NOT_SUPPORTED"
{ , "DCERPC_BIND_ERR_PROPOSED_TRANSFER_SYNTAXES_NOT_SUPPORTED", "DCERPC_BIND_ERR_LOCAL_LIMIT_EXCEEDED"
"0",
"DCERPC_BIND_ERR_ABSTRACT_SYNTAX_NOT_SUPPORTED",
"DCERPC_BIND_ERR_PROPOSED_TRANSFER_SYNTAXES_NOT_SUPPORTED",
"DCERPC_BIND_ERR_LOCAL_LIMIT_EXCEEDED"
}; };
internal static string GetResultMessage(int result) internal static string GetResultMessage(int result)
{ {
return result < 4 ? ResultMessage[result] : "0x" + Hexdump.ToHexString(result, 4); return result < 4 ? ResultMessage[result] : "0x" + Hexdump.ToHexString(result, 4
);
} }
public override DcerpcException GetResult() public override DcerpcException GetResult()

View File

@ -103,8 +103,7 @@ namespace SharpCifs.Dcerpc
public override string ToString() public override string ToString()
{ {
/* /* string ret = proto + ":" + server + "[" + endpoint;
string ret = proto + ":" + server + "[" + endpoint;
if (options != null) if (options != null)
{ {
Iterator iter = (Iterator) options.Keys.GetEnumerator(); Iterator iter = (Iterator) options.Keys.GetEnumerator();
@ -116,8 +115,7 @@ namespace SharpCifs.Dcerpc
} }
} }
ret += "]"; ret += "]";
return ret; return ret; */
*/
return null; return null;
} }
} }

View File

@ -18,7 +18,8 @@ namespace SharpCifs.Dcerpc
{ {
public static class DcerpcConstants public static class DcerpcConstants
{ {
public static Uuid DcerpcUuidSyntaxNdr = new Uuid("8a885d04-1ceb-11c9-9fe8-08002b104860"); public static Uuid DcerpcUuidSyntaxNdr = new Uuid("8a885d04-1ceb-11c9-9fe8-08002b104860"
);
public static int DcerpcFirstFrag = unchecked(0x01); public static int DcerpcFirstFrag = unchecked(0x01);

View File

@ -36,29 +36,13 @@ namespace SharpCifs.Dcerpc
public static int DcerpcFaultProtoError = unchecked(0x1c01000b); public static int DcerpcFaultProtoError = unchecked(0x1c01000b);
public static int[] DcerpcFaultCodes = { public static int[] DcerpcFaultCodes = { DcerpcFaultOther, DcerpcFaultAccessDenied
DcerpcFaultOther, , DcerpcFaultCantPerform, DcerpcFaultNdr, DcerpcFaultInvalidTag, DcerpcFaultContextMismatch
DcerpcFaultAccessDenied, , DcerpcFaultOpRngError, DcerpcFaultUnkIf, DcerpcFaultProtoError };
DcerpcFaultCantPerform,
DcerpcFaultNdr,
DcerpcFaultInvalidTag,
DcerpcFaultContextMismatch,
DcerpcFaultOpRngError,
DcerpcFaultUnkIf,
DcerpcFaultProtoError
};
public static string[] DcerpcFaultMessages = public static string[] DcerpcFaultMessages = { "DCERPC_FAULT_OTHER"
{ , "DCERPC_FAULT_ACCESS_DENIED", "DCERPC_FAULT_CANT_PERFORM", "DCERPC_FAULT_NDR",
"DCERPC_FAULT_OTHER", "DCERPC_FAULT_INVALID_TAG", "DCERPC_FAULT_CONTEXT_MISMATCH", "DCERPC_FAULT_OP_RNG_ERROR"
"DCERPC_FAULT_ACCESS_DENIED", , "DCERPC_FAULT_UNK_IF", "DCERPC_FAULT_PROTO_ERROR" };
"DCERPC_FAULT_CANT_PERFORM",
"DCERPC_FAULT_NDR",
"DCERPC_FAULT_INVALID_TAG",
"DCERPC_FAULT_CONTEXT_MISMATCH",
"DCERPC_FAULT_OP_RNG_ERROR",
"DCERPC_FAULT_UNK_IF",
"DCERPC_FAULT_PROTO_ERROR"
};
} }
} }

View File

@ -213,10 +213,8 @@ namespace SharpCifs.Dcerpc
{ {
msg.Flags &= ~DcerpcConstants.DcerpcFirstFrag; msg.Flags &= ~DcerpcConstants.DcerpcFirstFrag;
} }
if ( if ((msg.Flags & (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag)) != (DcerpcConstants.DcerpcFirstFrag |
(msg.Flags & (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag)) DcerpcConstants.DcerpcLastFrag))
!= (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag)
)
{ {
buf.Start = off; buf.Start = off;
buf.Reset(); buf.Reset();
@ -317,7 +315,8 @@ namespace SharpCifs.Dcerpc
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
protected internal abstract void DoSendFragment(byte[] buf, int off, int length, bool isDirect); protected internal abstract void DoSendFragment(byte[] buf, int off, int length,
bool isDirect);
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
protected internal abstract void DoReceiveFragment(byte[] buf, bool isDirect); protected internal abstract void DoReceiveFragment(byte[] buf, bool isDirect);

View File

@ -38,7 +38,8 @@ namespace SharpCifs.Dcerpc
public DcerpcPipeHandle(string url, NtlmPasswordAuthentication auth) public DcerpcPipeHandle(string url, NtlmPasswordAuthentication auth)
{ {
Binding = ParseBinding(url); Binding = ParseBinding(url);
url = "smb://" + Binding.Server + "/IPC$/" + Runtime.Substring(Binding.Endpoint, 6); url = "smb://" + Binding.Server + "/IPC$/" + Runtime.Substring(Binding.Endpoint
, 6);
string @params = string.Empty; string @params = string.Empty;
string server; string server;
string address; string address;
@ -56,15 +57,13 @@ namespace SharpCifs.Dcerpc
{ {
url += "?" + Runtime.Substring(@params, 1); url += "?" + Runtime.Substring(@params, 1);
} }
Pipe = new SmbNamedPipe(url, Pipe = new SmbNamedPipe(url, (unchecked(0x2019F) << 16) | SmbNamedPipe.PipeTypeRdwr
(unchecked(0x2019F) << 16) | SmbNamedPipe.PipeTypeDceTransact, auth);
| SmbNamedPipe.PipeTypeRdwr
| SmbNamedPipe.PipeTypeDceTransact,
auth);
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
protected internal override void DoSendFragment(byte[] buf, int off, int length, bool isDirect) protected internal override void DoSendFragment(byte[] buf, int off, int length,
bool isDirect)
{ {
if (Out != null && Out.IsOpen() == false) if (Out != null && Out.IsOpen() == false)
{ {

View File

@ -22,13 +22,9 @@ namespace SharpCifs.Dcerpc.Msrpc
{ {
internal Sid[] sids; internal Sid[] sids;
public MsrpcLookupSids(LsaPolicyHandle policyHandle, Sid[] sids) public MsrpcLookupSids(LsaPolicyHandle policyHandle, Sid[] sids) : base(policyHandle
: base(policyHandle, , new LsarSidArrayX(sids), new Lsarpc.LsarRefDomainList(), new Lsarpc.LsarTransNameArray
new LsarSidArrayX(sids), (), 1, sids.Length)
new Lsarpc.LsarRefDomainList(),
new Lsarpc.LsarTransNameArray(),
1,
sids.Length)
{ {
this.sids = sids; this.sids = sids;
Ptype = 0; Ptype = 0;

View File

@ -18,11 +18,8 @@ namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcLsarOpenPolicy2 : Lsarpc.LsarOpenPolicy2 public class MsrpcLsarOpenPolicy2 : Lsarpc.LsarOpenPolicy2
{ {
public MsrpcLsarOpenPolicy2(string server, int access, LsaPolicyHandle policyHandle) public MsrpcLsarOpenPolicy2(string server, int access, LsaPolicyHandle policyHandle
: base(server, ) : base(server, new Lsarpc.LsarObjectAttributes(), access, policyHandle)
new Lsarpc.LsarObjectAttributes(),
access,
policyHandle)
{ {
ObjectAttributes.Length = 24; ObjectAttributes.Length = 24;
Lsarpc.LsarQosInfo qos = new Lsarpc.LsarQosInfo(); Lsarpc.LsarQosInfo qos = new Lsarpc.LsarQosInfo();

View File

@ -20,8 +20,8 @@ namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcQueryInformationPolicy : Lsarpc.LsarQueryInformationPolicy public class MsrpcQueryInformationPolicy : Lsarpc.LsarQueryInformationPolicy
{ {
public MsrpcQueryInformationPolicy(LsaPolicyHandle policyHandle, short level, NdrObject info) public MsrpcQueryInformationPolicy(LsaPolicyHandle policyHandle, short level, NdrObject
: base(policyHandle, level, info) info) : base(policyHandle, level, info)
{ {
Ptype = 0; Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;

View File

@ -18,8 +18,8 @@ namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcSamrConnect2 : Samr.SamrConnect2 public class MsrpcSamrConnect2 : Samr.SamrConnect2
{ {
public MsrpcSamrConnect2(string server, int access, SamrPolicyHandle policyHandle) public MsrpcSamrConnect2(string server, int access, SamrPolicyHandle policyHandle
: base(server, access, policyHandle) ) : base(server, access, policyHandle)
{ {
Ptype = 0; Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;

View File

@ -18,8 +18,8 @@ namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcSamrConnect4 : Samr.SamrConnect4 public class MsrpcSamrConnect4 : Samr.SamrConnect4
{ {
public MsrpcSamrConnect4(string server, int access, SamrPolicyHandle policyHandle) public MsrpcSamrConnect4(string server, int access, SamrPolicyHandle policyHandle
: base(server, 2, access, policyHandle) ) : base(server, 2, access, policyHandle)
{ {
Ptype = 0; Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;

View File

@ -18,11 +18,8 @@ namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcSamrOpenAlias : Samr.SamrOpenAlias public class MsrpcSamrOpenAlias : Samr.SamrOpenAlias
{ {
public MsrpcSamrOpenAlias(SamrDomainHandle handle, public MsrpcSamrOpenAlias(SamrDomainHandle handle, int access, int rid, SamrAliasHandle
int access, aliasHandle) : base(handle, access, rid, aliasHandle)
int rid,
SamrAliasHandle aliasHandle)
: base(handle, access, rid, aliasHandle)
{ {
Ptype = 0; Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;

View File

@ -18,11 +18,8 @@ namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcSamrOpenDomain : Samr.SamrOpenDomain public class MsrpcSamrOpenDomain : Samr.SamrOpenDomain
{ {
public MsrpcSamrOpenDomain(SamrPolicyHandle handle, public MsrpcSamrOpenDomain(SamrPolicyHandle handle, int access, Rpc.SidT sid, SamrDomainHandle
int access, domainHandle) : base(handle, access, sid, domainHandle)
Rpc.SidT sid,
SamrDomainHandle domainHandle)
: base(handle, access, sid, domainHandle)
{ {
Ptype = 0; Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;

View File

@ -33,8 +33,8 @@ namespace SharpCifs.Dcerpc.Msrpc
private readonly MsrpcShareEnum _enclosing; private readonly MsrpcShareEnum _enclosing;
} }
public MsrpcShareEnum(string server) public MsrpcShareEnum(string server) : base("\\\\" + server, 1, new Srvsvc.ShareInfoCtr1
: base("\\\\" + server, 1, new Srvsvc.ShareInfoCtr1(), -1, 0, 0) (), -1, 0, 0)
{ {
Ptype = 0; Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;

View File

@ -20,8 +20,8 @@ namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcShareGetInfo : Srvsvc.ShareGetInfo public class MsrpcShareGetInfo : Srvsvc.ShareGetInfo
{ {
public MsrpcShareGetInfo(string server, string sharename) public MsrpcShareGetInfo(string server, string sharename) : base(server, sharename
: base(server, sharename, 502, new Srvsvc.ShareInfo502()) , 502, new Srvsvc.ShareInfo502())
{ {
Ptype = 0; Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;

View File

@ -103,7 +103,8 @@ namespace SharpCifs.Dcerpc.Msrpc
public Rpc.PolicyHandle Handle; public Rpc.PolicyHandle Handle;
public SamrConnect2(string systemName, int accessMask, Rpc.PolicyHandle handle) public SamrConnect2(string systemName, int accessMask, Rpc.PolicyHandle handle
)
{ {
this.SystemName = systemName; this.SystemName = systemName;
this.AccessMask = accessMask; this.AccessMask = accessMask;
@ -146,7 +147,8 @@ namespace SharpCifs.Dcerpc.Msrpc
public Rpc.PolicyHandle Handle; public Rpc.PolicyHandle Handle;
public SamrConnect4(string systemName, int unknown, int accessMask, Rpc.PolicyHandle handle) public SamrConnect4(string systemName, int unknown, int accessMask, Rpc.PolicyHandle
handle)
{ {
this.SystemName = systemName; this.SystemName = systemName;
this.Unknown = unknown; this.Unknown = unknown;
@ -191,10 +193,8 @@ namespace SharpCifs.Dcerpc.Msrpc
public Rpc.PolicyHandle DomainHandle; public Rpc.PolicyHandle DomainHandle;
public SamrOpenDomain(Rpc.PolicyHandle handle, public SamrOpenDomain(Rpc.PolicyHandle handle, int accessMask, Rpc.SidT sid, Rpc.PolicyHandle
int accessMask, domainHandle)
Rpc.SidT sid,
Rpc.PolicyHandle domainHandle)
{ {
this.Handle = handle; this.Handle = handle;
this.AccessMask = accessMask; this.AccessMask = accessMask;
@ -367,11 +367,8 @@ namespace SharpCifs.Dcerpc.Msrpc
public int NumEntries; public int NumEntries;
public SamrEnumerateAliasesInDomain(Rpc.PolicyHandle domainHandle, public SamrEnumerateAliasesInDomain(Rpc.PolicyHandle domainHandle, int resumeHandle
int resumeHandle, , int acctFlags, SamrSamArray sam, int numEntries)
int acctFlags,
SamrSamArray sam,
int numEntries)
{ {
this.DomainHandle = domainHandle; this.DomainHandle = domainHandle;
this.ResumeHandle = resumeHandle; this.ResumeHandle = resumeHandle;
@ -423,10 +420,8 @@ namespace SharpCifs.Dcerpc.Msrpc
public Rpc.PolicyHandle AliasHandle; public Rpc.PolicyHandle AliasHandle;
public SamrOpenAlias(Rpc.PolicyHandle domainHandle, public SamrOpenAlias(Rpc.PolicyHandle domainHandle, int accessMask, int rid, Rpc.PolicyHandle
int accessMask, aliasHandle)
int rid,
Rpc.PolicyHandle aliasHandle)
{ {
this.DomainHandle = domainHandle; this.DomainHandle = domainHandle;
this.AccessMask = accessMask; this.AccessMask = accessMask;
@ -463,7 +458,8 @@ namespace SharpCifs.Dcerpc.Msrpc
public Lsarpc.LsarSidArray Sids; public Lsarpc.LsarSidArray Sids;
public SamrGetMembersInAlias(Rpc.PolicyHandle aliasHandle, Lsarpc.LsarSidArray sids) public SamrGetMembersInAlias(Rpc.PolicyHandle aliasHandle, Lsarpc.LsarSidArray
sids)
{ {
this.AliasHandle = aliasHandle; this.AliasHandle = aliasHandle;
this.Sids = sids; this.Sids = sids;

View File

@ -21,10 +21,8 @@ namespace SharpCifs.Dcerpc.Msrpc
public class SamrAliasHandle : Rpc.PolicyHandle public class SamrAliasHandle : Rpc.PolicyHandle
{ {
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public SamrAliasHandle(DcerpcHandle handle, public SamrAliasHandle(DcerpcHandle handle, SamrDomainHandle domainHandle, int access
SamrDomainHandle domainHandle, , int rid)
int access,
int rid)
{ {
MsrpcSamrOpenAlias rpc = new MsrpcSamrOpenAlias(domainHandle, access, rid, this); MsrpcSamrOpenAlias rpc = new MsrpcSamrOpenAlias(domainHandle, access, rid, this);
handle.Sendrecv(rpc); handle.Sendrecv(rpc);

View File

@ -21,12 +21,11 @@ namespace SharpCifs.Dcerpc.Msrpc
public class SamrDomainHandle : Rpc.PolicyHandle public class SamrDomainHandle : Rpc.PolicyHandle
{ {
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public SamrDomainHandle(DcerpcHandle handle, public SamrDomainHandle(DcerpcHandle handle, SamrPolicyHandle policyHandle, int access
SamrPolicyHandle policyHandle, , Rpc.SidT sid)
int access,
Rpc.SidT sid)
{ {
MsrpcSamrOpenDomain rpc = new MsrpcSamrOpenDomain(policyHandle, access, sid, this); MsrpcSamrOpenDomain rpc = new MsrpcSamrOpenDomain(policyHandle, access, sid, this
);
handle.Sendrecv(rpc); handle.Sendrecv(rpc);
if (rpc.Retval != 0) if (rpc.Retval != 0)
{ {

View File

@ -430,12 +430,8 @@ namespace SharpCifs.Dcerpc.Msrpc
public int ResumeHandle; public int ResumeHandle;
public ShareEnumAll(string servername, public ShareEnumAll(string servername, int level, NdrObject info, int prefmaxlen,
int level, int totalentries, int resumeHandle)
NdrObject info,
int prefmaxlen,
int totalentries,
int resumeHandle)
{ {
this.Servername = servername; this.Servername = servername;
this.Level = level; this.Level = level;
@ -504,7 +500,8 @@ namespace SharpCifs.Dcerpc.Msrpc
public NdrObject Info; public NdrObject Info;
public ShareGetInfo(string servername, string sharename, int level, NdrObject info) public ShareGetInfo(string servername, string sharename, int level, NdrObject info
)
{ {
this.Servername = servername; this.Servername = servername;
this.Sharename = sharename; this.Sharename = sharename;

View File

@ -214,7 +214,8 @@ namespace SharpCifs.Dcerpc.Ndr
i += 4; i += 4;
try try
{ {
Array.Copy(Runtime.GetBytesForString(s, "UTF-16LE"), 0, Buf, i, len * 2); Array.Copy(Runtime.GetBytesForString(s, "UTF-16LE"), 0, Buf, i, len
* 2);
} }
catch (UnsupportedEncodingException) catch (UnsupportedEncodingException)
{ {

View File

@ -78,12 +78,8 @@ namespace SharpCifs.Dcerpc
return value; return value;
} }
internal static readonly char[] Hexchars = internal static readonly char[] Hexchars = { '0', '1', '2', '3', '4',
{ '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
'0', '1', '2', '3', '4',
'5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'
};
public static string Bin_to_hex(int value, int length) public static string Bin_to_hex(int value, int length)
{ {
@ -142,17 +138,11 @@ namespace SharpCifs.Dcerpc
public override string ToString() public override string ToString()
{ {
return Bin_to_hex(TimeLow, 8) return Bin_to_hex(TimeLow, 8) + '-' + Bin_to_hex(TimeMid, 4) + '-' + Bin_to_hex
+ '-' + Bin_to_hex(TimeMid, 4) (TimeHiAndVersion, 4) + '-' + Bin_to_hex(ClockSeqHiAndReserved, 2) + Bin_to_hex
+ '-' + Bin_to_hex(TimeHiAndVersion, 4) (ClockSeqLow, 2) + '-' + Bin_to_hex(Node[0], 2) + Bin_to_hex(Node[1], 2) + Bin_to_hex
+ '-' + Bin_to_hex(ClockSeqHiAndReserved, 2) (Node[2], 2) + Bin_to_hex(Node[3], 2) + Bin_to_hex(Node[4], 2) + Bin_to_hex(Node
+ Bin_to_hex(ClockSeqLow, 2) [5], 2);
+ '-' + Bin_to_hex(Node[0], 2)
+ Bin_to_hex(Node[1], 2)
+ Bin_to_hex(Node[2], 2)
+ Bin_to_hex(Node[3], 2)
+ Bin_to_hex(Node[4], 2)
+ Bin_to_hex(Node[5], 2);
} }
} }
} }

View File

@ -23,7 +23,8 @@ namespace SharpCifs.Netbios
{ {
public class Lmhosts public class Lmhosts
{ {
private static readonly string Filename = Config.GetProperty("jcifs.netbios.lmhosts"); private static readonly string Filename = Config.GetProperty("jcifs.netbios.lmhosts"
);
private static readonly Hashtable Tab = new Hashtable(); private static readonly Hashtable Tab = new Hashtable();

View File

@ -27,11 +27,11 @@ namespace SharpCifs.Netbios
private const int ScopeOffset = 33; private const int ScopeOffset = 33;
private static readonly string DefaultScope private static readonly string DefaultScope = Config.GetProperty("jcifs.netbios.scope"
= Config.GetProperty("jcifs.netbios.scope"); );
internal static readonly string OemEncoding internal static readonly string OemEncoding = Config.GetProperty("jcifs.encoding"
= Config.GetProperty("jcifs.encoding", Runtime.GetProperty("file.encoding")); , Runtime.GetProperty("file.encoding"));
public string name; public string name;
@ -69,20 +69,19 @@ namespace SharpCifs.Netbios
int i; int i;
for (i = 0; i < tmp.Length; i++) for (i = 0; i < tmp.Length; i++)
{ {
dst[dstIndex + (2 * i + 1)] dst[dstIndex + (2 * i + 1)] = unchecked((byte)(((tmp[i] & unchecked(0xF0))
= unchecked((byte)(((tmp[i] & unchecked(0xF0)) >> 4) + unchecked(0x41))); >> 4) + unchecked(0x41)));
dst[dstIndex + (2 * i + 2)] dst[dstIndex + (2 * i + 2)] = unchecked((byte)((tmp[i] & unchecked(0x0F))
= unchecked((byte)((tmp[i] & unchecked(0x0F)) + unchecked(0x41))); + unchecked(0x41)));
} }
for (; i < 15; i++) for (; i < 15; i++)
{ {
dst[dstIndex + (2 * i + 1)] = unchecked(unchecked(0x43)); dst[dstIndex + (2 * i + 1)] = unchecked(unchecked(0x43));
dst[dstIndex + (2 * i + 2)] = unchecked(unchecked(0x41)); dst[dstIndex + (2 * i + 2)] = unchecked(unchecked(0x41));
} }
dst[dstIndex + TypeOffset] dst[dstIndex + TypeOffset] = unchecked((byte)(((HexCode & unchecked(0xF0)
= unchecked((byte)(((HexCode & unchecked(0xF0)) >> 4) + unchecked(0x41))); ) >> 4) + unchecked(0x41)));
dst[dstIndex + TypeOffset + 1] dst[dstIndex + TypeOffset + 1] = unchecked((byte)((HexCode & unchecked(0x0F)) + unchecked(0x41)));
= unchecked((byte)((HexCode & unchecked(0x0F)) + unchecked(0x41)));
} }
catch (UnsupportedEncodingException) catch (UnsupportedEncodingException)
{ {
@ -96,17 +95,10 @@ namespace SharpCifs.Netbios
int length = 15; int length = 15;
for (int i = 0; i < 15; i++) for (int i = 0; i < 15; i++)
{ {
tmp[i] = unchecked( tmp[i] = unchecked((byte)(((src[srcIndex + (2 * i + 1)] & unchecked(0xFF))
(byte)( - unchecked(0x41)) << 4));
((src[srcIndex + (2 * i + 1)] & unchecked(0xFF)) - unchecked(0x41)) << 4 tmp[i] |= unchecked((byte)(((src[srcIndex + (2 * i + 2)] & unchecked(0xFF)
) ) - unchecked(0x41)) & unchecked(0x0F)));
);
tmp[i] |= unchecked(
(byte)(
((src[srcIndex + (2 * i + 2)] & unchecked(0xFF)) - unchecked(0x41))
& unchecked(0x0F)
)
);
if (tmp[i] != unchecked((byte)' ')) if (tmp[i] != unchecked((byte)' '))
{ {
length = i + 1; length = i + 1;
@ -121,8 +113,8 @@ namespace SharpCifs.Netbios
{ {
} }
HexCode = ((src[srcIndex + TypeOffset] & unchecked(0xFF)) - unchecked(0x41)) << 4; HexCode = ((src[srcIndex + TypeOffset] & unchecked(0xFF)) - unchecked(0x41)) << 4;
HexCode |= ((src[srcIndex + TypeOffset + 1] & unchecked(0xFF)) - unchecked(0x41)) HexCode |= ((src[srcIndex + TypeOffset + 1] & unchecked(0xFF)) - unchecked(
& unchecked(0x0F); 0x41)) & unchecked(0x0F);
return ScopeOffset + ReadScopeWireFormat(src, srcIndex + ScopeOffset); return ScopeOffset + ReadScopeWireFormat(src, srcIndex + ScopeOffset);
} }
@ -138,8 +130,9 @@ namespace SharpCifs.Netbios
{ {
name = Runtime.GetStringForBytes(tmp, 0, length).Trim(); name = Runtime.GetStringForBytes(tmp, 0, length).Trim();
} }
catch (Exception) catch (Exception ex)
{ {
} }
HexCode = src[srcIndex + length]; HexCode = src[srcIndex + length];
@ -159,8 +152,8 @@ namespace SharpCifs.Netbios
dst[dstIndex++] = unchecked((byte)('.')); dst[dstIndex++] = unchecked((byte)('.'));
try try
{ {
Array.Copy(Runtime.GetBytesForString(Scope, OemEncoding), Array.Copy(Runtime.GetBytesForString(Scope, OemEncoding
0, dst, dstIndex, Scope.Length); ), 0, dst, dstIndex, Scope.Length);
} }
catch (UnsupportedEncodingException) catch (UnsupportedEncodingException)
{ {

View File

@ -61,7 +61,8 @@ namespace SharpCifs.Netbios
public override string ToString() public override string ToString()
{ {
return "NameQueryResponse[" + base.ToString() + ",addrEntry=" + AddrEntry + "]"; return "NameQueryResponse[" + base.ToString() + ",addrEntry=" + AddrEntry
+ "]";
} }
} }
} }

View File

@ -21,13 +21,10 @@ using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using SharpCifs.Smb;
using SharpCifs.Util; using SharpCifs.Util;
using SharpCifs.Util.DbsHelper;
using SharpCifs.Util.Sharpen; using SharpCifs.Util.Sharpen;
using Thread = SharpCifs.Util.Sharpen.Thread; using Thread = SharpCifs.Util.Sharpen.Thread;
using System.Threading.Tasks;
namespace SharpCifs.Netbios namespace SharpCifs.Netbios
{ {
@ -51,29 +48,27 @@ namespace SharpCifs.Netbios
internal const int ResolverWins = 3; internal const int ResolverWins = 3;
private static readonly int SndBufSize private static readonly int SndBufSize = Config.GetInt("jcifs.netbios.snd_buf_size"
= Config.GetInt("jcifs.netbios.snd_buf_size", DefaultSndBufSize); , DefaultSndBufSize);
private static readonly int RcvBufSize private static readonly int RcvBufSize = Config.GetInt("jcifs.netbios.rcv_buf_size"
= Config.GetInt("jcifs.netbios.rcv_buf_size", DefaultRcvBufSize); , DefaultRcvBufSize);
private static readonly int SoTimeout private static readonly int SoTimeout = Config.GetInt("jcifs.netbios.soTimeout",
= Config.GetInt("jcifs.netbios.soTimeout", DefaultSoTimeout); DefaultSoTimeout);
private static readonly int RetryCount private static readonly int RetryCount = Config.GetInt("jcifs.netbios.retryCount"
= Config.GetInt("jcifs.netbios.retryCount", DefaultRetryCount); , DefaultRetryCount);
private static readonly int RetryTimeout private static readonly int RetryTimeout = Config.GetInt("jcifs.netbios.retryTimeout"
= Config.GetInt("jcifs.netbios.retryTimeout", DefaultRetryTimeout); , DefaultRetryTimeout);
private static readonly int Lport private static readonly int Lport = Config.GetInt("jcifs.netbios.lport", 137);
= Config.GetInt("jcifs.netbios.lport", 137);
private static readonly IPAddress Laddr private static readonly IPAddress Laddr = Config.GetInetAddress("jcifs.netbios.laddr"
= Config.GetInetAddress("jcifs.netbios.laddr", null); , null);
private static readonly string Ro private static readonly string Ro = Config.GetProperty("jcifs.resolveOrder");
= Config.GetProperty("jcifs.resolveOrder");
private static LogStream _log = LogStream.GetInstance(); private static LogStream _log = LogStream.GetInstance();
@ -87,7 +82,7 @@ namespace SharpCifs.Netbios
private byte[] _rcvBuf; private byte[] _rcvBuf;
private SocketEx _socketSender; private SocketEx _socket;
private Hashtable _responseTable = new Hashtable(); private Hashtable _responseTable = new Hashtable();
@ -99,8 +94,6 @@ namespace SharpCifs.Netbios
private bool _waitResponse = true; private bool _waitResponse = true;
private bool _isActive = false;
private AutoResetEvent _autoResetWaitReceive; private AutoResetEvent _autoResetWaitReceive;
internal IPAddress laddr; internal IPAddress laddr;
@ -118,15 +111,11 @@ namespace SharpCifs.Netbios
this.laddr = laddr this.laddr = laddr
?? Config.GetLocalHost() ?? Config.GetLocalHost()
?? Extensions.GetLocalAddresses()?.FirstOrDefault(); ?? Extensions.GetAddressesByName(Dns.GetHostName()).FirstOrDefault();
if (this.laddr == null)
throw new ArgumentNullException("IPAddress NOT found. if exec on localhost, set vallue to [jcifs.smb.client.laddr]");
try try
{ {
Baddr = Config.GetInetAddress("jcifs.netbios.baddr", Baddr = Config.GetInetAddress("jcifs.netbios.baddr", Extensions.GetAddressByName("255.255.255.255"));
Extensions.GetAddressByName("255.255.255.255"));
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -172,8 +161,8 @@ namespace SharpCifs.Netbios
{ {
if (_log.Level > 1) if (_log.Level > 1)
{ {
_log.WriteLine("NetBIOS resolveOrder specifies WINS however the " _log.WriteLine("NetBIOS resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set"
+ "jcifs.netbios.wins property has not been set"); );
} }
continue; continue;
} }
@ -219,93 +208,53 @@ namespace SharpCifs.Netbios
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal virtual void EnsureOpen(int timeout) internal virtual void EnsureOpen(int timeout)
{ {
//Log.Out($"NameServiceClient.EnsureOpen");
_closeTimeout = 0; _closeTimeout = 0;
if (SoTimeout != 0) if (SoTimeout != 0)
{ {
_closeTimeout = Math.Max(SoTimeout, timeout); _closeTimeout = Math.Max(SoTimeout, timeout);
} }
var localPort = (SmbConstants.Lport == 0) ? _lport : SmbConstants.Lport;
// If socket is still good, the new closeTimeout will // If socket is still good, the new closeTimeout will
// be ignored; see tryClose comment. // be ignored; see tryClose comment.
if ( if (_socket == null)
_socketSender == null
|| _socketSender.LocalEndPoint == null
|| _socketSender.GetLocalPort() != localPort
|| !IPAddress.Any.Equals(_socketSender.GetLocalInetAddress())
)
{ {
if (_socketSender != null) _socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
{
_socketSender.Dispose();
_socketSender = null;
}
_socketSender = new SocketEx(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
_socketSender.Bind(new IPEndPoint(IPAddress.Any, localPort));
//IPAddress.`Address` property deleted
//_socket.Bind(new IPEndPoint(laddr.Address, _lport));
_socket.Bind(new IPEndPoint(laddr, _lport));
if (_waitResponse) if (_waitResponse)
{ {
if (_thread != null) _thread = new Thread(this); //new Sharpen.Thread(this, "JCIFS-NameServiceClient");
{
_thread.Cancel(true);
_thread.Dispose();
}
_thread = new Thread(this);
_thread.SetDaemon(true); _thread.SetDaemon(true);
_thread.Start(true); _thread.Start();
} }
} }
} }
internal virtual void TryClose() internal virtual void TryClose()
{ {
//Log.Out("NameSerciceClient.TryClose");
if (this._isActive)
{
//Log.Out("NameSerciceClient.TryClose - Now in Processing... Exit.");
return;
}
lock (_lock) lock (_lock)
{ {
if (_socketSender != null) if (_socket != null)
{ {
_socketSender.Dispose(); //Socket.`Close` method deleted
_socketSender = null; //_socket.Close();
//Log.Out("NameSerciceClient.TryClose - _socketSender.Disposed"); _socket.Dispose();
_socket = null;
} }
if (_thread != null)
{
_thread.Cancel(true);
_thread.Dispose();
_thread = null; _thread = null;
//Log.Out("NameSerciceClient.TryClose - _thread.Aborted");
}
if (_waitResponse) if (_waitResponse)
{ {
_responseTable.Clear(); _responseTable.Clear();
} } else
else
{ {
_autoResetWaitReceive.Set(); _autoResetWaitReceive.Set();
} }
} }
} }
private int _recievedLength = -1;
public virtual void Run() public virtual void Run()
{ {
int nameTrnId; int nameTrnId;
@ -313,38 +262,12 @@ namespace SharpCifs.Netbios
try try
{ {
while (Thread.CurrentThread().Equals(_thread))
while (_thread == Thread.CurrentThread())
{ {
if (_thread.IsCanceled) _socket.SoTimeOut = _closeTimeout;
break;
var localPort = (SmbConstants.Lport == 0) ? _lport : SmbConstants.Lport; int len = _socket.Receive(_rcvBuf, 0, RcvBufSize);
var sockEvArg = new SocketAsyncEventArgs();
sockEvArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, localPort);
sockEvArg.SetBuffer(_rcvBuf, 0, RcvBufSize);
sockEvArg.Completed += this.OnReceiveCompleted;
_socketSender.SoTimeOut = _closeTimeout;
this._recievedLength = -1;
//Log.Out($"NameServiceClient.Run - Wait Recieve: {IPAddress.Any}: {localPort}");
_socketSender.ReceiveFromAsync(sockEvArg);
while (this._recievedLength == -1)
{
if (_thread.IsCanceled)
break;
Task.Delay(300).GetAwaiter().GetResult();
}
sockEvArg?.Dispose();
if (_thread.IsCanceled)
break;
if (_log.Level > 3) if (_log.Level > 3)
{ {
@ -361,15 +284,12 @@ namespace SharpCifs.Netbios
lock (response) lock (response)
{ {
if (_thread.IsCanceled)
break;
response.ReadWireFormat(_rcvBuf, 0); response.ReadWireFormat(_rcvBuf, 0);
if (_log.Level > 3) if (_log.Level > 3)
{ {
_log.WriteLine(response); _log.WriteLine(response);
Hexdump.ToHexdump(_log, _rcvBuf, 0, this._recievedLength); Hexdump.ToHexdump(_log, _rcvBuf, 0, len);
} }
if (response.IsResponse) if (response.IsResponse)
@ -380,6 +300,7 @@ namespace SharpCifs.Netbios
} }
} }
} }
} }
catch (TimeoutException) { } catch (TimeoutException) { }
catch (Exception ex) catch (Exception ex)
@ -395,21 +316,10 @@ namespace SharpCifs.Netbios
} }
} }
private void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)
{
//Log.Out("NameServiceClient.OnReceiveCompleted");
this._recievedLength = e.BytesTransferred;
}
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal virtual void Send(NameServicePacket request, internal virtual void Send(NameServicePacket request, NameServicePacket response,
NameServicePacket response,
int timeout) int timeout)
{ {
//Log.Out("NameSerciceClient.Send - Start");
int nid = 0; int nid = 0;
int max = NbtAddress.Nbns.Length; int max = NbtAddress.Nbns.Length;
if (max == 0) if (max == 0)
@ -419,7 +329,6 @@ namespace SharpCifs.Netbios
lock (response) lock (response)
{ {
this._isActive = true;
while (max-- > 0) while (max-- > 0)
{ {
@ -429,75 +338,45 @@ namespace SharpCifs.Netbios
{ {
request.NameTrnId = GetNextNameTrnId(); request.NameTrnId = GetNextNameTrnId();
nid = request.NameTrnId; nid = request.NameTrnId;
response.Received = false; response.Received = false;
_responseTable.Put(nid, response); _responseTable.Put(nid, response);
//Log.Out($"NameSerciceClient.Send - timeout = {timeout}");
EnsureOpen(timeout + 1000); EnsureOpen(timeout + 1000);
int requestLenght = request.WriteWireFormat(_sndBuf, 0); int requestLenght = request.WriteWireFormat(_sndBuf, 0);
byte[] msg = new byte[requestLenght]; _socket.Send(_sndBuf, 0, requestLenght, new IPEndPoint(request.Addr, _lport));
Array.Copy(_sndBuf, msg, requestLenght);
_socketSender.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast,
request.IsBroadcast
? 1
: 0);
_socketSender.SendTo(msg, new IPEndPoint(request.Addr, _lport));
//Log.Out("NameSerciceClient.Send - Sended");
if (_log.Level > 3) if (_log.Level > 3)
{ {
_log.WriteLine(request); _log.WriteLine(request);
Hexdump.ToHexdump(_log, _sndBuf, 0, requestLenght); Hexdump.ToHexdump(_log, _sndBuf, 0, requestLenght);
} }
}
}
if (_waitResponse) if (_waitResponse)
{ {
long start = Runtime.CurrentTimeMillis(); long start = Runtime.CurrentTimeMillis();
var isRecieved = false;
var startTime = DateTime.Now;
while (timeout > 0) while (timeout > 0)
{ {
Runtime.Wait(response, timeout); Runtime.Wait(response, timeout);
if (response.Received && request.QuestionType == response.RecordType) if (response.Received && request.QuestionType == response.RecordType)
{ {
//return; return;
isRecieved = true;
break;
} }
response.Received = false; response.Received = false;
timeout -= (int)(Runtime.CurrentTimeMillis() - start); timeout -= (int)(Runtime.CurrentTimeMillis() - start);
//if (timeout <= 0)
//{
// Log.Out($"NameSerciceClient.Send Timeout! - {(DateTime.Now - startTime).TotalMilliseconds} msec");
//}
} }
if (isRecieved)
break;
} }
} }
catch (Exception ie) catch (Exception ie)
{ {
if (_waitResponse)
_responseTable.Remove(nid);
//Log.Out("NameSerciceClient.Send - IOException");
throw new IOException(ie.Message); throw new IOException(ie.Message);
} }
finally finally
{ {
//Sharpen.Collections.Remove(responseTable, nid);
if (_waitResponse) if (_waitResponse)
{
_responseTable.Remove(nid); _responseTable.Remove(nid);
} }
}
if (_waitResponse) if (_waitResponse)
{ {
lock (_lock) lock (_lock)
@ -514,24 +393,17 @@ namespace SharpCifs.Netbios
} }
} }
} }
this._isActive = false;
//Log.Out("NameSerciceClient.Send - Normaly Ended.");
} }
} }
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
internal virtual NbtAddress[] GetAllByName(Name name, IPAddress addr) internal virtual NbtAddress[] GetAllByName(Name name, IPAddress addr)
{ {
//Log.Out("NameSerciceClient.GetAllByName");
int n; int n;
NameQueryRequest request = new NameQueryRequest(name); NameQueryRequest request = new NameQueryRequest(name);
NameQueryResponse response = new NameQueryResponse(); NameQueryResponse response = new NameQueryResponse();
request.Addr = addr ?? NbtAddress.GetWinsAddress(); request.Addr = addr ?? NbtAddress.GetWinsAddress();
request.IsBroadcast = (request.Addr == null request.IsBroadcast = request.Addr == null;
|| request.Addr.ToString() == Baddr.ToString());
if (request.IsBroadcast) if (request.IsBroadcast)
{ {
request.Addr = Baddr; request.Addr = Baddr;
@ -568,12 +440,10 @@ namespace SharpCifs.Netbios
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
internal virtual NbtAddress GetByName(Name name, IPAddress addr) internal virtual NbtAddress GetByName(Name name, IPAddress addr)
{ {
//Log.Out("NameSerciceClient.GetByName");
int n; int n;
NameQueryRequest request = new NameQueryRequest(name); NameQueryRequest request = new NameQueryRequest(name);
NameQueryResponse response = new NameQueryResponse(); NameQueryResponse response = new NameQueryResponse();
if (addr != null) if (addr != null)
{ {
request.Addr = addr; request.Addr = addr;
@ -593,9 +463,7 @@ namespace SharpCifs.Netbios
} }
throw new UnknownHostException(ioe); throw new UnknownHostException(ioe);
} }
if (response.Received && response.ResultCode == 0
if (response.Received
&& response.ResultCode == 0
&& response.IsResponse) && response.IsResponse)
{ {
int last = response.AddrEntry.Length - 1; int last = response.AddrEntry.Length - 1;
@ -603,11 +471,9 @@ namespace SharpCifs.Netbios
return response.AddrEntry[last]; return response.AddrEntry[last];
} }
} }
while (--n > 0 && request.IsBroadcast); while (--n > 0 && request.IsBroadcast);
throw new UnknownHostException(); throw new UnknownHostException();
} }
for (int i = 0; i < _resolveOrder.Length; i++) for (int i = 0; i < _resolveOrder.Length; i++)
{ {
try try
@ -630,8 +496,7 @@ namespace SharpCifs.Netbios
case ResolverWins: case ResolverWins:
case ResolverBcast: case ResolverBcast:
{ {
if (_resolveOrder[i] == ResolverWins if (_resolveOrder[i] == ResolverWins && name.name != NbtAddress.MasterBrowserName
&& name.name != NbtAddress.MasterBrowserName
&& name.HexCode != unchecked(0x1d)) && name.HexCode != unchecked(0x1d))
{ {
request.Addr = NbtAddress.GetWinsAddress(); request.Addr = NbtAddress.GetWinsAddress();
@ -657,12 +522,11 @@ namespace SharpCifs.Netbios
} }
throw new UnknownHostException(ioe); throw new UnknownHostException(ioe);
} }
if (response.Received if (response.Received && response.ResultCode == 0
&& response.ResultCode == 0
&& response.IsResponse) && response.IsResponse)
{ {
response.AddrEntry[0].HostName.SrcHashCode
= request.Addr.GetHashCode(); response.AddrEntry[0].HostName.SrcHashCode = request.Addr.GetHashCode();
return response.AddrEntry[0]; return response.AddrEntry[0];
} }
if (_resolveOrder[i] == ResolverWins) if (_resolveOrder[i] == ResolverWins)
@ -678,15 +542,12 @@ namespace SharpCifs.Netbios
{ {
} }
} }
throw new UnknownHostException(); throw new UnknownHostException();
} }
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
internal virtual NbtAddress[] GetNodeStatus(NbtAddress addr) internal virtual NbtAddress[] GetNodeStatus(NbtAddress addr)
{ {
//Log.Out("NameSerciceClient.GetNodeStatus");
int n; int n;
int srcHashCode; int srcHashCode;
NodeStatusRequest request; NodeStatusRequest request;
@ -695,7 +556,6 @@ namespace SharpCifs.Netbios
request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x00), null)); request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x00), null));
request.Addr = addr.GetInetAddress(); request.Addr = addr.GetInetAddress();
n = RetryCount; n = RetryCount;
while (n-- > 0) while (n-- > 0)
{ {
try try
@ -725,8 +585,6 @@ namespace SharpCifs.Netbios
internal virtual NbtAddress[] GetHosts() internal virtual NbtAddress[] GetHosts()
{ {
//Log.Out("NbtServiceClient.GetHosts");
try try
{ {
_waitResponse = false; _waitResponse = false;
@ -735,8 +593,6 @@ namespace SharpCifs.Netbios
for (int i = 1; i <= 254; i++) for (int i = 1; i <= 254; i++)
{ {
//Log.Out($"NbtServiceClient.GetHosts - {i}");
NodeStatusRequest request; NodeStatusRequest request;
NodeStatusResponse response; NodeStatusResponse response;
@ -749,27 +605,19 @@ namespace SharpCifs.Netbios
IPAddress addr = new IPAddress(addrBytes); IPAddress addr = new IPAddress(addrBytes);
response = new NodeStatusResponse( //response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName,
new NbtAddress(NbtAddress.UnknownName, // (int)addr.Address, false, 0x20));
BitConverter.ToInt32(addr.GetAddressBytes(), 0), response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName,
false, BitConverter.ToInt32(addr.GetAddressBytes(), 0) , false, 0x20));
0x20)
);
request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName,
unchecked(0x20),
null))
{
Addr = addr
};
request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x20), null));
request.Addr = addr;
Send(request, response, 0); Send(request, response, 0);
} }
} }
catch (IOException ioe) catch (IOException ioe)
{ {
//Log.Out(ioe);
if (_log.Level > 1) if (_log.Level > 1)
{ {
Runtime.PrintStackTrace(ioe, _log); Runtime.PrintStackTrace(ioe, _log);
@ -778,30 +626,28 @@ namespace SharpCifs.Netbios
} }
_autoResetWaitReceive = new AutoResetEvent(false); _autoResetWaitReceive = new AutoResetEvent(false);
if (_thread != null)
{
_thread.Cancel(true);
_thread.Dispose();
}
_thread = new Thread(this); _thread = new Thread(this);
_thread.SetDaemon(true); _thread.SetDaemon(true);
_thread.Start(true); _thread.Start();
_autoResetWaitReceive.WaitOne(); _autoResetWaitReceive.WaitOne();
var result = new List<NbtAddress>(); List<NbtAddress> result = new List<NbtAddress>();
foreach (var key in _responseTable.Keys) foreach (var key in _responseTable.Keys)
{ {
var resp = (NodeStatusResponse)_responseTable[key]; NodeStatusResponse resp = (NodeStatusResponse)_responseTable[key];
if (!resp.Received || resp.ResultCode != 0) if (resp.Received && resp.ResultCode == 0)
continue; {
foreach (var entry in resp.AddressArray)
result.AddRange(resp.AddressArray {
.Where(entry => entry.HostName.HexCode == 0x20)); if (entry.HostName.HexCode == 0x20)
{
result.Add(entry);
}
}
}
} }
_responseTable.Clear(); _responseTable.Clear();

View File

@ -92,10 +92,9 @@ namespace SharpCifs.Netbios
internal static int ReadInt4(byte[] src, int srcIndex) internal static int ReadInt4(byte[] src, int srcIndex)
{ {
return ((src[srcIndex] & unchecked(0xFF)) << 24) return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked(
+ ((src[srcIndex + 1] & unchecked(0xFF)) << 16) 0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src
+ ((src[srcIndex + 2] & unchecked(0xFF)) << 8) [srcIndex + 3] & unchecked(0xFF));
+ (src[srcIndex + 3] & unchecked(0xFF));
} }
internal static int ReadNameTrnId(byte[] src, int srcIndex) internal static int ReadNameTrnId(byte[] src, int srcIndex)
@ -181,34 +180,12 @@ namespace SharpCifs.Netbios
{ {
int start = dstIndex; int start = dstIndex;
WriteInt2(NameTrnId, dst, dstIndex); WriteInt2(NameTrnId, dst, dstIndex);
dst[dstIndex + OpcodeOffset] = unchecked( dst[dstIndex + OpcodeOffset] = unchecked((byte)((IsResponse ? unchecked(0x80) : unchecked(0x00)) + ((OpCode << 3) & unchecked(0x78)) + (IsAuthAnswer
(byte)( ? unchecked(0x04) : unchecked(0x00)) + (IsTruncated ? unchecked(0x02) : unchecked(0x00)) + (IsRecurDesired ? unchecked(0x01)
(IsResponse : unchecked(0x00))));
? unchecked(0x80) dst[dstIndex + OpcodeOffset + 1] = unchecked((byte)((IsRecurAvailable ? unchecked(
: unchecked(0x00)) 0x80) : unchecked(0x00)) + (IsBroadcast ? unchecked(0x10) :
+ ((OpCode << 3) & unchecked(0x78)) unchecked(0x00)) + (ResultCode & unchecked(0x0F))));
+ (IsAuthAnswer
? unchecked(0x04)
: unchecked(0x00))
+ (IsTruncated
? unchecked(0x02)
: unchecked(0x00))
+ (IsRecurDesired
? unchecked(0x01)
: unchecked(0x00))
)
);
dst[dstIndex + OpcodeOffset + 1] = unchecked(
(byte)(
(IsRecurAvailable
? unchecked(0x80)
: unchecked(0x00))
+ (IsBroadcast
? unchecked(0x10)
: unchecked(0x00))
+ (ResultCode & unchecked(0x0F))
)
);
WriteInt2(QuestionCount, dst, start + QuestionOffset); WriteInt2(QuestionCount, dst, start + QuestionOffset);
WriteInt2(AnswerCount, dst, start + AnswerOffset); WriteInt2(AnswerCount, dst, start + AnswerOffset);
WriteInt2(AuthorityCount, dst, start + AuthorityOffset); WriteInt2(AuthorityCount, dst, start + AuthorityOffset);
@ -219,26 +196,19 @@ namespace SharpCifs.Netbios
internal virtual int ReadHeaderWireFormat(byte[] src, int srcIndex) internal virtual int ReadHeaderWireFormat(byte[] src, int srcIndex)
{ {
NameTrnId = ReadInt2(src, srcIndex); NameTrnId = ReadInt2(src, srcIndex);
IsResponse = ((src[srcIndex + OpcodeOffset] & unchecked(0x80)) == 0) ? false
IsResponse = ((src[srcIndex + OpcodeOffset] & unchecked(0x80)) == 0)
? false
: true; : true;
OpCode = (src[srcIndex + OpcodeOffset] & unchecked(0x78)) >> 3; OpCode = (src[srcIndex + OpcodeOffset] & unchecked(0x78)) >> 3;
IsAuthAnswer = ((src[srcIndex + OpcodeOffset] & unchecked(0x04)) == 0) IsAuthAnswer = ((src[srcIndex + OpcodeOffset] & unchecked(0x04)) == 0) ?
? false false : true;
: true; IsTruncated = ((src[srcIndex + OpcodeOffset] & unchecked(0x02)) == 0) ? false
IsTruncated = ((src[srcIndex + OpcodeOffset] & unchecked(0x02)) == 0)
? false
: true;
IsRecurDesired = ((src[srcIndex + OpcodeOffset] & unchecked(0x01)) == 0)
? false
: true;
IsRecurAvailable = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x80)) == 0)
? false
: true; : true;
IsRecurDesired = ((src[srcIndex + OpcodeOffset] & unchecked(0x01)) == 0) ?
false : true;
IsRecurAvailable = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x80))
== 0) ? false : true;
IsBroadcast = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x10)) == 0) IsBroadcast = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x10)) == 0)
? false ? false : true;
: true;
ResultCode = src[srcIndex + OpcodeOffset + 1] & unchecked(0x0F); ResultCode = src[srcIndex + OpcodeOffset + 1] & unchecked(0x0F);
QuestionCount = ReadInt2(src, srcIndex + QuestionOffset); QuestionCount = ReadInt2(src, srcIndex + QuestionOffset);
AnswerCount = ReadInt2(src, srcIndex + AnswerOffset); AnswerCount = ReadInt2(src, srcIndex + AnswerOffset);
@ -463,31 +433,16 @@ namespace SharpCifs.Netbios
break; break;
} }
} }
return "nameTrnId=" + NameTrnId return "nameTrnId=" + NameTrnId + ",isResponse=" + IsResponse + ",opCode="
+ ",isResponse=" + IsResponse + opCodeString + ",isAuthAnswer=" + IsAuthAnswer + ",isTruncated=" + IsTruncated
+ ",opCode=" + opCodeString + ",isRecurAvailable=" + IsRecurAvailable + ",isRecurDesired=" + IsRecurDesired
+ ",isAuthAnswer=" + IsAuthAnswer + ",isBroadcast=" + IsBroadcast + ",resultCode=" + ResultCode + ",questionCount="
+ ",isTruncated=" + IsTruncated + QuestionCount + ",answerCount=" + AnswerCount + ",authorityCount=" + AuthorityCount
+ ",isRecurAvailable=" + IsRecurAvailable + ",additionalCount=" + AdditionalCount + ",questionName=" + QuestionName + ",questionType="
+ ",isRecurDesired=" + IsRecurDesired + questionTypeString + ",questionClass=" + (QuestionClass == In ? "IN" : "0x" +
+ ",isBroadcast=" + IsBroadcast Hexdump.ToHexString(QuestionClass, 4)) + ",recordName=" + RecordName + ",recordType="
+ ",resultCode=" + ResultCode + recordTypeString + ",recordClass=" + (RecordClass == In ? "IN" : "0x" + Hexdump
+ ",questionCount=" + QuestionCount .ToHexString(RecordClass, 4)) + ",ttl=" + Ttl + ",rDataLength=" + RDataLength;
+ ",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;
} }
} }
} }

View File

@ -18,7 +18,6 @@ using System;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using SharpCifs.Util; using SharpCifs.Util;
using SharpCifs.Util.DbsHelper;
using SharpCifs.Util.Sharpen; using SharpCifs.Util.Sharpen;
using Extensions = SharpCifs.Util.Sharpen.Extensions; using Extensions = SharpCifs.Util.Sharpen.Extensions;
@ -73,8 +72,7 @@ namespace SharpCifs.Netbios
/// <since>jcifs-0.1</since> /// <since>jcifs-0.1</since>
public sealed class NbtAddress public sealed class NbtAddress
{ {
internal static readonly string AnyHostsName internal static readonly string AnyHostsName = "*\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";
= "*\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";
/// <summary> /// <summary>
/// This is a special name for querying the master browser that serves the /// This is a special name for querying the master browser that serves the
@ -132,15 +130,15 @@ namespace SharpCifs.Netbios
/// </remarks> /// </remarks>
public const int HNode = 3; public const int HNode = 3;
internal static readonly IPAddress[] Nbns internal static readonly IPAddress[] Nbns = Config.GetInetAddressArray("jcifs.netbios.wins"
= Config.GetInetAddressArray("jcifs.netbios.wins", ",", new IPAddress[0]); , ",", new IPAddress[0]);
private static readonly NameServiceClient Client = new NameServiceClient(); private static readonly NameServiceClient Client = new NameServiceClient();
private const int DefaultCachePolicy = 30; private const int DefaultCachePolicy = 30;
private static readonly int CachePolicy private static readonly int CachePolicy = Config.GetInt("jcifs.netbios.cachePolicy"
= Config.GetInt("jcifs.netbios.cachePolicy", DefaultCachePolicy); , DefaultCachePolicy);
private const int Forever = -1; private const int Forever = -1;
@ -152,20 +150,12 @@ namespace SharpCifs.Netbios
internal static readonly Name UnknownName = new Name("0.0.0.0", unchecked(0x00), null); internal static readonly Name UnknownName = new Name("0.0.0.0", unchecked(0x00), null);
internal static readonly NbtAddress UnknownAddress internal static readonly NbtAddress UnknownAddress = new NbtAddress
= new NbtAddress(UnknownName, 0, false, BNode); (UnknownName, 0, false, BNode);
internal static readonly byte[] UnknownMacAddress = internal static readonly byte[] UnknownMacAddress = { unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)), unchecked(unchecked(0x00)) };
{
unchecked(unchecked(0x00)),
unchecked(unchecked(0x00)),
unchecked(unchecked(0x00)),
unchecked(unchecked(0x00)),
unchecked(unchecked(0x00)),
unchecked(unchecked(0x00))
};
private sealed class CacheEntry internal sealed class CacheEntry
{ {
internal Name HostName; internal Name HostName;
@ -181,16 +171,15 @@ namespace SharpCifs.Netbios
} }
} }
private static NbtAddress Localhost; internal static NbtAddress Localhost;
static NbtAddress() static NbtAddress()
{ {
IPAddress localInetAddress; IPAddress localInetAddress;
string localHostname; string localHostname;
Name localName; Name localName;
AddressCache.Put(UnknownName, new CacheEntry(UnknownName, AddressCache.Put(UnknownName, new CacheEntry(UnknownName, UnknownAddress
UnknownAddress, , Forever));
Forever));
localInetAddress = Client.laddr; localInetAddress = Client.laddr;
if (localInetAddress == null) if (localInetAddress == null)
{ {
@ -200,48 +189,27 @@ namespace SharpCifs.Netbios
} }
catch (UnknownHostException) catch (UnknownHostException)
{ {
} }
} }
localHostname = Config.GetProperty("jcifs.netbios.hostname", null); localHostname = Config.GetProperty("jcifs.netbios.hostname", null);
if (string.IsNullOrEmpty(localHostname)) if (string.IsNullOrEmpty(localHostname))
{ {
/*
byte[] addr = localInetAddress.GetAddressBytes(); byte[] addr = localInetAddress.GetAddressBytes();
localHostname = "JCIFS" /*localHostname = "JCIFS" + (addr[2] & unchecked((int)(0xFF))) + "_" + (addr[3] & unchecked(
+ (addr[2] & unchecked((int)(0xFF))) (int)(0xFF))) + "_" + Hexdump.ToHexString((int)(new Random().NextDouble() * (double)unchecked(
+ "_" + (addr[3] & unchecked((int)(0xFF))) (int)(0xFF))), 2);*/
+ "_" + Hexdump.ToHexString(
(int)(new Random().NextDouble()
* (double)unchecked((int)(0xFF))),
2
);
*/
try
{
localHostname = Dns.GetHostName();
}
catch (Exception)
{
localHostname = "JCIFS_127_0_0_1"; localHostname = "JCIFS_127_0_0_1";
} }
} localName = new Name(localHostname, unchecked(0x00), Config.GetProperty("jcifs.netbios.scope"
localName = new Name(localHostname, , null));
unchecked(0x00), Localhost = new NbtAddress(localName, localInetAddress.GetHashCode(), false, BNode
Config.GetProperty("jcifs.netbios.scope", null)); , false, false, true, false, UnknownMacAddress);
Localhost = new NbtAddress(localName,
localInetAddress.GetHashCode(),
false,
BNode,
false,
false,
true,
false,
UnknownMacAddress);
CacheAddress(localName, Localhost, Forever); CacheAddress(localName, Localhost, Forever);
} }
private static void CacheAddress(Name hostName, NbtAddress addr) internal static void CacheAddress(Name hostName, NbtAddress addr)
{ {
if (CachePolicy == 0) if (CachePolicy == 0)
{ {
@ -255,7 +223,8 @@ namespace SharpCifs.Netbios
CacheAddress(hostName, addr, expiration); CacheAddress(hostName, addr, expiration);
} }
private static void CacheAddress(Name hostName, NbtAddress addr, long expiration) internal static void CacheAddress(Name hostName, NbtAddress addr, long expiration
)
{ {
if (CachePolicy == 0) if (CachePolicy == 0)
{ {
@ -277,7 +246,7 @@ namespace SharpCifs.Netbios
} }
} }
private static void CacheAddressArray(NbtAddress[] addrs) internal static void CacheAddressArray(NbtAddress[] addrs)
{ {
if (CachePolicy == 0) if (CachePolicy == 0)
{ {
@ -292,7 +261,8 @@ namespace SharpCifs.Netbios
{ {
for (int i = 0; i < addrs.Length; i++) for (int i = 0; i < addrs.Length; i++)
{ {
CacheEntry entry = (CacheEntry)AddressCache.Get(addrs[i].HostName); CacheEntry entry = (CacheEntry)AddressCache.Get(addrs[i].HostName
);
if (entry == null) if (entry == null)
{ {
entry = new CacheEntry(addrs[i].HostName, addrs[i], expiration); entry = new CacheEntry(addrs[i].HostName, addrs[i], expiration);
@ -307,7 +277,7 @@ namespace SharpCifs.Netbios
} }
} }
private static NbtAddress GetCachedAddress(Name hostName) internal static NbtAddress GetCachedAddress(Name hostName)
{ {
if (CachePolicy == 0) if (CachePolicy == 0)
{ {
@ -316,20 +286,17 @@ namespace SharpCifs.Netbios
lock (AddressCache) lock (AddressCache)
{ {
CacheEntry entry = (CacheEntry)AddressCache.Get(hostName); CacheEntry entry = (CacheEntry)AddressCache.Get(hostName);
if (entry != null if (entry != null && entry.Expiration < Runtime.CurrentTimeMillis() && entry.Expiration
&& entry.Expiration < Runtime.CurrentTimeMillis() >= 0)
&& entry.Expiration>= 0)
{ {
entry = null; entry = null;
} }
return entry != null return entry != null ? entry.Address : null;
? entry.Address
: null;
} }
} }
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
private static NbtAddress DoNameQuery(Name name, IPAddress svr) internal static NbtAddress DoNameQuery(Name name, IPAddress svr)
{ {
NbtAddress addr; NbtAddress addr;
if (name.HexCode == unchecked(0x1d) && svr == null) if (name.HexCode == unchecked(0x1d) && svr == null)
@ -337,9 +304,7 @@ namespace SharpCifs.Netbios
svr = Client.Baddr; svr = Client.Baddr;
} }
// bit of a hack but saves a lookup // bit of a hack but saves a lookup
name.SrcHashCode = svr != null name.SrcHashCode = svr != null ? svr.GetHashCode() : 0;
? svr.GetHashCode()
: 0;
addr = GetCachedAddress(name); addr = GetCachedAddress(name);
if (addr == null) if (addr == null)
{ {
@ -409,8 +374,6 @@ namespace SharpCifs.Netbios
} }
} }
/// <summary>Retrieves the local host address.</summary> /// <summary>Retrieves the local host address.</summary>
/// <remarks>Retrieves the local host address.</remarks> /// <remarks>Retrieves the local host address.</remarks>
/// <exception cref="UnknownHostException"> /// <exception cref="UnknownHostException">
@ -424,7 +387,6 @@ namespace SharpCifs.Netbios
public static NbtAddress[] GetHosts() public static NbtAddress[] GetHosts()
{ {
//Log.Out("NbtAddress.GetHosts");
return new NameServiceClient().GetHosts(); return new NameServiceClient().GetHosts();
} }
@ -473,7 +435,8 @@ namespace SharpCifs.Netbios
} }
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
public static NbtAddress GetByName(string host, int type, string scope, IPAddress svr) public static NbtAddress GetByName(string host, int type, string scope, IPAddress
svr)
{ {
if (string.IsNullOrEmpty(host)) if (string.IsNullOrEmpty(host))
{ {
@ -522,10 +485,8 @@ namespace SharpCifs.Netbios
} }
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
public static NbtAddress[] GetAllByName(string host, public static NbtAddress[] GetAllByName(string host, int type, string scope, IPAddress
int type, svr)
string scope,
IPAddress svr)
{ {
return Client.GetAllByName(new Name(host, type, scope), svr); return Client.GetAllByName(new Name(host, type, scope), svr);
} }
@ -584,13 +545,10 @@ namespace SharpCifs.Netbios
} }
catch (UnknownHostException) catch (UnknownHostException)
{ {
throw new UnknownHostException( throw new UnknownHostException("no name with type 0x" + Hexdump.ToHexString(addr.
"no name with type 0x" + Hexdump.ToHexString(addr.HostName.HexCode, 2) HostName.HexCode, 2) + (((addr.HostName.Scope == null) || (addr.HostName.Scope.Length
+ (((addr.HostName.Scope == null) || (addr.HostName.Scope.Length == 0)) == 0)) ? " with no scope" : " with scope " + addr.HostName.Scope) + " for host "
? " with no scope" + addr.GetHostAddress());
: " with scope " + addr.HostName.Scope)
+ " for host " + addr.GetHostAddress()
);
} }
} }
@ -647,15 +605,9 @@ namespace SharpCifs.Netbios
this.NodeType = nodeType; this.NodeType = nodeType;
} }
internal NbtAddress(Name hostName, internal NbtAddress(Name hostName, int address, bool groupName, int nodeType, bool
int address, isBeingDeleted, bool isInConflict, bool isActive, bool isPermanent, byte[] macAddress
bool groupName, )
int nodeType,
bool isBeingDeleted,
bool isInConflict,
bool isActive,
bool isPermanent,
byte[] macAddress)
{ {
this.HostName = hostName; this.HostName = hostName;
this.Address = address; this.Address = address;
@ -885,9 +837,12 @@ namespace SharpCifs.Netbios
public byte[] GetAddress() public byte[] GetAddress()
{ {
byte[] addr = new byte[4]; byte[] addr = new byte[4];
addr[0] = unchecked((byte)(((int)(((uint)Address) >> 24)) & unchecked(0xFF))); addr[0] = unchecked((byte)(((int)(((uint)Address) >> 24)) & unchecked(0xFF
addr[1] = unchecked((byte)(((int)(((uint)Address) >> 16)) & unchecked(0xFF))); )));
addr[2] = unchecked((byte)(((int)(((uint)Address) >> 8)) & unchecked(0xFF))); addr[1] = unchecked((byte)(((int)(((uint)Address) >> 16)) & unchecked(0xFF
)));
addr[2] = unchecked((byte)(((int)(((uint)Address) >> 8)) & unchecked(0xFF)
));
addr[3] = unchecked((byte)(Address & unchecked(0xFF))); addr[3] = unchecked((byte)(Address & unchecked(0xFF)));
return addr; return addr;
} }
@ -912,10 +867,10 @@ namespace SharpCifs.Netbios
/// </summary> /// </summary>
public string GetHostAddress() public string GetHostAddress()
{ {
return (((int)(((uint)Address) >> 24)) & unchecked(0xFF)) return (((int)(((uint)Address) >> 24)) & unchecked(0xFF)) + "." + (((int)(
+ "." + (((int)(((uint)Address) >> 16)) & unchecked(0xFF)) ((uint)Address) >> 16)) & unchecked(0xFF)) + "." + (((int)(((uint)Address
+ "." + (((int)(((uint)Address) >> 8)) & unchecked(0xFF)) ) >> 8)) & unchecked(0xFF)) + "." + (((int)(((uint)Address) >> 0)) & unchecked(
+ "." + (((int)(((uint)Address) >> 0)) & unchecked(0xFF)); 0xFF));
} }
/// <summary>Returned the hex code associated with this name(e.g.</summary> /// <summary>Returned the hex code associated with this name(e.g.</summary>
@ -948,9 +903,8 @@ namespace SharpCifs.Netbios
/// </remarks> /// </remarks>
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
return (obj != null) return (obj != null) && (obj is NbtAddress) && (((NbtAddress)obj).Address == Address
&& (obj is NbtAddress) );
&& (((NbtAddress)obj).Address == Address);
} }
/// <summary> /// <summary>

View File

@ -157,9 +157,8 @@ namespace SharpCifs.Netbios
public override string ToString() public override string ToString()
{ {
return "errorClass=" + ErrorClass return "errorClass=" + ErrorClass + ",errorCode=" + ErrorCode + ",errorString="
+ ",errorCode=" + ErrorCode + GetErrorString(ErrorClass, ErrorCode);
+ ",errorString=" + GetErrorString(ErrorClass, ErrorCode);
} }
} }
} }

View File

@ -94,26 +94,14 @@ namespace SharpCifs.Netbios
n = Runtime.GetStringForBytes(src, srcIndex, j - srcIndex + 1, Name.OemEncoding n = Runtime.GetStringForBytes(src, srcIndex, j - srcIndex + 1, Name.OemEncoding
); );
hexCode = src[srcIndex + 15] & unchecked(0xFF); hexCode = src[srcIndex + 15] & unchecked(0xFF);
groupName = ((src[srcIndex + 16] & unchecked(0x80)) == unchecked(0x80)) groupName = ((src[srcIndex + 16] & unchecked(0x80)) == unchecked(0x80)) ? true : false;
? true
: false;
ownerNodeType = (src[srcIndex + 16] & unchecked(0x60)) >> 5; ownerNodeType = (src[srcIndex + 16] & unchecked(0x60)) >> 5;
isBeingDeleted = ((src[srcIndex + 16] & unchecked(0x10)) == unchecked(0x10)) isBeingDeleted = ((src[srcIndex + 16] & unchecked(0x10)) == unchecked(0x10)) ? true : false;
? true isInConflict = ((src[srcIndex + 16] & unchecked(0x08)) == unchecked(0x08)) ? true : false;
: false; isActive = ((src[srcIndex + 16] & unchecked(0x04)) == unchecked(0x04)) ? true : false;
isInConflict = ((src[srcIndex + 16] & unchecked(0x08)) == unchecked(0x08)) isPermanent = ((src[srcIndex + 16] & unchecked(0x02)) == unchecked(0x02)) ? true : false;
? true if (!addrFound && _queryAddress.HostName.HexCode == hexCode && (_queryAddress.HostName
: false; == NbtAddress.UnknownName || _queryAddress.HostName.name.Equals(n)))
isActive = ((src[srcIndex + 16] & unchecked(0x04)) == unchecked(0x04))
? true
: false;
isPermanent = ((src[srcIndex + 16] & unchecked(0x02)) == unchecked(0x02))
? true
: false;
if (!addrFound
&& _queryAddress.HostName.HexCode == hexCode
&& (_queryAddress.HostName == NbtAddress.UnknownName
|| _queryAddress.HostName.name.Equals(n)))
{ {
if (_queryAddress.HostName == NbtAddress.UnknownName) if (_queryAddress.HostName == NbtAddress.UnknownName)
{ {
@ -132,14 +120,8 @@ namespace SharpCifs.Netbios
} }
else else
{ {
AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope), AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope), _queryAddress.Address
_queryAddress.Address, , groupName, ownerNodeType, isBeingDeleted, isInConflict, isActive, isPermanent,
groupName,
ownerNodeType,
isBeingDeleted,
isInConflict,
isActive,
isPermanent,
_macAddress); _macAddress);
} }
} }

View File

@ -47,7 +47,8 @@ namespace SharpCifs.Netbios
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex) internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
)
{ {
int start = bufferIndex; int start = bufferIndex;
if (@in.Read(buffer, bufferIndex, Length) != Length) if (@in.Read(buffer, bufferIndex, Length) != Length)

View File

@ -37,7 +37,8 @@ namespace SharpCifs.Netbios
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex) internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
)
{ {
if (@in.Read(buffer, bufferIndex, Length) != Length) if (@in.Read(buffer, bufferIndex, Length) != Length)
{ {

View File

@ -54,24 +54,22 @@ namespace SharpCifs.Netbios
internal static int ReadInt2(byte[] src, int srcIndex) internal static int ReadInt2(byte[] src, int srcIndex)
{ {
return ((src[srcIndex] & unchecked(0xFF)) << 8) return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked(
+ (src[srcIndex + 1] & unchecked(0xFF)); 0xFF));
} }
internal static int ReadInt4(byte[] src, int srcIndex) internal static int ReadInt4(byte[] src, int srcIndex)
{ {
return ((src[srcIndex] & unchecked(0xFF)) << 24) return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked(
+ ((src[srcIndex + 1] & unchecked(0xFF)) << 16) 0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src
+ ((src[srcIndex + 2] & unchecked(0xFF)) << 8) [srcIndex + 3] & unchecked(0xFF));
+ (src[srcIndex + 3] & unchecked(0xFF));
} }
internal static int ReadLength(byte[] src, int srcIndex) internal static int ReadLength(byte[] src, int srcIndex)
{ {
srcIndex++; srcIndex++;
return ((src[srcIndex++] & unchecked(0x01)) << 16) return ((src[srcIndex++] & unchecked(0x01)) << 16) + ((src[srcIndex++] & unchecked(
+ ((src[srcIndex++] & unchecked(0xFF)) << 8) 0xFF)) << 8) + (src[srcIndex++] & unchecked(0xFF));
+ (src[srcIndex++] & unchecked(0xFF));
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
@ -92,7 +90,8 @@ namespace SharpCifs.Netbios
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal static int ReadPacketType(InputStream @in, byte[] buffer, int bufferIndex) internal static int ReadPacketType(InputStream @in, byte[] buffer, int bufferIndex
)
{ {
int n; int n;
if ((n = Readn(@in, buffer, bufferIndex, HeaderLength)) != HeaderLength) if ((n = Readn(@in, buffer, bufferIndex, HeaderLength)) != HeaderLength)
@ -119,7 +118,8 @@ namespace SharpCifs.Netbios
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal virtual int ReadWireFormat(InputStream @in, byte[] buffer, int bufferIndex) internal virtual int ReadWireFormat(InputStream @in, byte[] buffer, int bufferIndex
)
{ {
ReadHeaderWireFormat(@in, buffer, bufferIndex); ReadHeaderWireFormat(@in, buffer, bufferIndex);
return HeaderLength + ReadTrailerWireFormat(@in, buffer, bufferIndex); return HeaderLength + ReadTrailerWireFormat(@in, buffer, bufferIndex);
@ -138,17 +138,19 @@ namespace SharpCifs.Netbios
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal virtual int ReadHeaderWireFormat(InputStream @in, byte[] buffer, int bufferIndex) internal virtual int ReadHeaderWireFormat(InputStream @in, byte[] buffer, int bufferIndex
)
{ {
Type = buffer[bufferIndex++] & unchecked(0xFF); Type = buffer[bufferIndex++] & unchecked(0xFF);
Length = ((buffer[bufferIndex] & unchecked(0x01)) << 16) Length = ((buffer[bufferIndex] & unchecked(0x01)) << 16) + ReadInt2(buffer
+ ReadInt2(buffer, bufferIndex + 1); , bufferIndex + 1);
return HeaderLength; return HeaderLength;
} }
internal abstract int WriteTrailerWireFormat(byte[] dst, int dstIndex); internal abstract int WriteTrailerWireFormat(byte[] dst, int dstIndex);
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal abstract int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex); internal abstract int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
);
} }
} }

View File

@ -170,7 +170,8 @@ namespace SharpCifs.Ntlmssp
public const int NtlmsspRequestAcceptResponse = unchecked(0x00200000); public const int NtlmsspRequestAcceptResponse = unchecked(0x00200000);
public const int NtlmsspRequestNonNtSessionKey = unchecked(0x00400000); public const int NtlmsspRequestNonNtSessionKey = unchecked(0x00400000
);
/// <summary> /// <summary>
/// Sent by the server in the Type 2 message to indicate that it is /// Sent by the server in the Type 2 message to indicate that it is

View File

@ -24,17 +24,10 @@ namespace SharpCifs.Ntlmssp
{ {
/// <summary>The NTLMSSP "preamble".</summary> /// <summary>The NTLMSSP "preamble".</summary>
/// <remarks>The NTLMSSP "preamble".</remarks> /// <remarks>The NTLMSSP "preamble".</remarks>
protected internal static readonly byte[] NtlmsspSignature = protected internal static readonly byte[] NtlmsspSignature = { unchecked(
{ (byte)('N')), unchecked((byte)('T')), unchecked((byte)('L')),
unchecked((byte)('N')), unchecked((byte)('M')), unchecked((byte)('S')), unchecked((byte
unchecked((byte)('T')), )('S')), unchecked((byte)('P')), unchecked(0) };
unchecked((byte)('L')),
unchecked((byte)('M')),
unchecked((byte)('S')),
unchecked((byte)('S')),
unchecked((byte)('P')),
unchecked(0)
};
private static readonly string OemEncoding = Config.DefaultOemEncoding; private static readonly string OemEncoding = Config.DefaultOemEncoding;
@ -82,17 +75,14 @@ namespace SharpCifs.Ntlmssp
/// </param> /// </param>
public virtual void SetFlag(int flag, bool value) public virtual void SetFlag(int flag, bool value)
{ {
SetFlags(value SetFlags(value ? (GetFlags() | flag) : (GetFlags() & (unchecked((int)(0xffffffff)
? (GetFlags() | flag) ) ^ flag)));
: (GetFlags() & (unchecked((int)(0xffffffff)) ^ flag)));
} }
internal static int ReadULong(byte[] src, int index) internal static int ReadULong(byte[] src, int index)
{ {
return (src[index] & unchecked(0xff)) return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8) | ((src[index + 2] & unchecked(0xff)) << 16) | ((src[index
| ((src[index + 1] & unchecked(0xff)) << 8) + 3] & unchecked(0xff)) << 24);
| ((src[index + 2] & unchecked(0xff)) << 16)
| ((src[index + 3] & unchecked(0xff)) << 24);
} }
internal static int ReadUShort(byte[] src, int index) internal static int ReadUShort(byte[] src, int index)
@ -123,14 +113,10 @@ namespace SharpCifs.Ntlmssp
dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff))); dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff)));
} }
internal static void WriteSecurityBuffer(byte[] dest, internal static void WriteSecurityBuffer(byte[] dest, int offset, int bodyOffset,
int offset,
int bodyOffset,
byte[] src) byte[] src)
{ {
int length = (src != null) int length = (src != null) ? src.Length : 0;
? src.Length
: 0;
if (length == 0) if (length == 0)
{ {
return; return;

View File

@ -38,9 +38,8 @@ namespace SharpCifs.Ntlmssp
static Type1Message() static Type1Message()
{ {
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode", true) DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
? NtlmsspNegotiateUnicode , true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
: NtlmsspNegotiateOem);
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null); DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
string defaultWorkstation = null; string defaultWorkstation = null;
try try
@ -61,9 +60,8 @@ namespace SharpCifs.Ntlmssp
/// Creates a Type-1 message using default values from the current /// Creates a Type-1 message using default values from the current
/// environment. /// environment.
/// </remarks> /// </remarks>
public Type1Message() : this(GetDefaultFlags(), public Type1Message() : this(GetDefaultFlags(), GetDefaultDomain(), GetDefaultWorkstation
GetDefaultDomain(), ())
GetDefaultWorkstation())
{ {
} }
@ -86,8 +84,7 @@ namespace SharpCifs.Ntlmssp
/// <summary>Creates a Type-1 message using the given raw Type-1 material.</summary> /// <summary>Creates a Type-1 message using the given raw Type-1 material.</summary>
/// <remarks>Creates a Type-1 message using the given raw Type-1 material.</remarks> /// <remarks>Creates a Type-1 message using the given raw Type-1 material.</remarks>
/// <param name="material">The raw Type-1 material used to construct this message.</param> /// <param name="material">The raw Type-1 material used to construct this message.</param>
/// <exception cref="System.IO.IOException"> /// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
/// If an error occurs while parsing the material.
/// </exception> /// </exception>
public Type1Message(byte[] material) public Type1Message(byte[] material)
{ {
@ -139,8 +136,8 @@ namespace SharpCifs.Ntlmssp
{ {
hostInfo = true; hostInfo = true;
flags |= NtlmsspNegotiateOemDomainSupplied; flags |= NtlmsspNegotiateOemDomainSupplied;
domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(), domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(), GetOemEncoding
GetOemEncoding()); ());
} }
else else
{ {
@ -151,16 +148,16 @@ namespace SharpCifs.Ntlmssp
{ {
hostInfo = true; hostInfo = true;
flags |= NtlmsspNegotiateOemWorkstationSupplied; flags |= NtlmsspNegotiateOemWorkstationSupplied;
workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(), workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(), GetOemEncoding
GetOemEncoding()); ());
} }
else else
{ {
flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff))); flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff
)));
} }
byte[] type1 = new byte[hostInfo byte[] type1 = new byte[hostInfo ? (32 + domain.Length + workstation.Length) : 16
? (32 + domain.Length + workstation.Length) ];
: 16];
Array.Copy(NtlmsspSignature, 0, type1, 0, 8); Array.Copy(NtlmsspSignature, 0, type1, 0, 8);
WriteULong(type1, 8, 1); WriteULong(type1, 8, 1);
WriteULong(type1, 12, flags); WriteULong(type1, 12, flags);
@ -181,9 +178,9 @@ namespace SharpCifs.Ntlmssp
{ {
string suppliedDomain = GetSuppliedDomain(); string suppliedDomain = GetSuppliedDomain();
string suppliedWorkstation = GetSuppliedWorkstation(); string suppliedWorkstation = GetSuppliedWorkstation();
return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null") return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null"
+ ",suppliedWorkstation=" + (suppliedWorkstation ?? "null") ) + ",suppliedWorkstation=" + (suppliedWorkstation ?? "null"
+ ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]"; ) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
} }
/// <summary> /// <summary>
@ -241,7 +238,8 @@ namespace SharpCifs.Ntlmssp
if ((flags & NtlmsspNegotiateOemWorkstationSupplied) != 0) if ((flags & NtlmsspNegotiateOemWorkstationSupplied) != 0)
{ {
byte[] workstation = ReadSecurityBuffer(material, 24); byte[] workstation = ReadSecurityBuffer(material, 24);
suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding()); suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding
());
} }
SetFlags(flags); SetFlags(flags);
SetSuppliedDomain(suppliedDomain); SetSuppliedDomain(suppliedDomain);

View File

@ -42,9 +42,8 @@ namespace SharpCifs.Ntlmssp
static Type2Message() static Type2Message()
{ {
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode", true) DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
? NtlmsspNegotiateUnicode , true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
: NtlmsspNegotiateOem);
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null); DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
byte[] domain = new byte[0]; byte[] domain = new byte[0];
if (DefaultDomain != null) if (DefaultDomain != null)
@ -77,13 +76,8 @@ namespace SharpCifs.Ntlmssp
{ {
} }
int serverLength = server.Length; int serverLength = server.Length;
byte[] targetInfo = new byte[(domainLength > 0 byte[] targetInfo = new byte[(domainLength > 0 ? domainLength + 4 : 0) + (serverLength
? domainLength + 4 > 0 ? serverLength + 4 : 0) + 4];
: 0)
+ (serverLength > 0
? serverLength + 4
: 0)
+ 4];
int offset = 0; int offset = 0;
if (domainLength > 0) if (domainLength > 0)
{ {
@ -135,14 +129,9 @@ namespace SharpCifs.Ntlmssp
/// <param name="type1">The Type-1 message which this represents a response to.</param> /// <param name="type1">The Type-1 message which this represents a response to.</param>
/// <param name="challenge">The challenge from the domain controller/server.</param> /// <param name="challenge">The challenge from the domain controller/server.</param>
/// <param name="target">The authentication target.</param> /// <param name="target">The authentication target.</param>
public Type2Message(Type1Message type1, public Type2Message(Type1Message type1, byte[] challenge, string target) : this(GetDefaultFlags
byte[] challenge, (type1), challenge, (type1 != null && target == null && type1.GetFlag(NtlmsspRequestTarget
string target) )) ? GetDefaultDomain() : target)
: this(GetDefaultFlags(type1),
challenge,
(type1 != null && target == null && type1.GetFlag(NtlmsspRequestTarget))
? GetDefaultDomain()
: target)
{ {
} }
@ -265,9 +254,9 @@ namespace SharpCifs.Ntlmssp
{ {
if (!string.IsNullOrEmpty(targetName)) if (!string.IsNullOrEmpty(targetName))
{ {
target = (flags & NtlmsspNegotiateUnicode) != 0 target = (flags & NtlmsspNegotiateUnicode) != 0 ? Runtime.GetBytesForString
? Runtime.GetBytesForString(targetName, UniEncoding) (targetName, UniEncoding) : Runtime.GetBytesForString(targetName.ToUpper
: Runtime.GetBytesForString(targetName.ToUpper(), GetOemEncoding()); (), GetOemEncoding());
} }
else else
{ {
@ -292,11 +281,8 @@ namespace SharpCifs.Ntlmssp
{ {
data += 8; data += 8;
} }
byte[] type2 = new byte[data byte[] type2 = new byte[data + target.Length + (targetInformation != null ? targetInformation
+ target.Length .Length : 0)];
+ (targetInformation != null
? targetInformation.Length
: 0)];
Array.Copy(NtlmsspSignature, 0, type2, 0, 8); Array.Copy(NtlmsspSignature, 0, type2, 0, 8);
WriteULong(type2, 8, 2); WriteULong(type2, 8, 2);
WriteSecurityBuffer(type2, 12, data, target); WriteSecurityBuffer(type2, 12, data, target);
@ -324,17 +310,11 @@ namespace SharpCifs.Ntlmssp
byte[] challenge = GetChallenge(); byte[] challenge = GetChallenge();
byte[] context = GetContext(); byte[] context = GetContext();
byte[] targetInformation = GetTargetInformation(); byte[] targetInformation = GetTargetInformation();
return "Type2Message[target=" + target return "Type2Message[target=" + target + ",challenge=" + (challenge == null ? "null"
+ ",challenge=" + (challenge == null : "<" + challenge.Length + " bytes>") + ",context=" + (context == null ? "null"
? "null" : "<" + context.Length + " bytes>") + ",targetInformation=" + (targetInformation
: "<" + challenge.Length + " bytes>") == null ? "null" : "<" + targetInformation.Length + " bytes>") + ",flags=0x" +
+ ",context=" + (context == null Hexdump.ToHexString(GetFlags(), 8) + "]";
? "null"
: "<" + context.Length + " bytes>")
+ ",targetInformation=" + (targetInformation == null
? "null"
: "<" + targetInformation.Length + " bytes>")
+ ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
} }
/// <summary> /// <summary>
@ -368,8 +348,7 @@ namespace SharpCifs.Ntlmssp
} }
int flags = NtlmsspNegotiateNtlm; int flags = NtlmsspNegotiateNtlm;
int type1Flags = type1.GetFlags(); int type1Flags = type1.GetFlags();
flags |= ((type1Flags & NtlmsspNegotiateUnicode) != 0) flags |= ((type1Flags & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode
? NtlmsspNegotiateUnicode
: NtlmsspNegotiateOem; : NtlmsspNegotiateOem;
if ((type1Flags & NtlmsspRequestTarget) != 0) if ((type1Flags & NtlmsspRequestTarget) != 0)
{ {
@ -415,10 +394,8 @@ namespace SharpCifs.Ntlmssp
byte[] bytes = ReadSecurityBuffer(material, 12); byte[] bytes = ReadSecurityBuffer(material, 12);
if (bytes.Length != 0) if (bytes.Length != 0)
{ {
target = Runtime.GetStringForBytes(bytes, target = Runtime.GetStringForBytes(bytes, ((flags & NtlmsspNegotiateUnicode
((flags & NtlmsspNegotiateUnicode) != 0) ) != 0) ? UniEncoding : GetOemEncoding());
? UniEncoding
: GetOemEncoding());
} }
SetTarget(target); SetTarget(target);
for (int i1 = 24; i1 < 32; i1++) for (int i1 = 24; i1 < 32; i1++)

View File

@ -59,9 +59,8 @@ namespace SharpCifs.Ntlmssp
static Type3Message() static Type3Message()
{ {
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode", true) DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
? NtlmsspNegotiateUnicode , true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
: NtlmsspNegotiateOem);
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null); DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
DefaultUser = Config.GetProperty("jcifs.smb.client.username", null); DefaultUser = Config.GetProperty("jcifs.smb.client.username", null);
DefaultPassword = Config.GetProperty("jcifs.smb.client.password", null); DefaultPassword = Config.GetProperty("jcifs.smb.client.password", null);
@ -158,12 +157,8 @@ namespace SharpCifs.Ntlmssp
/// The workstation from which authentication is /// The workstation from which authentication is
/// taking place. /// taking place.
/// </param> /// </param>
public Type3Message(Type2Message type2, public Type3Message(Type2Message type2, string password, string domain, string user
string password, , string workstation, int flags)
string domain,
string user,
string workstation,
int flags)
{ {
SetFlags(flags | GetDefaultFlags(type2)); SetFlags(flags | GetDefaultFlags(type2));
if (workstation == null) if (workstation == null)
@ -190,12 +185,9 @@ namespace SharpCifs.Ntlmssp
//RANDOM.NextBytes(clientChallenge); //RANDOM.NextBytes(clientChallenge);
Arrays.Fill(clientChallenge, 8, 24, unchecked((byte)unchecked(0x00))); Arrays.Fill(clientChallenge, 8, 24, unchecked((byte)unchecked(0x00)));
// NTLMv1 w/ NTLM2 session sec and key exch all been verified with a debug build of smbclient // NTLMv1 w/ NTLM2 session sec and key exch all been verified with a debug build of smbclient
byte[] responseKeyNt byte[] responseKeyNt = NtlmPasswordAuthentication.NtowFv1(password);
= NtlmPasswordAuthentication.NtowFv1(password); byte[] ntlm2Response = NtlmPasswordAuthentication.GetNtlm2Response(responseKeyNt,
byte[] ntlm2Response type2.GetChallenge(), clientChallenge);
= NtlmPasswordAuthentication.GetNtlm2Response(responseKeyNt,
type2.GetChallenge(),
clientChallenge);
SetLmResponse(clientChallenge); SetLmResponse(clientChallenge);
SetNtResponse(ntlm2Response); SetNtResponse(ntlm2Response);
if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign) if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign)
@ -240,8 +232,8 @@ namespace SharpCifs.Ntlmssp
case 4: case 4:
case 5: case 5:
{ {
byte[] responseKeyNt1 byte[] responseKeyNt1 = NtlmPasswordAuthentication.NtowFv2(domain, user, password
= NtlmPasswordAuthentication.NtowFv2(domain, user, password); );
byte[] clientChallenge1 = new byte[8]; byte[] clientChallenge1 = new byte[8];
//RANDOM.NextBytes(clientChallenge_1); //RANDOM.NextBytes(clientChallenge_1);
SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge1)); SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge1));
@ -292,12 +284,8 @@ namespace SharpCifs.Ntlmssp
/// The workstation from which authentication is /// The workstation from which authentication is
/// taking place. /// taking place.
/// </param> /// </param>
public Type3Message(int flags, public Type3Message(int flags, byte[] lmResponse, byte[] ntResponse, string domain
byte[] lmResponse, , string user, string workstation)
byte[] ntResponse,
string domain,
string user,
string workstation)
{ {
SetFlags(flags); SetFlags(flags);
SetLmResponse(lmResponse); SetLmResponse(lmResponse);
@ -433,61 +421,39 @@ namespace SharpCifs.Ntlmssp
{ {
int flags = GetFlags(); int flags = GetFlags();
bool unicode = (flags & NtlmsspNegotiateUnicode) != 0; bool unicode = (flags & NtlmsspNegotiateUnicode) != 0;
string oem = unicode string oem = unicode ? null : GetOemEncoding();
? null
: GetOemEncoding();
string domainName = GetDomain(); string domainName = GetDomain();
byte[] domain = null; byte[] domain = null;
if (!string.IsNullOrEmpty(domainName)) if (!string.IsNullOrEmpty(domainName))
{ {
domain = unicode domain = unicode ? Runtime.GetBytesForString(domainName, UniEncoding) :
? Runtime.GetBytesForString(domainName, UniEncoding) Runtime.GetBytesForString(domainName, oem);
: Runtime.GetBytesForString(domainName, oem);
} }
int domainLength = (domain != null) int domainLength = (domain != null) ? domain.Length : 0;
? domain.Length
: 0;
string userName = GetUser(); string userName = GetUser();
byte[] user = null; byte[] user = null;
if (!string.IsNullOrEmpty(userName)) if (!string.IsNullOrEmpty(userName))
{ {
user = unicode user = unicode ? Runtime.GetBytesForString(userName, UniEncoding) : Runtime.GetBytesForString
? Runtime.GetBytesForString(userName, UniEncoding) (userName.ToUpper(), oem);
: Runtime.GetBytesForString(userName.ToUpper(), oem);
} }
int userLength = (user != null) int userLength = (user != null) ? user.Length : 0;
? user.Length
: 0;
string workstationName = GetWorkstation(); string workstationName = GetWorkstation();
byte[] workstation = null; byte[] workstation = null;
if (!string.IsNullOrEmpty(workstationName)) if (!string.IsNullOrEmpty(workstationName))
{ {
workstation = unicode workstation = unicode ? Runtime.GetBytesForString(workstationName, UniEncoding
? Runtime.GetBytesForString(workstationName, UniEncoding) ) : Runtime.GetBytesForString(workstationName.ToUpper(), oem);
: Runtime.GetBytesForString(workstationName.ToUpper(), oem);
} }
int workstationLength = (workstation != null) int workstationLength = (workstation != null) ? workstation.Length : 0;
? workstation.Length
: 0;
byte[] lmResponse = GetLMResponse(); byte[] lmResponse = GetLMResponse();
int lmLength = (lmResponse != null) int lmLength = (lmResponse != null) ? lmResponse.Length : 0;
? lmResponse.Length
: 0;
byte[] ntResponse = GetNTResponse(); byte[] ntResponse = GetNTResponse();
int ntLength = (ntResponse != null) int ntLength = (ntResponse != null) ? ntResponse.Length : 0;
? ntResponse.Length
: 0;
byte[] sessionKey = GetSessionKey(); byte[] sessionKey = GetSessionKey();
int keyLength = (sessionKey != null) int keyLength = (sessionKey != null) ? sessionKey.Length : 0;
? sessionKey.Length byte[] type3 = new byte[64 + domainLength + userLength + workstationLength + lmLength
: 0; + ntLength + keyLength];
byte[] type3 = new byte[64
+ domainLength
+ userLength
+ workstationLength
+ lmLength
+ ntLength
+ keyLength];
Array.Copy(NtlmsspSignature, 0, type3, 0, 8); Array.Copy(NtlmsspSignature, 0, type3, 0, 8);
WriteULong(type3, 8, 3); WriteULong(type3, 8, 3);
int offset = 64; int offset = 64;
@ -519,19 +485,11 @@ namespace SharpCifs.Ntlmssp
byte[] lmResponse = GetLMResponse(); byte[] lmResponse = GetLMResponse();
byte[] ntResponse = GetNTResponse(); byte[] ntResponse = GetNTResponse();
byte[] sessionKey = GetSessionKey(); byte[] sessionKey = GetSessionKey();
return "Type3Message[domain=" + domain return "Type3Message[domain=" + domain + ",user=" + user + ",workstation=" + workstation
+ ",user=" + user + ",lmResponse=" + (lmResponse == null ? "null" : "<" + lmResponse.Length + " bytes>"
+ ",workstation=" + workstation ) + ",ntResponse=" + (ntResponse == null ? "null" : "<" + ntResponse.Length + " bytes>"
+ ",lmResponse=" + (lmResponse == null ) + ",sessionKey=" + (sessionKey == null ? "null" : "<" + sessionKey.Length + " bytes>"
? "null" ) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
: "<" + lmResponse.Length + " bytes>")
+ ",ntResponse=" + (ntResponse == null
? "null"
: "<" + ntResponse.Length + " bytes>")
+ ",sessionKey=" + (sessionKey == null
? "null"
: "<" + sessionKey.Length + " bytes>")
+ ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
} }
/// <summary> /// <summary>
@ -564,8 +522,7 @@ namespace SharpCifs.Ntlmssp
return DefaultFlags; return DefaultFlags;
} }
int flags = NtlmsspNegotiateNtlm; int flags = NtlmsspNegotiateNtlm;
flags |= ((type2.GetFlags() & NtlmsspNegotiateUnicode) != 0) flags |= ((type2.GetFlags() & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode
? NtlmsspNegotiateUnicode
: NtlmsspNegotiateOem; : NtlmsspNegotiateOem;
return flags; return flags;
} }
@ -587,47 +544,33 @@ namespace SharpCifs.Ntlmssp
{ {
return null; return null;
} }
return NtlmPasswordAuthentication.GetPreNtlmResponse(password, return NtlmPasswordAuthentication.GetPreNtlmResponse(password, type2.GetChallenge
type2.GetChallenge()); ());
} }
public static byte[] GetLMv2Response(Type2Message type2, public static byte[] GetLMv2Response(Type2Message type2, string domain, string user
string domain, , string password, byte[] clientChallenge)
string user,
string password,
byte[] clientChallenge)
{ {
if (type2 == null if (type2 == null || domain == null || user == null || password == null || clientChallenge
|| domain == null == null)
|| user == null
|| password == null
|| clientChallenge == null)
{ {
return null; return null;
} }
return NtlmPasswordAuthentication.GetLMv2Response(domain, return NtlmPasswordAuthentication.GetLMv2Response(domain, user, password, type2.GetChallenge
user, (), clientChallenge);
password,
type2.GetChallenge(),
clientChallenge);
} }
public static byte[] GetNtlMv2Response(Type2Message type2, public static byte[] GetNtlMv2Response(Type2Message type2, byte[] responseKeyNt,
byte[] responseKeyNt,
byte[] clientChallenge) byte[] clientChallenge)
{ {
if (type2 == null || responseKeyNt == null || clientChallenge == null) if (type2 == null || responseKeyNt == null || clientChallenge == null)
{ {
return null; return null;
} }
long nanos1601 = (Runtime.CurrentTimeMillis() long nanos1601 = (Runtime.CurrentTimeMillis() + MillisecondsBetween1970And1601
+ MillisecondsBetween1970And1601) ) * 10000L;
* 10000L; return NtlmPasswordAuthentication.GetNtlMv2Response(responseKeyNt, type2.GetChallenge
return NtlmPasswordAuthentication.GetNtlMv2Response(responseKeyNt, (), clientChallenge, nanos1601, type2.GetTargetInformation());
type2.GetChallenge(),
clientChallenge,
nanos1601,
type2.GetTargetInformation());
} }
/// <summary> /// <summary>
@ -709,11 +652,8 @@ namespace SharpCifs.Ntlmssp
int flags; int flags;
string charset; string charset;
byte[] _sessionKey = null; byte[] _sessionKey = null;
if (lmResponseOffset == 52 if (lmResponseOffset == 52 || ntResponseOffset == 52 || domainOffset == 52 || userOffset
|| ntResponseOffset == 52 == 52 || workstationOffset == 52)
|| domainOffset == 52
|| userOffset == 52
|| workstationOffset == 52)
{ {
flags = NtlmsspNegotiateNtlm | NtlmsspNegotiateOem; flags = NtlmsspNegotiateNtlm | NtlmsspNegotiateOem;
charset = GetOemEncoding(); charset = GetOemEncoding();
@ -722,9 +662,8 @@ namespace SharpCifs.Ntlmssp
{ {
_sessionKey = ReadSecurityBuffer(material, 52); _sessionKey = ReadSecurityBuffer(material, 52);
flags = ReadULong(material, 60); flags = ReadULong(material, 60);
charset = ((flags & NtlmsspNegotiateUnicode) != 0) charset = ((flags & NtlmsspNegotiateUnicode) != 0) ? UniEncoding : GetOemEncoding
? UniEncoding ();
: GetOemEncoding();
} }
SetSessionKey(_sessionKey); SetSessionKey(_sessionKey);
SetFlags(flags); SetFlags(flags);

View File

@ -162,7 +162,7 @@ namespace SharpCifs.Smb
/// <summary>Returns the flags for this ACE.</summary> /// <summary>Returns the flags for this ACE.</summary>
/// <remarks> /// <remarks>
/// Returns the flags for this ACE. The <tt>isInherited()</tt> /// Returns the flags for this ACE. The </tt>isInherited()</tt>
/// method checks the <tt>FLAGS_INHERITED</tt> bit in these flags. /// method checks the <tt>FLAGS_INHERITED</tt> bit in these flags.
/// </remarks> /// </remarks>
public virtual int GetFlags() public virtual int GetFlags()
@ -181,7 +181,8 @@ namespace SharpCifs.Smb
/// </remarks> /// </remarks>
public virtual string GetApplyToText() public virtual string GetApplyToText()
{ {
switch (Flags & (FlagsObjectInherit | FlagsContainerInherit | FlagsInheritOnly)) switch (Flags & (FlagsObjectInherit | FlagsContainerInherit | FlagsInheritOnly
))
{ {
case unchecked(0x00): case unchecked(0x00):
{ {
@ -275,14 +276,10 @@ namespace SharpCifs.Smb
int i; int i;
string str; string str;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.Append(IsAllow() sb.Append(IsAllow() ? "Allow " : "Deny ");
? "Allow "
: "Deny ");
AppendCol(sb, Sid.ToDisplayString(), 25); AppendCol(sb, Sid.ToDisplayString(), 25);
sb.Append(" 0x").Append(Hexdump.ToHexString(Access, 8)).Append(' '); sb.Append(" 0x").Append(Hexdump.ToHexString(Access, 8)).Append(' ');
sb.Append(IsInherited() sb.Append(IsInherited() ? "Inherited " : "Direct ");
? "Inherited "
: "Direct ");
AppendCol(sb, GetApplyToText(), 34); AppendCol(sb, GetApplyToText(), 34);
return sb.ToString(); return sb.ToString();
} }

View File

@ -86,9 +86,8 @@ namespace SharpCifs.Smb
dst[dstIndex++] = unchecked((byte)(ByteCount & unchecked(0xFF))); dst[dstIndex++] = unchecked((byte)(ByteCount & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((ByteCount >> 8) & unchecked(0xFF))); dst[dstIndex++] = unchecked((byte)((ByteCount >> 8) & unchecked(0xFF)));
dstIndex += ByteCount; dstIndex += ByteCount;
if (Andx == null if (Andx == null || SmbConstants.UseBatching == false || BatchLevel >= GetBatchLimit(Andx.Command
|| SmbConstants.UseBatching == false ))
|| BatchLevel >= GetBatchLimit(Andx.Command))
{ {
_andxCommand = unchecked(unchecked(0xFF)); _andxCommand = unchecked(unchecked(0xFF));
Andx = null; Andx = null;
@ -110,7 +109,8 @@ namespace SharpCifs.Smb
if (Andx is AndXServerMessageBlock) if (Andx is AndXServerMessageBlock)
{ {
Andx.Uid = Uid; Andx.Uid = Uid;
dstIndex += ((AndXServerMessageBlock)Andx).WriteAndXWireFormat(dst, dstIndex); dstIndex += ((AndXServerMessageBlock)Andx).WriteAndXWireFormat(dst, dstIndex
);
} }
else else
{ {
@ -123,7 +123,8 @@ namespace SharpCifs.Smb
dst[andxStart] = unchecked((byte)(Andx.WordCount & unchecked(0xFF))); dst[andxStart] = unchecked((byte)(Andx.WordCount & unchecked(0xFF)));
Andx.ByteCount = Andx.WriteBytesWireFormat(dst, dstIndex + 2); Andx.ByteCount = Andx.WriteBytesWireFormat(dst, dstIndex + 2);
dst[dstIndex++] = unchecked((byte)(Andx.ByteCount & unchecked(0xFF))); dst[dstIndex++] = unchecked((byte)(Andx.ByteCount & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((Andx.ByteCount >> 8) & unchecked(0xFF))); dst[dstIndex++] = unchecked((byte)((Andx.ByteCount >> 8) & unchecked(0xFF)
));
dstIndex += Andx.ByteCount; dstIndex += Andx.ByteCount;
} }
return dstIndex - start; return dstIndex - start;
@ -184,12 +185,13 @@ namespace SharpCifs.Smb
Andx.UseUnicode = UseUnicode; Andx.UseUnicode = UseUnicode;
if (Andx is AndXServerMessageBlock) if (Andx is AndXServerMessageBlock)
{ {
bufferIndex += ((AndXServerMessageBlock)Andx).ReadAndXWireFormat(buffer, bufferIndex += ((AndXServerMessageBlock)Andx).ReadAndXWireFormat(buffer
bufferIndex); , bufferIndex);
} }
else else
{ {
buffer[bufferIndex++] = unchecked((byte)(Andx.WordCount & unchecked(0xFF))); buffer[bufferIndex++] = unchecked((byte)(Andx.WordCount & unchecked(0xFF))
);
if (Andx.WordCount != 0) if (Andx.WordCount != 0)
{ {
if (Andx.WordCount > 2) if (Andx.WordCount > 2)
@ -212,9 +214,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return base.ToString() return base.ToString() + ",andxCommand=0x" + Hexdump.ToHexString(_andxCommand
+ ",andxCommand=0x" + Hexdump.ToHexString(_andxCommand, 2) , 2) + ",andxOffset=" + _andxOffset;
+ ",andxOffset=" + _andxOffset;
} }
} }
} }

View File

@ -18,7 +18,8 @@ namespace SharpCifs.Smb
{ {
public class BufferCache public class BufferCache
{ {
private static readonly int MaxBuffers = Config.GetInt("jcifs.smb.maxBuffers", 16); private static readonly int MaxBuffers = Config.GetInt("jcifs.smb.maxBuffers", 16
);
internal static object[] Cache = new object[MaxBuffers]; internal static object[] Cache = new object[MaxBuffers];
@ -47,7 +48,8 @@ namespace SharpCifs.Smb
} }
} }
internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse rsp) internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse
rsp)
{ {
lock (Cache) lock (Cache)
{ {

View File

@ -41,14 +41,14 @@ namespace SharpCifs.Smb
internal static LogStream Log = LogStream.GetInstance(); internal static LogStream Log = LogStream.GetInstance();
internal static readonly bool StrictView internal static readonly bool StrictView = Config.GetBoolean("jcifs.smb.client.dfs.strictView"
= Config.GetBoolean("jcifs.smb.client.dfs.strictView", false); , false);
internal static readonly long Ttl internal static readonly long Ttl = Config.GetLong("jcifs.smb.client.dfs.ttl", 300
= Config.GetLong("jcifs.smb.client.dfs.ttl", 300); );
internal static readonly bool Disabled internal static readonly bool Disabled = Config.GetBoolean("jcifs.smb.client.dfs.disabled"
= Config.GetBoolean("jcifs.smb.client.dfs.disabled", false); , false);
internal static CacheEntry FalseEntry = new CacheEntry(0L); internal static CacheEntry FalseEntry = new CacheEntry(0L);
@ -106,7 +106,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception> /// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual bool IsTrustedDomain(string domain, NtlmPasswordAuthentication auth) public virtual bool IsTrustedDomain(string domain, NtlmPasswordAuthentication auth
)
{ {
Hashtable domains = GetTrustedDomains(auth); Hashtable domains = GetTrustedDomains(auth);
if (domains == null) if (domains == null)
@ -165,11 +166,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception> /// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual DfsReferral GetReferral(SmbTransport trans, public virtual DfsReferral GetReferral(SmbTransport trans, string domain, string
string domain, root, string path, NtlmPasswordAuthentication auth)
string root,
string path,
NtlmPasswordAuthentication auth)
{ {
if (Disabled) if (Disabled)
{ {
@ -203,10 +201,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception> /// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual DfsReferral Resolve(string domain, public virtual DfsReferral Resolve(string domain, string root, string path, NtlmPasswordAuthentication
string root, auth)
string path,
NtlmPasswordAuthentication auth)
{ {
lock (this) lock (this)
{ {

View File

@ -59,14 +59,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "DfsReferral[pathConsumed=" + PathConsumed return "DfsReferral[pathConsumed=" + PathConsumed + ",server=" + Server + ",share="
+ ",server=" + Server + Share + ",link=" + Link + ",path=" + Path + ",ttl=" + Ttl + ",expiration=" +
+ ",share=" + Share Expiration + ",resolveHashes=" + ResolveHashes + "]";
+ ",link=" + Link
+ ",path=" + Path
+ ",ttl=" + Ttl
+ ",expiration=" + Expiration
+ ",resolveHashes=" + ResolveHashes + "]";
} }
} }
} }

View File

@ -18,92 +18,47 @@ namespace SharpCifs.Smb
{ {
public static class DosError public static class DosError
{ {
public static int[][] DosErrorCodes = public static int[][] DosErrorCodes = { new[] { unchecked(0x00000000), unchecked(0x00000000) }, new[] { unchecked(0x00010001), unchecked((int)(0xc0000002)) }, new[] { unchecked(0x00010002), unchecked(
{ (int)(0xc0000002)) }, new[] { unchecked(0x00020001), unchecked((int)(
new[] { unchecked(0x00000000), unchecked(0x00000000) }, 0xc000000f)) }, new[] { unchecked(0x00020002), unchecked((int)(0xc000006a
new[] { unchecked(0x00010001), unchecked((int)(0xc0000002)) }, )) }, new[] { unchecked(0x00030001), unchecked((int)(0xc000003a)) },
new[] { unchecked(0x00010002), unchecked((int)(0xc0000002)) }, new[] { unchecked(0x00030002), unchecked((int)(0xc00000cb)) }, new[] { unchecked(0x00040002), unchecked((int)(0xc00000ca)) }, new[] { unchecked(
new[] { unchecked(0x00020001), unchecked((int)(0xc000000f)) }, 0x00050001), unchecked((int)(0xc0000022)) }, new[] { unchecked(0x00050002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x00060001), unchecked((int)(0xc0000008)) }, new[] { unchecked(0x00060002), unchecked(
new[] { unchecked(0x00020002), unchecked((int)(0xc000006a)) }, (int)(0xc00000cc)) }, new[] { unchecked(0x00080001), unchecked((int)(
new[] { unchecked(0x00030001), unchecked((int)(0xc000003a)) }, 0xc000009a)) }, new[] { unchecked(0x00130003), unchecked((int)(0xc00000a2
new[] { unchecked(0x00030002), unchecked((int)(0xc00000cb)) }, )) }, new[] { unchecked(0x00150003), unchecked((int)(0xc0000013)) },
new[] { unchecked(0x00040002), unchecked((int)(0xc00000ca)) }, new[] { unchecked(0x001f0001), unchecked((int)(0xc0000001)) }, new[] { unchecked(0x001f0003), unchecked((int)(0xc0000001)) }, new[] { unchecked(
new[] { unchecked(0x00050001), unchecked((int)(0xc0000022)) }, 0x00200001), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00200003), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00210003), unchecked((int)(0xc0000054)) }, new[] { unchecked(0x00270003), unchecked(
new[] { unchecked(0x00050002), unchecked((int)(0xc000000d)) }, (int)(0xc000007f)) }, new[] { unchecked(0x00340001), unchecked((int)(
new[] { unchecked(0x00060001), unchecked((int)(0xc0000008)) }, 0xC00000bd)) }, new[] { unchecked(0x00430001), unchecked((int)(0xc00000cc
new[] { unchecked(0x00060002), unchecked((int)(0xc00000cc)) }, )) }, new[] { unchecked(0x00470001), unchecked((int)(0xC00000d0)) },
new[] { unchecked(0x00080001), unchecked((int)(0xc000009a)) }, new[] { unchecked(0x00500001), unchecked((int)(0xc0000035)) }, new[] { unchecked(0x00570001), unchecked((int)(0xc0000003)) }, new[] { unchecked(
new[] { unchecked(0x00130003), unchecked((int)(0xc00000a2)) }, 0x005a0002), unchecked((int)(0xc00000ce)) }, new[] { unchecked(0x005b0002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x006d0001), unchecked((int)(0xC000014b)) }, new[] { unchecked(0x007b0001), unchecked(
new[] { unchecked(0x00150003), unchecked((int)(0xc0000013)) }, (int)(0xc0000033)) }, new[] { unchecked(0x00910001), unchecked((int)(
new[] { unchecked(0x001f0001), unchecked((int)(0xc0000001)) }, 0xC0000101)) }, new[] { unchecked(0x00b70001), unchecked((int)(0xc0000035
new[] { unchecked(0x001f0003), unchecked((int)(0xc0000001)) }, )) }, new[] { unchecked(0x00e70001), unchecked((int)(0xc00000ab)) },
new[] { unchecked(0x00200001), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00e80001), unchecked((int)(0xc00000b1)) }, new[] { unchecked(0x00e90001), unchecked((int)(0xc00000b0)) }, new[] { unchecked(
new[] { unchecked(0x00200003), unchecked((int)(0xc0000043)) }, 0x00ea0001), unchecked((int)(0xc0000016)) }, new[] { unchecked(0x08bf0002), unchecked((int)(0xC0000193)) }, new[] { unchecked(0x08c00002), unchecked((int)(0xC0000070)) }, new[] { unchecked(0x08c10002), unchecked(
new[] { unchecked(0x00210003), unchecked((int)(0xc0000054)) }, (int)(0xC000006f)) }, new[] { unchecked(0x08c20002), unchecked((int)(
new[] { unchecked(0x00270003), unchecked((int)(0xc000007f)) }, 0xC0000071)) } };
new[] { unchecked(0x00340001), unchecked((int)(0xC00000bd)) },
new[] { unchecked(0x00430001), unchecked((int)(0xc00000cc)) },
new[] { unchecked(0x00470001), unchecked((int)(0xC00000d0)) },
new[] { unchecked(0x00500001), unchecked((int)(0xc0000035)) },
new[] { unchecked(0x00570001), unchecked((int)(0xc0000003)) },
new[] { unchecked(0x005a0002), unchecked((int)(0xc00000ce)) },
new[] { unchecked(0x005b0002), unchecked((int)(0xc000000d)) },
new[] { unchecked(0x006d0001), unchecked((int)(0xC000014b)) },
new[] { unchecked(0x007b0001), unchecked((int)(0xc0000033)) },
new[] { unchecked(0x00910001), unchecked((int)(0xC0000101)) },
new[] { unchecked(0x00b70001), unchecked((int)(0xc0000035)) },
new[] { unchecked(0x00e70001), unchecked((int)(0xc00000ab)) },
new[] { unchecked(0x00e80001), unchecked((int)(0xc00000b1)) },
new[] { unchecked(0x00e90001), unchecked((int)(0xc00000b0)) },
new[] { unchecked(0x00ea0001), unchecked((int)(0xc0000016)) },
new[] { unchecked(0x08bf0002), unchecked((int)(0xC0000193)) },
new[] { unchecked(0x08c00002), unchecked((int)(0xC0000070)) },
new[] { unchecked(0x08c10002), unchecked((int)(0xC000006f)) },
new[] { unchecked(0x08c20002), unchecked((int)(0xC0000071)) }
};
public static string[] DosErrorMessages = public static string[] DosErrorMessages = { "The operation completed successfully."
{ , "Incorrect function.", "Incorrect function.", "The system cannot find the file specified."
"The operation completed successfully.", , "Bad password.", "The system cannot find the path specified.", "reserved", "The client does not have the necessary access rights to perform the requested function."
"Incorrect function.", , "Access is denied.", "The TID specified was invalid.", "The handle is invalid."
"Incorrect function.", , "The network name cannot be found.", "Not enough storage is available to process this command."
"The system cannot find the file specified.", , "The media is write protected.", "The device is not ready.", "A device attached to the system is not functioning."
"Bad password.", , "A device attached to the system is not functioning.", "The process cannot access the file because it is being used by another process."
"The system cannot find the path specified.", , "The process cannot access the file because it is being used by another process."
"reserved", , "The process cannot access the file because another process has locked a portion of the file."
"The client does not have the necessary access rights to perform the requested function.", , "The disk is full.", "A duplicate name exists on the network.", "The network name cannot be found."
"Access is denied.", , "ERRnomoreconn.", "The file exists.", "The parameter is incorrect.", "Too many Uids active on this session."
"The TID specified was invalid.", , "The Uid is not known as a valid user identifier on this session.", "The pipe has been ended."
"The handle is invalid.", , "The filename, directory name, or volume label syntax is incorrect.", "The directory is not empty."
"The network name cannot be found.", , "Cannot create a file when that file already exists.", "All pipe instances are busy."
"Not enough storage is available to process this command.", , "The pipe is being closed.", "No process is on the other end of the pipe.", "More data is available."
"The media is write protected.", , "This user account has expired.", "The user is not allowed to log on from this workstation."
"The device is not ready.", , "The user is not allowed to log on at this time.", "The password of this user has expired."
"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 Uid is not known as a valid user identifier 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."
}; };
} }
} }

View File

@ -25,11 +25,8 @@ namespace SharpCifs.Smb
internal const int SvTypeDomainEnum = unchecked((int)(0x80000000)); internal const int SvTypeDomainEnum = unchecked((int)(0x80000000));
internal static readonly string[] Descr = internal static readonly string[] Descr = { "WrLehDO\u0000B16BBDz\u0000"
{ , "WrLehDz\u0000B16BBDz\u0000" };
"WrLehDO\u0000B16BBDz\u0000",
"WrLehDz\u0000B16BBDz\u0000"
};
internal string Domain; internal string Domain;
@ -99,12 +96,14 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{ {
return 0; return 0;
} }
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{ {
return 0; return 0;
} }
@ -116,12 +115,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "NetServerEnum2[" return "NetServerEnum2[" + base.ToString() + ",name=" + Name + ",serverTypes="
+ base.ToString() + (ServerTypes == SvTypeAll ? "SV_TYPE_ALL" : "SV_TYPE_DOMAIN_ENUM") + "]";
+ ",name=" + Name
+ ",serverTypes=" + (ServerTypes == SvTypeAll
? "SV_TYPE_ALL"
: "SV_TYPE_DOMAIN_ENUM") + "]";
} }
} }
} }

View File

@ -39,9 +39,8 @@ namespace SharpCifs.Smb
public new virtual int GetType() public new virtual int GetType()
{ {
return (Type & unchecked((int)(0x80000000))) != 0 return (Type & unchecked((int)(0x80000000))) != 0 ? SmbFile.TypeWorkgroup :
? SmbFile.TypeWorkgroup SmbFile.TypeServer;
: SmbFile.TypeServer;
} }
public virtual int GetAttributes() public virtual int GetAttributes()
@ -66,12 +65,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "ServerInfo1[" return "ServerInfo1[" + "name=" + Name + ",versionMajor=" + VersionMajor + ",versionMinor=" + VersionMinor + ",type=0x" + Hexdump.ToHexString
+ "name=" + Name (Type, 8) + ",commentOrMasterBrowser=" + CommentOrMasterBrowser + "]";
+ ",versionMajor=" + VersionMajor
+ ",versionMinor=" + VersionMinor
+ ",type=0x" + Hexdump.ToHexString(Type, 8)
+ ",commentOrMasterBrowser=" + CommentOrMasterBrowser + "]";
} }
internal ServerInfo1(NetServerEnum2Response enclosing) internal ServerInfo1(NetServerEnum2Response enclosing)
@ -109,7 +104,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{ {
int start = bufferIndex; int start = bufferIndex;
Status = ReadInt2(buffer, bufferIndex); Status = ReadInt2(buffer, bufferIndex);
@ -153,13 +149,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "NetServerEnum2Response[" return "NetServerEnum2Response[" + base.ToString() + ",status=" + Status
+ base.ToString() + ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries="
+ ",status=" + Status + _totalAvailableEntries + ",lastName=" + LastName + "]";
+ ",converter=" + _converter
+ ",entriesReturned=" + NumEntries
+ ",totalAvailableEntries=" + _totalAvailableEntries
+ ",lastName=" + LastName + "]";
} }
} }
} }

View File

@ -70,12 +70,14 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{ {
return 0; return 0;
} }
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{ {
return 0; return 0;
} }

View File

@ -37,12 +37,14 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{ {
return 0; return 0;
} }
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{ {
int start = bufferIndex; int start = bufferIndex;
Status = ReadInt2(buffer, bufferIndex); Status = ReadInt2(buffer, bufferIndex);
@ -84,12 +86,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "NetShareEnumResponse[" return "NetShareEnumResponse[" + base.ToString() + ",status=" + Status
+ base.ToString() + ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries="
+ ",status=" + Status + _totalAvailableEntries + "]";
+ ",converter=" + _converter
+ ",entriesReturned=" + NumEntries
+ ",totalAvailableEntries=" + _totalAvailableEntries + "]";
} }
} }
} }

View File

@ -36,7 +36,8 @@ namespace SharpCifs.Smb
public const int NtStatusNoSuchFile = unchecked((int)(0xC000000f)); public const int NtStatusNoSuchFile = unchecked((int)(0xC000000f));
public const int NtStatusMoreProcessingRequired = unchecked((int)(0xC0000016)); public const int NtStatusMoreProcessingRequired = unchecked((int)(0xC0000016)
);
public const int NtStatusAccessDenied = unchecked((int)(0xC0000022)); public const int NtStatusAccessDenied = unchecked((int)(0xC0000022));
@ -130,7 +131,8 @@ namespace SharpCifs.Smb
public const int NtStatusTrustedDomainFailure = unchecked((int)(0xC000018c)); public const int NtStatusTrustedDomainFailure = unchecked((int)(0xC000018c));
public const int NtStatusNologonWorkstationTrustAccount = unchecked((int)(0xC0000199)); public const int NtStatusNologonWorkstationTrustAccount = unchecked((int)(0xC0000199
));
public const int NtStatusPasswordMustChange = unchecked((int)(0xC0000224)); public const int NtStatusPasswordMustChange = unchecked((int)(0xC0000224));
@ -140,138 +142,61 @@ namespace SharpCifs.Smb
public const int NtStatusPathNotCovered = unchecked((int)(0xC0000257)); public const int NtStatusPathNotCovered = unchecked((int)(0xC0000257));
public const int NtStatusIoReparseTagNotHandled = unchecked((int)(0xC0000279)); public const int NtStatusIoReparseTagNotHandled = unchecked((int)(0xC0000279
));
public static int[] NtStatusCodes = public static int[] NtStatusCodes = { NtStatusOk, NtStatusUnsuccessful
{ , NtStatusNotImplemented, NtStatusInvalidInfoClass, NtStatusAccessViolation
NtStatusOk, , NtStatusInvalidHandle, NtStatusInvalidParameter, NtStatusNoSuchDevice
NtStatusUnsuccessful, , NtStatusNoSuchFile, NtStatusMoreProcessingRequired, NtStatusAccessDenied
NtStatusNotImplemented, , NtStatusBufferTooSmall, NtStatusObjectNameInvalid, NtStatusObjectNameNotFound
NtStatusInvalidInfoClass, , NtStatusObjectNameCollision, NtStatusPortDisconnected, NtStatusObjectPathInvalid
NtStatusAccessViolation, , NtStatusObjectPathNotFound, NtStatusObjectPathSyntaxBad, NtStatusSharingViolation
NtStatusInvalidHandle, , NtStatusDeletePending, NtStatusNoLogonServers, NtStatusUserExists, NtStatusNoSuchUser
NtStatusInvalidParameter, , NtStatusWrongPassword, NtStatusLogonFailure, NtStatusAccountRestriction
NtStatusNoSuchDevice, , NtStatusInvalidLogonHours, NtStatusInvalidWorkstation, NtStatusPasswordExpired
NtStatusNoSuchFile, , NtStatusAccountDisabled, NtStatusNoneMapped, NtStatusInvalidSid, NtStatusInstanceNotAvailable
NtStatusMoreProcessingRequired, , NtStatusPipeNotAvailable, NtStatusInvalidPipeState, NtStatusPipeBusy
NtStatusAccessDenied, , NtStatusPipeDisconnected, NtStatusPipeClosing, NtStatusPipeListening,
NtStatusBufferTooSmall, NtStatusFileIsADirectory, NtStatusDuplicateName, NtStatusNetworkNameDeleted
NtStatusObjectNameInvalid, , NtStatusNetworkAccessDenied, NtStatusBadNetworkName, NtStatusRequestNotAccepted
NtStatusObjectNameNotFound, , NtStatusCantAccessDomainInfo, NtStatusNoSuchDomain, NtStatusNotADirectory
NtStatusObjectNameCollision, , NtStatusCannotDelete, NtStatusInvalidComputerName, NtStatusPipeBroken
NtStatusPortDisconnected, , NtStatusNoSuchAlias, NtStatusLogonTypeNotGranted, NtStatusNoTrustSamAccount
NtStatusObjectPathInvalid, , NtStatusTrustedDomainFailure, NtStatusNologonWorkstationTrustAccount,
NtStatusObjectPathNotFound, NtStatusPasswordMustChange, NtStatusNotFound, NtStatusAccountLockedOut
NtStatusObjectPathSyntaxBad, , NtStatusPathNotCovered, NtStatusIoReparseTagNotHandled };
NtStatusSharingViolation,
NtStatusDeletePending,
NtStatusNoLogonServers,
NtStatusUserExists,
NtStatusNoSuchUser,
NtStatusWrongPassword,
NtStatusLogonFailure,
NtStatusAccountRestriction,
NtStatusInvalidLogonHours,
NtStatusInvalidWorkstation,
NtStatusPasswordExpired,
NtStatusAccountDisabled,
NtStatusNoneMapped,
NtStatusInvalidSid,
NtStatusInstanceNotAvailable,
NtStatusPipeNotAvailable,
NtStatusInvalidPipeState,
NtStatusPipeBusy,
NtStatusPipeDisconnected,
NtStatusPipeClosing,
NtStatusPipeListening,
NtStatusFileIsADirectory,
NtStatusDuplicateName,
NtStatusNetworkNameDeleted,
NtStatusNetworkAccessDenied,
NtStatusBadNetworkName,
NtStatusRequestNotAccepted,
NtStatusCantAccessDomainInfo,
NtStatusNoSuchDomain,
NtStatusNotADirectory,
NtStatusCannotDelete,
NtStatusInvalidComputerName,
NtStatusPipeBroken,
NtStatusNoSuchAlias,
NtStatusLogonTypeNotGranted,
NtStatusNoTrustSamAccount,
NtStatusTrustedDomainFailure,
NtStatusNologonWorkstationTrustAccount,
NtStatusPasswordMustChange,
NtStatusNotFound,
NtStatusAccountLockedOut,
NtStatusPathNotCovered,
NtStatusIoReparseTagNotHandled
};
public static string[] NtStatusMessages = public static string[] NtStatusMessages = { "The operation completed successfully."
{ , "A device attached to the system is not functioning.", "Incorrect function.",
"The operation completed successfully.", "The parameter is incorrect.", "Invalid access to memory location.", "The handle is invalid."
"A device attached to the system is not functioning.", , "The parameter is incorrect.", "The system cannot find the file specified.", "The system cannot find the file specified."
"Incorrect function.", , "More data is available.", "Access is denied.", "The data area passed to a system call is too small."
"The parameter is incorrect.", , "The filename, directory name, or volume label syntax is incorrect.", "The system cannot find the file specified."
"Invalid access to memory location.", , "Cannot create a file when that file already exists.", "The handle is invalid."
"The handle is invalid.", , "The specified path is invalid.", "The system cannot find the path specified."
"The parameter is incorrect.", , "The specified path is invalid.", "The process cannot access the file because it is being used by another process."
"The system cannot find the file specified.", , "Access is denied.", "There are currently no logon servers available to service the logon request."
"The system cannot find the file specified.", , "The specified user already exists.", "The specified user does not exist.", "The specified network password is not correct."
"More data is available.", , "Logon failure: unknown user name or bad password.", "Logon failure: user account restriction."
"Access is denied.", , "Logon failure: account logon time restriction violation.", "Logon failure: user not allowed to log on to this computer."
"The data area passed to a system call is too small.", , "Logon failure: the specified account password has expired.", "Logon failure: account currently disabled."
"The filename, directory name, or volume label syntax is incorrect.", , "No mapping between account names and security IDs was done.", "The security ID structure is invalid."
"The system cannot find the file specified.", , "All pipe instances are busy.", "All pipe instances are busy.", "The pipe state is invalid."
"Cannot create a file when that file already exists.", , "All pipe instances are busy.", "No process is on the other end of the pipe.",
"The handle is invalid.", "The pipe is being closed.", "Waiting for a process to open the other end of the pipe."
"The specified path is invalid.", , "Access is denied.", "A duplicate name exists on the network.", "The specified network name is no longer available."
"The system cannot find the path specified.", , "Network access is denied.", "The network name cannot be found.", "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 specified path is invalid.", , "Indicates a Windows NT Server could not be contacted or that objects within the domain are protected such that necessary information could not be retrieved."
"The process cannot access the file because it is being used by another process.", , "The specified domain did not exist.", "The directory name is invalid.", "Access is denied."
"Access is denied.", , "The format of the specified computer name is invalid.", "The pipe has been ended."
"There are currently no logon servers available to service the logon request.", , "The specified local group does not exist.", "Logon failure: the user has not been granted the requested logon type at this computer."
"The specified user already exists.", , "The SAM database on the Windows NT Server does not have a computer account for this workstation trust relationship."
"The specified user does not exist.", , "The trust relationship between the primary domain and the trusted domain failed."
"The specified network password is not correct.", , "The account used is a Computer Account. Use your global user account or local user account to access this server."
"Logon failure: unknown user name or bad password.", , "The user must change his password before he logs on the first time.", "NT_STATUS_NOT_FOUND"
"Logon failure: user account restriction.", , "The referenced account is currently locked out and may not be logged on to.",
"Logon failure: account logon time restriction violation.", "The remote system is not reachable by the transport.", "NT_STATUS_IO_REPARSE_TAG_NOT_HANDLED"
"Logon failure: user not allowed to log on to this computer.",
"Logon failure: the specified account password has expired.",
"Logon failure: account currently disabled.",
"No mapping between account names and security IDs was done.",
"The security ID structure is invalid.",
"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.",
"A duplicate name exists on the network.",
"The specified network name is no longer available.",
"Network access is denied.",
"The network name cannot be found.",
"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.",
"Indicates a Windows NT Server could not be contacted or that objects within the domain are protected such that necessary information could not be retrieved.",
"The specified domain did not exist.",
"The directory name is invalid.",
"Access is denied.",
"The format of the specified computer name is invalid.",
"The pipe has been ended.",
"The specified local group does not exist.",
"Logon failure: the user has not been granted the requested logon type at this computer.",
"The SAM database on the Windows NT Server does not have a computer account for this workstation trust relationship.",
"The trust relationship between the primary domain and the trusted domain failed.",
"The account used is a Computer Account. Use your global user account or local user account to access this server.",
"The user must change his password before he logs on the first time.",
"NT_STATUS_NOT_FOUND",
"The referenced account is currently locked out and may not be logged on to.",
"The remote system is not reachable by the transport.",
"NT_STATUS_IO_REPARSE_TAG_NOT_HANDLED"
}; };
} }
} }

View File

@ -61,12 +61,14 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{ {
return 0; return 0;
} }
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{ {
return 0; return 0;
} }
@ -78,11 +80,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "NtTransQuerySecurityDesc[" return "NtTransQuerySecurityDesc[" + base.ToString() + ",fid=0x" + Hexdump
+ base.ToString() .ToHexString(Fid, 4) + ",securityInformation=0x" + Hexdump.ToHexString(SecurityInformation
+ ",fid=0x" + Hexdump.ToHexString(Fid, 4) , 8) + "]";
+ ",securityInformation=0x" + Hexdump.ToHexString(SecurityInformation, 8)
+ "]";
} }
} }
} }

View File

@ -38,12 +38,14 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{ {
return 0; return 0;
} }
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{ {
Length = ReadInt4(buffer, bufferIndex); Length = ReadInt4(buffer, bufferIndex);
return 4; return 4;

View File

@ -16,11 +16,9 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
/// <summary> /// <summary>This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials.
/// This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials.
/// </summary> /// </summary>
/// <remarks> /// <remarks>This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials. Read <a href="../../../authhandler.html">jCIFS Exceptions and NtlmAuthenticator</a> for complete details.
/// This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials. Read <a href="../../../authhandler.html">jCIFS Exceptions and NtlmAuthenticator</a> for complete details.
/// </remarks> /// </remarks>
public abstract class NtlmAuthenticator public abstract class NtlmAuthenticator
{ {
@ -37,8 +35,7 @@ namespace SharpCifs.Smb
} }
/// <summary>Set the default <tt>NtlmAuthenticator</tt>.</summary> /// <summary>Set the default <tt>NtlmAuthenticator</tt>.</summary>
/// <remarks> /// <remarks>Set the default <tt>NtlmAuthenticator</tt>. Once the default authenticator is set it cannot be changed. Calling this metho again will have no effect.
/// Set the default <tt>NtlmAuthenticator</tt>. Once the default authenticator is set it cannot be changed. Calling this metho again will have no effect.
/// </remarks> /// </remarks>
public static void SetDefault(NtlmAuthenticator a) public static void SetDefault(NtlmAuthenticator a)
{ {
@ -62,14 +59,12 @@ namespace SharpCifs.Smb
return _sae; return _sae;
} }
/// <summary> /// <summary>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
/// Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
/// </summary> /// </summary>
/// <remarks> /// <remarks>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
/// Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
/// </remarks> /// </remarks>
public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string url, public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string
SmbAuthException sae) url, SmbAuthException sae)
{ {
if (_auth == null) if (_auth == null)
{ {
@ -89,7 +84,8 @@ namespace SharpCifs.Smb
/// 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. /// 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>. /// 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>.
/// </remarks> /// </remarks>
protected internal virtual NtlmPasswordAuthentication GetNtlmPasswordAuthentication() protected internal virtual NtlmPasswordAuthentication GetNtlmPasswordAuthentication
()
{ {
return null; return null;
} }

View File

@ -33,8 +33,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "NtlmChallenge[challenge=0x" + Hexdump.ToHexString(Challenge, 0, Challenge.Length * 2) return "NtlmChallenge[challenge=0x" + Hexdump.ToHexString(Challenge, 0, Challenge
+ ",dc=" + Dc + "]"; .Length * 2) + ",dc=" + Dc + "]";
} }
} }
} }

View File

@ -47,14 +47,11 @@ namespace SharpCifs.Smb
public NtlmContext(NtlmPasswordAuthentication auth, bool doSigning) public NtlmContext(NtlmPasswordAuthentication auth, bool doSigning)
{ {
this.Auth = auth; this.Auth = auth;
NtlmsspFlags = NtlmsspFlags NtlmsspFlags = NtlmsspFlags | NtlmFlags.NtlmsspRequestTarget | NtlmFlags.NtlmsspNegotiateNtlm2
| NtlmFlags.NtlmsspRequestTarget
| NtlmFlags.NtlmsspNegotiateNtlm2
| NtlmFlags.NtlmsspNegotiate128; | NtlmFlags.NtlmsspNegotiate128;
if (doSigning) if (doSigning)
{ {
NtlmsspFlags |= NtlmFlags.NtlmsspNegotiateSign NtlmsspFlags |= NtlmFlags.NtlmsspNegotiateSign | NtlmFlags.NtlmsspNegotiateAlwaysSign
| NtlmFlags.NtlmsspNegotiateAlwaysSign
| NtlmFlags.NtlmsspNegotiateKeyExch; | NtlmFlags.NtlmsspNegotiateKeyExch;
} }
Workstation = Type1Message.GetDefaultWorkstation(); Workstation = Type1Message.GetDefaultWorkstation();
@ -63,12 +60,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
string ret = "NtlmContext[auth=" + Auth string ret = "NtlmContext[auth=" + Auth + ",ntlmsspFlags=0x" + Hexdump.ToHexString
+ ",ntlmsspFlags=0x" + Hexdump.ToHexString(NtlmsspFlags, 8) (NtlmsspFlags, 8) + ",workstation=" + Workstation + ",isEstablished=" + isEstablished
+ ",workstation=" + Workstation + ",state=" + State + ",serverChallenge=";
+ ",isEstablished=" + isEstablished
+ ",state=" + State
+ ",serverChallenge=";
if (ServerChallenge == null) if (ServerChallenge == null)
{ {
ret += "null"; ret += "null";
@ -126,10 +120,8 @@ namespace SharpCifs.Smb
{ {
try try
{ {
return Runtime.GetStringForBytes(type2Token, return Runtime.GetStringForBytes(type2Token, ri, len, SmbConstants.UniEncoding
ri, );
len,
SmbConstants.UniEncoding);
} }
catch (UnsupportedEncodingException) catch (UnsupportedEncodingException)
{ {
@ -148,9 +140,7 @@ namespace SharpCifs.Smb
{ {
case 1: case 1:
{ {
Type1Message msg1 = new Type1Message(NtlmsspFlags, Type1Message msg1 = new Type1Message(NtlmsspFlags, Auth.GetDomain(), Workstation);
Auth.GetDomain(),
Workstation);
token = msg1.ToByteArray(); token = msg1.ToByteArray();
if (Log.Level >= 4) if (Log.Level >= 4)
{ {
@ -180,12 +170,8 @@ namespace SharpCifs.Smb
ServerChallenge = msg2.GetChallenge(); ServerChallenge = msg2.GetChallenge();
NtlmsspFlags &= msg2.GetFlags(); NtlmsspFlags &= msg2.GetFlags();
// netbiosName = getNtlmsspListItem(token, 0x0001); // netbiosName = getNtlmsspListItem(token, 0x0001);
Type3Message msg3 = new Type3Message(msg2, Type3Message msg3 = new Type3Message(msg2, Auth.GetPassword(), Auth.GetDomain(),
Auth.GetPassword(), Auth.GetUsername(), Workstation, NtlmsspFlags);
Auth.GetDomain(),
Auth.GetUsername(),
Workstation,
NtlmsspFlags);
token = msg3.ToByteArray(); token = msg3.ToByteArray();
if (Log.Level >= 4) if (Log.Level >= 4)
{ {

View File

@ -33,24 +33,14 @@ namespace SharpCifs.Smb
public sealed class NtlmPasswordAuthentication : Principal public sealed class NtlmPasswordAuthentication : Principal
{ {
private static readonly int LmCompatibility private static readonly int LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility"
= Config.GetInt("jcifs.smb.lmCompatibility", 3); , 3);
private static readonly Random Random = new Random(); private static readonly Random Random = new Random();
private static LogStream _log = LogStream.GetInstance(); private static LogStream _log = LogStream.GetInstance();
private static readonly byte[] S8 = private static readonly byte[] S8 = { unchecked(unchecked(0x4b)), unchecked(unchecked(0x47)), unchecked(unchecked(0x53)), unchecked(unchecked(0x21)), unchecked(unchecked(0x40)), unchecked(unchecked(0x23)), unchecked(unchecked(0x24)), unchecked(unchecked(0x25)) };
{
unchecked(unchecked(0x4b)),
unchecked(unchecked(0x47)),
unchecked(unchecked(0x53)),
unchecked(unchecked(0x21)),
unchecked(unchecked(0x40)),
unchecked(unchecked(0x23)),
unchecked(unchecked(0x24)),
unchecked(unchecked(0x25))
};
// KGS!@#$% // KGS!@#$%
private static void E(byte[] key, byte[] data, byte[] e) private static void E(byte[] key, byte[] data, byte[] e)
@ -74,8 +64,8 @@ namespace SharpCifs.Smb
internal static readonly string Blank = string.Empty; internal static readonly string Blank = string.Empty;
public static readonly NtlmPasswordAuthentication Anonymous public static readonly NtlmPasswordAuthentication Anonymous = new NtlmPasswordAuthentication
= new NtlmPasswordAuthentication(string.Empty, string.Empty, string.Empty); (string.Empty, string.Empty, string.Empty);
internal static void InitDefaults() internal static void InitDefaults()
{ {
@ -88,11 +78,9 @@ namespace SharpCifs.Smb
DefaultPassword = Config.GetProperty("jcifs.smb.client.password", Blank); DefaultPassword = Config.GetProperty("jcifs.smb.client.password", Blank);
} }
/// <summary> /// <summary>Generate the ANSI DES hash for the password associated with these credentials.
/// Generate the ANSI DES hash for the password associated with these credentials.
/// </summary> /// </summary>
/// <remarks> /// <remarks>Generate the ANSI DES hash for the password associated with these credentials.
/// Generate the ANSI DES hash for the password associated with these credentials.
/// </remarks> /// </remarks>
public static byte[] GetPreNtlmResponse(string password, byte[] challenge) public static byte[] GetPreNtlmResponse(string password, byte[] challenge)
{ {
@ -120,11 +108,9 @@ namespace SharpCifs.Smb
return p24; return p24;
} }
/// <summary> /// <summary>Generate the Unicode MD4 hash for the password associated with these credentials.
/// Generate the Unicode MD4 hash for the password associated with these credentials.
/// </summary> /// </summary>
/// <remarks> /// <remarks>Generate the Unicode MD4 hash for the password associated with these credentials.
/// Generate the Unicode MD4 hash for the password associated with these credentials.
/// </remarks> /// </remarks>
public static byte[] GetNtlmResponse(string password, byte[] challenge) public static byte[] GetNtlmResponse(string password, byte[] challenge)
{ {
@ -166,11 +152,8 @@ namespace SharpCifs.Smb
/// <param name="password">The user's password.</param> /// <param name="password">The user's password.</param>
/// <param name="challenge">The server challenge.</param> /// <param name="challenge">The server challenge.</param>
/// <param name="clientChallenge">The client challenge (nonce).</param> /// <param name="clientChallenge">The client challenge (nonce).</param>
public static byte[] GetLMv2Response(string domain, public static byte[] GetLMv2Response(string domain, string user, string password,
string user, byte[] challenge, byte[] clientChallenge)
string password,
byte[] challenge,
byte[] clientChallenge)
{ {
try try
{ {
@ -178,10 +161,13 @@ namespace SharpCifs.Smb
byte[] response = new byte[24]; byte[] response = new byte[24];
// The next 2-1/2 lines of this should be placed with nTOWFv1 in place of password // The next 2-1/2 lines of this should be placed with nTOWFv1 in place of password
Md4 md4 = new Md4(); Md4 md4 = new Md4();
md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)); md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
);
Hmact64 hmac = new Hmact64(md4.Digest()); Hmact64 hmac = new Hmact64(md4.Digest());
hmac.Update(Runtime.GetBytesForString(user.ToUpper(), SmbConstants.UniEncoding)); hmac.Update(Runtime.GetBytesForString(user.ToUpper(), SmbConstants.UniEncoding
hmac.Update(Runtime.GetBytesForString(domain.ToUpper(), SmbConstants.UniEncoding)); ));
hmac.Update(Runtime.GetBytesForString(domain.ToUpper(), SmbConstants.UniEncoding
));
hmac = new Hmact64(hmac.Digest()); hmac = new Hmact64(hmac.Digest());
hmac.Update(challenge); hmac.Update(challenge);
hmac.Update(clientChallenge); hmac.Update(clientChallenge);
@ -199,9 +185,8 @@ namespace SharpCifs.Smb
} }
} }
public static byte[] GetNtlm2Response(byte[] nTowFv1, public static byte[] GetNtlm2Response(byte[] nTowFv1, byte[] serverChallenge, byte
byte[] serverChallenge, [] clientChallenge)
byte[] clientChallenge)
{ {
byte[] sessionHash = new byte[8]; byte[] sessionHash = new byte[8];
try try
@ -236,7 +221,8 @@ namespace SharpCifs.Smb
try try
{ {
Md4 md4 = new Md4(); Md4 md4 = new Md4();
md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)); md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
);
return md4.Digest(); return md4.Digest();
} }
catch (UnsupportedEncodingException uee) catch (UnsupportedEncodingException uee)
@ -250,9 +236,11 @@ namespace SharpCifs.Smb
try try
{ {
Md4 md4 = new Md4(); Md4 md4 = new Md4();
md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)); md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
);
Hmact64 hmac = new Hmact64(md4.Digest()); Hmact64 hmac = new Hmact64(md4.Digest());
hmac.Update(Runtime.GetBytesForString(username.ToUpper(), SmbConstants.UniEncoding)); hmac.Update(Runtime.GetBytesForString(username.ToUpper(), SmbConstants.UniEncoding
));
hmac.Update(Runtime.GetBytesForString(domain, SmbConstants.UniEncoding)); hmac.Update(Runtime.GetBytesForString(domain, SmbConstants.UniEncoding));
return hmac.Digest(); return hmac.Digest();
} }
@ -262,11 +250,8 @@ namespace SharpCifs.Smb
} }
} }
internal static byte[] ComputeResponse(byte[] responseKey, internal static byte[] ComputeResponse(byte[] responseKey, byte[] serverChallenge
byte[] serverChallenge, , byte[] clientData, int offset, int length)
byte[] clientData,
int offset,
int length)
{ {
Hmact64 hmac = new Hmact64(responseKey); Hmact64 hmac = new Hmact64(responseKey);
hmac.Update(serverChallenge); hmac.Update(serverChallenge);
@ -278,26 +263,17 @@ namespace SharpCifs.Smb
return ret; return ret;
} }
public static byte[] GetLMv2Response(byte[] responseKeyLm, public static byte[] GetLMv2Response(byte[] responseKeyLm, byte[] serverChallenge
byte[] serverChallenge, , byte[] clientChallenge)
byte[] clientChallenge)
{ {
return ComputeResponse(responseKeyLm, return ComputeResponse(responseKeyLm, serverChallenge
serverChallenge, , clientChallenge, 0, clientChallenge.Length);
clientChallenge,
0,
clientChallenge.Length);
} }
public static byte[] GetNtlMv2Response(byte[] responseKeyNt, public static byte[] GetNtlMv2Response(byte[] responseKeyNt, byte[] serverChallenge
byte[] serverChallenge, , byte[] clientChallenge, long nanos1601, byte[] targetInfo)
byte[] clientChallenge,
long nanos1601,
byte[] targetInfo)
{ {
int targetInfoLength = targetInfo != null int targetInfoLength = targetInfo != null ? targetInfo.Length : 0;
? targetInfo.Length
: 0;
byte[] temp = new byte[28 + targetInfoLength + 4]; byte[] temp = new byte[28 + targetInfoLength + 4];
Encdec.Enc_uint32le(unchecked(0x00000101), temp, 0); Encdec.Enc_uint32le(unchecked(0x00000101), temp, 0);
// Header // Header
@ -313,21 +289,18 @@ namespace SharpCifs.Smb
} }
Encdec.Enc_uint32le(unchecked(0x00000000), temp, 28 + targetInfoLength); Encdec.Enc_uint32le(unchecked(0x00000000), temp, 28 + targetInfoLength);
// mystery bytes! // mystery bytes!
return ComputeResponse(responseKeyNt, return ComputeResponse(responseKeyNt, serverChallenge
serverChallenge, , temp, 0, temp.Length);
temp,
0,
temp.Length);
} }
internal static readonly NtlmPasswordAuthentication Null internal static readonly NtlmPasswordAuthentication Null = new NtlmPasswordAuthentication
= new NtlmPasswordAuthentication(string.Empty, string.Empty, string.Empty); (string.Empty, string.Empty, string.Empty);
internal static readonly NtlmPasswordAuthentication Guest internal static readonly NtlmPasswordAuthentication Guest = new NtlmPasswordAuthentication
= new NtlmPasswordAuthentication("?", "GUEST", string.Empty); ("?", "GUEST", string.Empty);
internal static readonly NtlmPasswordAuthentication Default internal static readonly NtlmPasswordAuthentication Default = new NtlmPasswordAuthentication
= new NtlmPasswordAuthentication(null); (null);
internal string Domain; internal string Domain;
@ -416,7 +389,8 @@ namespace SharpCifs.Smb
/// <tt>jcifs.smb.client.username</tt>, <tt>jcifs.smb.client.password</tt> /// <tt>jcifs.smb.client.username</tt>, <tt>jcifs.smb.client.password</tt>
/// property values. /// property values.
/// </remarks> /// </remarks>
public NtlmPasswordAuthentication(string domain, string username, string password) public NtlmPasswordAuthentication(string domain, string username, string password
)
{ {
int ci; int ci;
if (username != null) if (username != null)
@ -464,16 +438,10 @@ namespace SharpCifs.Smb
/// hashes. This is used exclusively by the <tt>jcifs.http.NtlmSsp</tt> /// hashes. This is used exclusively by the <tt>jcifs.http.NtlmSsp</tt>
/// class which is in turn used by NTLM HTTP authentication functionality. /// class which is in turn used by NTLM HTTP authentication functionality.
/// </remarks> /// </remarks>
public NtlmPasswordAuthentication(string domain, public NtlmPasswordAuthentication(string domain, string username, byte[] challenge
string username, , byte[] ansiHash, byte[] unicodeHash)
byte[] challenge,
byte[] ansiHash,
byte[] unicodeHash)
{ {
if (domain == null if (domain == null || username == null || ansiHash == null || unicodeHash == null)
|| username == null
|| ansiHash == null
|| unicodeHash == null)
{ {
throw new ArgumentException("External credentials cannot be null"); throw new ArgumentException("External credentials cannot be null");
} }
@ -529,16 +497,12 @@ namespace SharpCifs.Smb
public new string GetName() public new string GetName()
{ {
bool d = Domain.Length > 0 && Domain.Equals("?") == false; bool d = Domain.Length > 0 && Domain.Equals("?") == false;
return d return d ? Domain + "\\" + Username : Username;
? Domain + "\\" + Username
: Username;
} }
/// <summary> /// <summary>Computes the 24 byte ANSI password hash given the 8 byte server challenge.
/// Computes the 24 byte ANSI password hash given the 8 byte server challenge.
/// </summary> /// </summary>
/// <remarks> /// <remarks>Computes the 24 byte ANSI password hash given the 8 byte server challenge.
/// Computes the 24 byte ANSI password hash given the 8 byte server challenge.
/// </remarks> /// </remarks>
public byte[] GetAnsiHash(byte[] challenge) public byte[] GetAnsiHash(byte[] challenge)
{ {
@ -568,11 +532,7 @@ namespace SharpCifs.Smb
ClientChallenge = new byte[8]; ClientChallenge = new byte[8];
Random.NextBytes(ClientChallenge); Random.NextBytes(ClientChallenge);
} }
return GetLMv2Response(Domain, return GetLMv2Response(Domain, Username, Password, challenge, ClientChallenge);
Username,
Password,
challenge,
ClientChallenge);
} }
default: default:
@ -582,11 +542,9 @@ namespace SharpCifs.Smb
} }
} }
/// <summary> /// <summary>Computes the 24 byte Unicode password hash given the 8 byte server challenge.
/// Computes the 24 byte Unicode password hash given the 8 byte server challenge.
/// </summary> /// </summary>
/// <remarks> /// <remarks>Computes the 24 byte Unicode password hash given the 8 byte server challenge.
/// Computes the 24 byte Unicode password hash given the 8 byte server challenge.
/// </remarks> /// </remarks>
public byte[] GetUnicodeHash(byte[] challenge) public byte[] GetUnicodeHash(byte[] challenge)
{ {
@ -636,10 +594,8 @@ namespace SharpCifs.Smb
case 4: case 4:
case 5: case 5:
{ {
throw new SmbException( throw new SmbException("NTLMv2 requires extended security (jcifs.smb.client.useExtendedSecurity must be true if jcifs.smb.lmCompatibility >= 3)"
"NTLMv2 requires extended security " );
+ "(jcifs.smb.client.useExtendedSecurity must be true "
+ "if jcifs.smb.lmCompatibility >= 3)");
} }
} }
return null; return null;
@ -694,7 +650,8 @@ namespace SharpCifs.Smb
try try
{ {
Md4 md4 = new Md4(); Md4 md4 = new Md4();
md4.Update(Runtime.GetBytesForString(Password, SmbConstants.UniEncoding)); md4.Update(Runtime.GetBytesForString(Password, SmbConstants.UniEncoding)
);
switch (LmCompatibility) switch (LmCompatibility)
{ {
case 0: case 0:
@ -716,10 +673,10 @@ namespace SharpCifs.Smb
Random.NextBytes(ClientChallenge); Random.NextBytes(ClientChallenge);
} }
Hmact64 hmac = new Hmact64(md4.Digest()); Hmact64 hmac = new Hmact64(md4.Digest());
hmac.Update(Runtime.GetBytesForString(Username.ToUpper(), hmac.Update(Runtime.GetBytesForString(Username.ToUpper(), SmbConstants.UniEncoding
SmbConstants.UniEncoding)); ));
hmac.Update(Runtime.GetBytesForString(Domain.ToUpper(), hmac.Update(Runtime.GetBytesForString(Domain.ToUpper(), SmbConstants.UniEncoding
SmbConstants.UniEncoding)); ));
byte[] ntlmv2Hash = hmac.Digest(); byte[] ntlmv2Hash = hmac.Digest();
hmac = new Hmact64(ntlmv2Hash); hmac = new Hmact64(ntlmv2Hash);
hmac.Update(challenge); hmac.Update(challenge);
@ -757,15 +714,16 @@ namespace SharpCifs.Smb
{ {
if (obj is NtlmPasswordAuthentication) if (obj is NtlmPasswordAuthentication)
{ {
NtlmPasswordAuthentication ntlm = (NtlmPasswordAuthentication)obj; NtlmPasswordAuthentication ntlm = (NtlmPasswordAuthentication
if (ntlm.Domain.ToUpper().Equals(Domain.ToUpper()) )obj;
&& ntlm.Username.ToUpper().Equals(Username.ToUpper())) if (ntlm.Domain.ToUpper().Equals(Domain.ToUpper()) && ntlm.Username.ToUpper().Equals
(Username.ToUpper()))
{ {
if (HashesExternal && ntlm.HashesExternal) if (HashesExternal && ntlm.HashesExternal)
{ {
return Arrays.Equals(AnsiHash, ntlm.AnsiHash) return Arrays.Equals(AnsiHash, ntlm.AnsiHash) && Arrays.Equals(UnicodeHash, ntlm.
&& Arrays.Equals(UnicodeHash, ntlm.UnicodeHash); UnicodeHash);
} }
if (!HashesExternal && Password.Equals(ntlm.Password)) if (!HashesExternal && Password.Equals(ntlm.Password))
{ {
@ -834,12 +792,8 @@ namespace SharpCifs.Smb
case 1: case 1:
{ {
b[0] = unchecked( b[0] = unchecked((byte)(Convert.ToInt32(Runtime.Substring(str, i,
(byte)( i + 2), 16) & unchecked(0xFF)));
Convert.ToInt32(Runtime.Substring(str, i, i + 2), 16)
& unchecked(0xFF)
)
);
@out[j++] = (Runtime.GetStringForBytes(b, 0, 1, "ASCII"))[0]; @out[j++] = (Runtime.GetStringForBytes(b, 0, 1, "ASCII"))[0];
i++; i++;
state = 0; state = 0;

View File

@ -67,11 +67,8 @@ namespace SharpCifs.Smb
public const int SidTypeUnknown = Lsarpc.SidNameUnknown; public const int SidTypeUnknown = Lsarpc.SidNameUnknown;
internal static readonly string[] SidTypeNames = internal static readonly string[] SidTypeNames = { "0", "User", "Domain group"
{ , "Domain", "Local group", "Builtin group", "Deleted", "Invalid", "Unknown" };
"0", "User", "Domain group", "Domain", "Local group",
"Builtin group", "Deleted", "Invalid", "Unknown"
};
public const int SidFlagResolveSids = unchecked(0x0001); public const int SidFlagResolveSids = unchecked(0x0001);
@ -97,9 +94,8 @@ namespace SharpCifs.Smb
internal static Hashtable SidCache = new Hashtable(); internal static Hashtable SidCache = new Hashtable();
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal static void ResolveSids(DcerpcHandle handle, internal static void ResolveSids(DcerpcHandle handle, LsaPolicyHandle policyHandle
LsaPolicyHandle policyHandle, , Sid[] sids)
Sid[] sids)
{ {
MsrpcLookupSids rpc = new MsrpcLookupSids(policyHandle, sids); MsrpcLookupSids rpc = new MsrpcLookupSids(policyHandle, sids);
handle.Sendrecv(rpc); handle.Sendrecv(rpc);
@ -136,16 +132,16 @@ namespace SharpCifs.Smb
break; break;
} }
} }
sids[si].AcctName = (new UnicodeString(rpc.Names.Names[si].Name, false)).ToString(); sids[si].AcctName = (new UnicodeString(rpc.Names.Names[si].Name, false)).ToString
();
sids[si].OriginServer = null; sids[si].OriginServer = null;
sids[si].OriginAuth = null; sids[si].OriginAuth = null;
} }
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal static void ResolveSids0(string authorityServerName, internal static void ResolveSids0(string authorityServerName, NtlmPasswordAuthentication
NtlmPasswordAuthentication auth, auth, Sid[] sids)
Sid[] sids)
{ {
DcerpcHandle handle = null; DcerpcHandle handle = null;
LsaPolicyHandle policyHandle = null; LsaPolicyHandle policyHandle = null;
@ -153,8 +149,8 @@ namespace SharpCifs.Smb
{ {
try try
{ {
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\lsarpc]"
+ "[\\PIPE\\lsarpc]", auth); , auth);
string server = authorityServerName; string server = authorityServerName;
int dot = server.IndexOf('.'); int dot = server.IndexOf('.');
if (dot > 0 && char.IsDigit(server[0]) == false) if (dot > 0 && char.IsDigit(server[0]) == false)
@ -179,11 +175,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public static void ResolveSids(string authorityServerName, public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication
NtlmPasswordAuthentication auth, auth, Sid[] sids, int offset, int length)
Sid[] sids,
int offset,
int length)
{ {
List<object> list = new List<object>();//new List<object>(sids.Length); List<object> list = new List<object>();//new List<object>(sids.Length);
int si; int si;
@ -219,25 +212,21 @@ namespace SharpCifs.Smb
/// <summary>Resolve an array of SIDs using a cache and at most one MSRPC request.</summary> /// <summary>Resolve an array of SIDs using a cache and at most one MSRPC request.</summary>
/// <remarks> /// <remarks>
/// Resolve an array of SIDs using a cache and at most one MSRPC request. /// Resolve an array of SIDs using a cache and at most one MSRPC request.
/// /// <p>
/// This method will attempt /// This method will attempt
/// to resolve SIDs using a cache and cache the results of any SIDs that /// to resolve SIDs using a cache and cache the results of any SIDs that
/// required resolving with the authority. SID cache entries are currently not /// required resolving with the authority. SID cache entries are currently not
/// expired because under normal circumstances SID information never changes. /// expired because under normal circumstances SID information never changes.
/// </remarks> /// </remarks>
/// <param name="authorityServerName"> /// <param name="authorityServerName">The hostname of the server that should be queried. For maximum efficiency this should be the hostname of a domain controller however a member server will work as well and a domain controller may not return names for SIDs corresponding to local accounts for which the domain controller is not an authority.
/// The hostname of the server that should be queried. For maximum efficiency this should be the hostname of a domain controller however a member server will work as well and a domain controller may not return names for SIDs corresponding to local accounts for which the domain controller is not an authority.
/// </param> /// </param>
/// <param name="auth"> /// <param name="auth">The credentials that should be used to communicate with the named server. As usual, <tt>null</tt> indicates that default credentials should be used.
/// The credentials that should be used to communicate with the named server. As usual, <tt>null</tt> indicates that default credentials should be used.
/// </param> /// </param>
/// <param name="sids"> /// <param name="sids">The SIDs that should be resolved. After this function is called, the names associated with the SIDs may be queried with the <tt>toDisplayString</tt>, <tt>getDomainName</tt>, and <tt>getAccountName</tt> methods.
/// The SIDs that should be resolved. After this function is called, the names associated with the SIDs may be queried with the <tt>toDisplayString</tt>, <tt>getDomainName</tt>, and <tt>getAccountName</tt> methods.
/// </param> /// </param>
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public static void ResolveSids(string authorityServerName, public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication
NtlmPasswordAuthentication auth, auth, Sid[] sids)
Sid[] sids)
{ {
List<object> list = new List<object>();//new List<object>(sids.Length); List<object> list = new List<object>();//new List<object>(sids.Length);
int si; int si;
@ -271,8 +260,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public static Sid GetServerSid(string server, public static Sid GetServerSid(string server, NtlmPasswordAuthentication
NtlmPasswordAuthentication auth) auth)
{ {
DcerpcHandle handle = null; DcerpcHandle handle = null;
LsaPolicyHandle policyHandle = null; LsaPolicyHandle policyHandle = null;
@ -285,19 +274,15 @@ namespace SharpCifs.Smb
handle = DcerpcHandle.GetHandle("ncacn_np:" + server + "[\\PIPE\\lsarpc]", auth); handle = DcerpcHandle.GetHandle("ncacn_np:" + server + "[\\PIPE\\lsarpc]", auth);
// NetApp doesn't like the 'generic' access mask values // NetApp doesn't like the 'generic' access mask values
policyHandle = new LsaPolicyHandle(handle, null, unchecked(0x00000001)); policyHandle = new LsaPolicyHandle(handle, null, unchecked(0x00000001));
rpc = new MsrpcQueryInformationPolicy(policyHandle, rpc = new MsrpcQueryInformationPolicy(policyHandle, Lsarpc.PolicyInfoAccountDomain
Lsarpc.PolicyInfoAccountDomain, , info);
info);
handle.Sendrecv(rpc); handle.Sendrecv(rpc);
if (rpc.Retval != 0) if (rpc.Retval != 0)
{ {
throw new SmbException(rpc.Retval, false); throw new SmbException(rpc.Retval, false);
} }
return new Sid(info.Sid, return new Sid(info.Sid, SidTypeDomain, (new UnicodeString
SidTypeDomain, (info.Name, false)).ToString(), null, false);
(new UnicodeString(info.Name, false)).ToString(),
null,
false);
} }
finally finally
{ {
@ -428,11 +413,8 @@ namespace SharpCifs.Smb
SubAuthority[i] = rid; SubAuthority[i] = rid;
} }
public Sid(Rpc.SidT sid, public Sid(Rpc.SidT sid, int type, string domainName, string acctName, bool decrementAuthority
int type, )
string domainName,
string acctName,
bool decrementAuthority)
{ {
Revision = sid.Revision; Revision = sid.Revision;
SubAuthorityCount = sid.SubAuthorityCount; SubAuthorityCount = sid.SubAuthorityCount;
@ -454,11 +436,8 @@ namespace SharpCifs.Smb
public virtual Sid GetDomainSid() public virtual Sid GetDomainSid()
{ {
return new Sid(this, return new Sid(this, SidTypeDomain, DomainName, null, GetType()
SidTypeDomain, != SidTypeDomain);
DomainName,
null,
GetType() != SidTypeDomain);
} }
public virtual int GetRid() public virtual int GetRid()
@ -533,7 +512,8 @@ namespace SharpCifs.Smb
if (Type == SidTypeUnknown) if (Type == SidTypeUnknown)
{ {
string full = ToString(); string full = ToString();
return Runtime.Substring(full, 0, full.Length - GetAccountName().Length - 1); return Runtime.Substring(full, 0, full.Length - GetAccountName().Length -
1);
} }
return DomainName; return DomainName;
} }
@ -617,8 +597,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
string ret = "S-" + (Revision & unchecked(0xFF)) + "-"; string ret = "S-" + (Revision & unchecked(0xFF)) + "-";
if (IdentifierAuthority[0] != unchecked(0) if (IdentifierAuthority[0] != unchecked(0) || IdentifierAuthority[1] != unchecked(
|| IdentifierAuthority[1] != unchecked(0)) 0))
{ {
ret += "0x"; ret += "0x";
ret += Hexdump.ToHexString(IdentifierAuthority, 0, 6); ret += Hexdump.ToHexString(IdentifierAuthority, 0, 6);
@ -709,8 +689,8 @@ namespace SharpCifs.Smb
/// </param> /// </param>
/// <param name="auth">Credentials suitable for accessing the SID's information.</param> /// <param name="auth">Credentials suitable for accessing the SID's information.</param>
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public virtual void Resolve(string authorityServerName, public virtual void Resolve(string authorityServerName, NtlmPasswordAuthentication
NtlmPasswordAuthentication auth) auth)
{ {
Sid[] sids = new Sid[1]; Sid[] sids = new Sid[1];
sids[0] = this; sids[0] = this;
@ -737,11 +717,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal static Sid[] GetGroupMemberSids0(DcerpcHandle handle, internal static Sid[] GetGroupMemberSids0(DcerpcHandle handle, SamrDomainHandle
SamrDomainHandle domainHandle, domainHandle, Sid domsid, int rid, int flags)
Sid domsid,
int rid,
int flags)
{ {
SamrAliasHandle aliasHandle = null; SamrAliasHandle aliasHandle = null;
Lsarpc.LsarSidArray sidarray = new Lsarpc.LsarSidArray(); Lsarpc.LsarSidArray sidarray = new Lsarpc.LsarSidArray();
@ -757,8 +734,8 @@ namespace SharpCifs.Smb
} }
Sid[] sids = new Sid[rpc.Sids.NumSids]; Sid[] sids = new Sid[rpc.Sids.NumSids];
string originServer = handle.GetServer(); string originServer = handle.GetServer();
NtlmPasswordAuthentication originAuth NtlmPasswordAuthentication originAuth = (NtlmPasswordAuthentication)handle.GetPrincipal
= (NtlmPasswordAuthentication)handle.GetPrincipal(); ();
for (int i = 0; i < sids.Length; i++) for (int i = 0; i < sids.Length; i++)
{ {
sids[i] = new Sid(rpc.Sids.Sids[i].Sid, 0, null, null, false); sids[i] = new Sid(rpc.Sids.Sids[i].Sid, 0, null, null, false);
@ -781,9 +758,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public virtual Sid[] GetGroupMemberSids(string authorityServerName, public virtual Sid[] GetGroupMemberSids(string authorityServerName, NtlmPasswordAuthentication
NtlmPasswordAuthentication auth, auth, int flags)
int flags)
{ {
if (Type != SidTypeDomGrp && Type != SidTypeAlias) if (Type != SidTypeDomGrp && Type != SidTypeAlias)
{ {
@ -797,19 +773,11 @@ namespace SharpCifs.Smb
{ {
try try
{ {
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]"
+ "[\\PIPE\\samr]", auth); , auth);
policyHandle = new SamrPolicyHandle(handle, policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x00000030));
authorityServerName, domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x00000200), domsid);
unchecked(0x00000030)); return GetGroupMemberSids0(handle, domainHandle, domsid, GetRid(),
domainHandle = new SamrDomainHandle(handle,
policyHandle,
unchecked(0x00000200),
domsid);
return GetGroupMemberSids0(handle,
domainHandle,
domsid,
GetRid(),
flags); flags);
} }
finally finally
@ -874,18 +842,12 @@ namespace SharpCifs.Smb
{ {
try try
{ {
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]"
+ "[\\PIPE\\samr]", auth); , auth);
policyHandle = new SamrPolicyHandle(handle, policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x02000000));
authorityServerName, domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x02000000), domsid);
unchecked(0x02000000)); rpc = new MsrpcEnumerateAliasesInDomain(domainHandle, unchecked(0xFFFF), sam
domainHandle = new SamrDomainHandle(handle, );
policyHandle,
unchecked(0x02000000),
domsid);
rpc = new MsrpcEnumerateAliasesInDomain(domainHandle,
unchecked(0xFFFF),
sam);
handle.Sendrecv(rpc); handle.Sendrecv(rpc);
if (rpc.Retval != 0) if (rpc.Retval != 0)
{ {
@ -895,11 +857,8 @@ namespace SharpCifs.Smb
for (int ei = 0; ei < rpc.Sam.Count; ei++) for (int ei = 0; ei < rpc.Sam.Count; ei++)
{ {
Samr.SamrSamEntry entry = rpc.Sam.Entries[ei]; Samr.SamrSamEntry entry = rpc.Sam.Entries[ei];
Sid[] mems = GetGroupMemberSids0(handle, Sid[] mems = GetGroupMemberSids0(handle, domainHandle, domsid
domainHandle, , entry.Idx, flags);
domsid,
entry.Idx,
flags);
Sid groupSid = new Sid(domsid, entry.Idx); Sid groupSid = new Sid(domsid, entry.Idx);
groupSid.Type = SidTypeAlias; groupSid.Type = SidTypeAlias;
groupSid.DomainName = domsid.GetDomainName(); groupSid.DomainName = domsid.GetDomainName();

View File

@ -27,14 +27,9 @@ namespace SharpCifs.Smb
internal static long Ticks1601 = new DateTime(1601, 1, 1).Ticks; internal static long Ticks1601 = new DateTime(1601, 1, 1).Ticks;
internal static readonly byte[] Header = internal static readonly byte[] Header = { 0xFF, (byte)('S'), (byte)('M'),
{ (byte)('B'), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, (byte)('S'), (byte)('M'), (byte)('B'), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
internal static void WriteInt2(long val, byte[] dst, int dstIndex) internal static void WriteInt2(long val, byte[] dst, int dstIndex)
{ {
@ -52,22 +47,19 @@ namespace SharpCifs.Smb
internal static int ReadInt2(byte[] src, int srcIndex) internal static int ReadInt2(byte[] src, int srcIndex)
{ {
return unchecked(src[srcIndex] & 0xFF) return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8);
+ ((src[srcIndex + 1] & 0xFF) << 8);
} }
internal static int ReadInt4(byte[] src, int srcIndex) internal static int ReadInt4(byte[] src, int srcIndex)
{ {
return unchecked(src[srcIndex] & 0xFF) return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8) + ((src[srcIndex + 2]
+ ((src[srcIndex + 1] & 0xFF) << 8) & 0xFF) << 16) + ((src[srcIndex + 3] & 0xFF) << 24);
+ ((src[srcIndex + 2] & 0xFF) << 16)
+ ((src[srcIndex + 3] & 0xFF) << 24);
} }
internal static long ReadInt8(byte[] src, int srcIndex) internal static long ReadInt8(byte[] src, int srcIndex)
{ {
return unchecked(ReadInt4(src, srcIndex) & unchecked(0xFFFFFFFFL)) return unchecked(ReadInt4(src, srcIndex) & unchecked(0xFFFFFFFFL)) + unchecked((long)(ReadInt4
+ unchecked((long)(ReadInt4(src, srcIndex + 4)) << 32); (src, srcIndex + 4)) << 32);
} }
internal static void WriteInt8(long val, byte[] dst, int dstIndex) internal static void WriteInt8(long val, byte[] dst, int dstIndex)
@ -214,20 +206,16 @@ namespace SharpCifs.Smb
public ServerMessageBlock() public ServerMessageBlock()
{ {
Flags = unchecked( Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized
(byte)(SmbConstants.FlagsPathNamesCaseless ));
| SmbConstants.FlagsPathNamesCanonicalized)
);
Pid = SmbConstants.Pid; Pid = SmbConstants.Pid;
BatchLevel = 0; BatchLevel = 0;
} }
internal virtual void Reset() internal virtual void Reset()
{ {
Flags = unchecked( Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized
(byte)(SmbConstants.FlagsPathNamesCaseless ));
| SmbConstants.FlagsPathNamesCanonicalized)
);
Flags2 = 0; Flags2 = 0;
ErrorCode = 0; ErrorCode = 0;
Received = false; Received = false;
@ -239,7 +227,8 @@ namespace SharpCifs.Smb
return WriteString(str, dst, dstIndex, UseUnicode); return WriteString(str, dst, dstIndex, UseUnicode);
} }
internal virtual int WriteString(string str, byte[] dst, int dstIndex, bool useUnicode) internal virtual int WriteString(string str, byte[] dst, int dstIndex, bool useUnicode
)
{ {
int start = dstIndex; int start = dstIndex;
try try
@ -251,8 +240,8 @@ namespace SharpCifs.Smb
{ {
dst[dstIndex++] = (byte)('\0'); dst[dstIndex++] = (byte)('\0');
} }
Array.Copy(Runtime.GetBytesForString(str, SmbConstants.UniEncoding), Array.Copy(Runtime.GetBytesForString(str, SmbConstants.UniEncoding), 0, dst, dstIndex
0, dst, dstIndex, str.Length * 2); , str.Length * 2);
dstIndex += str.Length * 2; dstIndex += str.Length * 2;
dst[dstIndex++] = (byte)('\0'); dst[dstIndex++] = (byte)('\0');
dst[dstIndex++] = (byte)('\0'); dst[dstIndex++] = (byte)('\0');
@ -280,7 +269,8 @@ namespace SharpCifs.Smb
return ReadString(src, srcIndex, 256, UseUnicode); return ReadString(src, srcIndex, 256, UseUnicode);
} }
internal virtual string ReadString(byte[] src, int srcIndex, int maxLen, bool useUnicode) internal virtual string ReadString(byte[] src, int srcIndex, int maxLen, bool useUnicode
)
{ {
int len = 0; int len = 0;
string str = null; string str = null;
@ -301,12 +291,8 @@ namespace SharpCifs.Smb
{ {
if (Log.Level > 0) if (Log.Level > 0)
{ {
Hexdump.ToHexdump(Console.Error, Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
src, 128);
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
} }
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
@ -322,12 +308,8 @@ namespace SharpCifs.Smb
{ {
if (Log.Level > 0) if (Log.Level > 0)
{ {
Hexdump.ToHexdump(Console.Error, Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
src, 128);
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
} }
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
@ -345,11 +327,8 @@ namespace SharpCifs.Smb
return str; return str;
} }
internal virtual string ReadString(byte[] src, internal virtual string ReadString(byte[] src, int srcIndex, int srcEnd, int maxLen
int srcIndex, , bool useUnicode)
int srcEnd,
int maxLen,
bool useUnicode)
{ {
int len = 0; int len = 0;
string str = null; string str = null;
@ -364,7 +343,8 @@ namespace SharpCifs.Smb
} }
for (len = 0; (srcIndex + len + 1) < srcEnd; len += 2) for (len = 0; (srcIndex + len + 1) < srcEnd; len += 2)
{ {
if (src[srcIndex + len] == 0x00 && src[srcIndex + len + 1] == 0x00) if (src[srcIndex + len] == 0x00 && src[srcIndex
+ len + 1] == 0x00)
{ {
break; break;
} }
@ -372,12 +352,8 @@ namespace SharpCifs.Smb
{ {
if (Log.Level > 0) if (Log.Level > 0)
{ {
Hexdump.ToHexdump(Console.Error, Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
src, 128);
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
} }
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
@ -396,12 +372,8 @@ namespace SharpCifs.Smb
{ {
if (Log.Level > 0) if (Log.Level > 0)
{ {
Hexdump.ToHexdump(Console.Error, Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
src, 128);
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
} }
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
@ -475,8 +447,8 @@ namespace SharpCifs.Smb
{ {
if (Log.Level >= 5) if (Log.Level >= 5)
{ {
Log.WriteLine("wordCount * 2=" + (WordCount * 2) Log.WriteLine("wordCount * 2=" + (WordCount * 2) + " but readParameterWordsWireFormat returned "
+ " but readParameterWordsWireFormat returned " + n); + n);
} }
} }
bufferIndex += WordCount * 2; bufferIndex += WordCount * 2;
@ -490,8 +462,8 @@ namespace SharpCifs.Smb
{ {
if (Log.Level >= 5) if (Log.Level >= 5)
{ {
Log.WriteLine("byteCount=" + ByteCount Log.WriteLine("byteCount=" + ByteCount + " but readBytesWireFormat returned " + n
+ " but readBytesWireFormat returned " + n); );
} }
} }
// Don't think we can rely on n being correct here. Must use byteCount. // Don't think we can rely on n being correct here. Must use byteCount.
@ -538,7 +510,8 @@ namespace SharpCifs.Smb
internal abstract int WriteBytesWireFormat(byte[] dst, int dstIndex); internal abstract int WriteBytesWireFormat(byte[] dst, int dstIndex);
internal abstract int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex); internal abstract int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
);
internal abstract int ReadBytesWireFormat(byte[] buffer, int bufferIndex); internal abstract int ReadBytesWireFormat(byte[] buffer, int bufferIndex);
@ -549,7 +522,8 @@ namespace SharpCifs.Smb
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
return obj is ServerMessageBlock && ((ServerMessageBlock)obj).Mid == Mid; return obj is ServerMessageBlock && ((ServerMessageBlock)obj)
.Mid == Mid;
} }
public override string ToString() public override string ToString()
@ -707,21 +681,12 @@ namespace SharpCifs.Smb
break; break;
} }
} }
string str = ErrorCode == 0 string str = ErrorCode == 0 ? "0" : SmbException.GetMessageByCode(ErrorCode);
? "0" return "command=" + c + ",received=" + Received + ",errorCode=" + str
: SmbException.GetMessageByCode(ErrorCode); + ",flags=0x" + Hexdump.ToHexString(Flags & 0xFF, 4) + ",flags2=0x"
return "command=" + c + Hexdump.ToHexString(Flags2, 4) + ",signSeq=" + SignSeq + ",tid=" + Tid + ",pid="
+ ",received=" + Received + Pid + ",uid=" + Uid + ",mid=" + Mid + ",wordCount=" + WordCount + ",byteCount="
+ ",errorCode=" + str + ByteCount;
+ ",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;
} }
} }
} }

View File

@ -85,14 +85,9 @@ namespace SharpCifs.Smb
case 2: case 2:
{ {
_macSigningKey = new byte[40]; _macSigningKey = new byte[40];
auth.GetUserSessionKey(transport.Server.EncryptionKey, auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
_macSigningKey, Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey
0); , 16, 24);
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey),
0,
_macSigningKey,
16,
24);
break; break;
} }
@ -109,11 +104,8 @@ namespace SharpCifs.Smb
{ {
_macSigningKey = new byte[40]; _macSigningKey = new byte[40];
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0); auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey
0, , 16, 24);
_macSigningKey,
16,
24);
break; break;
} }
} }
@ -169,11 +161,8 @@ namespace SharpCifs.Smb
/// <param name="data">The data.</param> /// <param name="data">The data.</param>
/// <param name="offset">The starting offset at which the SMB header begins.</param> /// <param name="offset">The starting offset at which the SMB header begins.</param>
/// <param name="length">The length of the SMB data starting at offset.</param> /// <param name="length">The length of the SMB data starting at offset.</param>
internal virtual void Sign(byte[] data, internal virtual void Sign(byte[] data, int offset, int length, ServerMessageBlock
int offset, request, ServerMessageBlock response)
int length,
ServerMessageBlock request,
ServerMessageBlock response)
{ {
request.SignSeq = _signSequence; request.SignSeq = _signSequence;
if (response != null) if (response != null)
@ -195,10 +184,7 @@ namespace SharpCifs.Smb
if (_bypass) if (_bypass)
{ {
_bypass = false; _bypass = false;
Array.Copy(Runtime.GetBytesForString("BSRSPYL "), Array.Copy(Runtime.GetBytesForString("BSRSPYL "), 0, data, index,
0,
data,
index,
8); 8);
} }
} }
@ -223,7 +209,8 @@ namespace SharpCifs.Smb
/// <param name="data">The data.</param> /// <param name="data">The data.</param>
/// <param name="offset">The starting offset at which the SMB header begins.</param> /// <param name="offset">The starting offset at which the SMB header begins.</param>
/// <param name="length">The length of the SMB data starting at offset.</param> /// <param name="length">The length of the SMB data starting at offset.</param>
internal virtual bool Verify(byte[] data, int offset, ServerMessageBlock response) internal virtual bool Verify(byte[] data, int offset, ServerMessageBlock response
)
{ {
Update(_macSigningKey, 0, _macSigningKey.Length); Update(_macSigningKey, 0, _macSigningKey.Length);
int index = offset; int index = offset;
@ -263,10 +250,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "LM_COMPATIBILITY=" + SmbConstants.LmCompatibility return "LM_COMPATIBILITY=" + SmbConstants.LmCompatibility + " MacSigningKey=" + Hexdump.ToHexString
+ " MacSigningKey=" + Hexdump.ToHexString(_macSigningKey, (_macSigningKey, 0, _macSigningKey.Length);
0,
_macSigningKey.Length);
} }
} }
} }

View File

@ -55,10 +55,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComClose[" return "SmbComClose[" + base.ToString() + ",fid=" + _fid + ",lastWriteTime="
+ base.ToString() + _lastWriteTime + "]";
+ ",fid=" + _fid
+ ",lastWriteTime=" + _lastWriteTime + "]";
} }
} }
} }

View File

@ -50,9 +50,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComCreateDirectory[" return "SmbComCreateDirectory[" + base.ToString() + ",directoryName="
+ base.ToString() + Path + "]";
+ ",directoryName=" + Path + "]";
} }
} }
} }

View File

@ -26,9 +26,7 @@ namespace SharpCifs.Smb
{ {
Path = fileName; Path = fileName;
Command = SmbComDelete; Command = SmbComDelete;
_searchAttributes = SmbConstants.AttrHidden _searchAttributes = SmbConstants.AttrHidden | SmbConstants.AttrHidden | SmbConstants.AttrSystem;
| SmbConstants.AttrHidden
| SmbConstants.AttrSystem;
} }
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
@ -45,7 +43,8 @@ namespace SharpCifs.Smb
return dstIndex - start; return dstIndex - start;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -57,10 +56,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComDelete[" return "SmbComDelete[" + base.ToString() + ",searchAttributes=0x" + Hexdump
+ base.ToString() .ToHexString(_searchAttributes, 4) + ",fileName=" + Path + "]";
+ ",searchAttributes=0x" + Hexdump.ToHexString(_searchAttributes, 4)
+ ",fileName=" + Path + "]";
} }
} }
} }

View File

@ -37,7 +37,8 @@ namespace SharpCifs.Smb
return dstIndex - start; return dstIndex - start;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -49,9 +50,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComDeleteDirectory[" return "SmbComDeleteDirectory[" + base.ToString() + ",directoryName="
+ base.ToString() + Path + "]";
+ ",directoryName=" + Path + "]";
} }
} }
} }

View File

@ -37,7 +37,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -49,9 +50,7 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComFindClose2[" return "SmbComFindClose2[" + base.ToString() + ",sid=" + _sid + "]";
+ base.ToString()
+ ",sid=" + _sid + "]";
} }
} }
} }

View File

@ -33,7 +33,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }

View File

@ -66,13 +66,8 @@ namespace SharpCifs.Smb
internal int DesiredAccess; internal int DesiredAccess;
internal SmbComNtCreateAndX(string name, internal SmbComNtCreateAndX(string name, int flags, int access, int shareAccess,
int flags, int extFileAttributes, int createOptions, ServerMessageBlock andx) : base(andx)
int access,
int shareAccess,
int extFileAttributes,
int createOptions,
ServerMessageBlock andx) : base(andx)
{ {
// share access specified in SmbFile // share access specified in SmbFile
// create disposition // create disposition
@ -81,9 +76,7 @@ namespace SharpCifs.Smb
Path = name; Path = name;
Command = SmbComNtCreateAndx; Command = SmbComNtCreateAndx;
DesiredAccess = access; DesiredAccess = access;
DesiredAccess |= SmbConstants.FileReadData DesiredAccess |= SmbConstants.FileReadData | SmbConstants.FileReadEa | SmbConstants.FileReadAttributes;
| SmbConstants.FileReadEa
| SmbConstants.FileReadAttributes;
// extFileAttributes // extFileAttributes
this._extFileAttributes = extFileAttributes; this._extFileAttributes = extFileAttributes;
// shareAccess // shareAccess
@ -174,7 +167,8 @@ namespace SharpCifs.Smb
return n; return n;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -186,19 +180,14 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComNTCreateAndX[" return "SmbComNTCreateAndX[" + base.ToString() + ",flags=0x" + Hexdump
+ base.ToString() .ToHexString(Flags0, 2) + ",rootDirectoryFid=" + _rootDirectoryFid + ",desiredAccess=0x"
+ ",flags=0x" + Hexdump.ToHexString(Flags0, 2) + Hexdump.ToHexString(DesiredAccess, 4) + ",allocationSize=" + _allocationSize +
+ ",rootDirectoryFid=" + _rootDirectoryFid ",extFileAttributes=0x" + Hexdump.ToHexString(_extFileAttributes, 4) + ",shareAccess=0x"
+ ",desiredAccess=0x" + Hexdump.ToHexString(DesiredAccess, 4) + Hexdump.ToHexString(_shareAccess, 4) + ",createDisposition=0x" + Hexdump.ToHexString
+ ",allocationSize=" + _allocationSize (_createDisposition, 4) + ",createOptions=0x" + Hexdump.ToHexString(_createOptions
+ ",extFileAttributes=0x" + Hexdump.ToHexString(_extFileAttributes, 4) , 8) + ",impersonationLevel=0x" + Hexdump.ToHexString(_impersonationLevel, 4) + ",securityFlags=0x"
+ ",shareAccess=0x" + Hexdump.ToHexString(_shareAccess, 4) + Hexdump.ToHexString(_securityFlags, 2) + ",name=" + Path + "]";
+ ",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 + "]";
} }
} }
} }

View File

@ -65,7 +65,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
int start = bufferIndex; int start = bufferIndex;
OplockLevel = buffer[bufferIndex++]; OplockLevel = buffer[bufferIndex++];
@ -102,20 +103,13 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComNTCreateAndXResponse[" return "SmbComNTCreateAndXResponse[" + base.ToString() + ",oplockLevel="
+ base.ToString() + OplockLevel + ",fid=" + Fid + ",createAction=0x" + Hexdump.ToHexString(CreateAction
+ ",oplockLevel=" + OplockLevel , 4) + ",creationTime=" + Extensions.CreateDate(CreationTime) + ",lastAccessTime="
+ ",fid=" + Fid + Extensions.CreateDate(LastAccessTime) + ",lastWriteTime=" + Extensions.CreateDate
+ ",createAction=0x" + Hexdump.ToHexString(CreateAction, 4) (LastWriteTime) + ",changeTime=" + Extensions.CreateDate(ChangeTime) + ",extFileAttributes=0x"
+ ",creationTime=" + Extensions.CreateDate(CreationTime) + Hexdump.ToHexString(ExtFileAttributes, 4) + ",allocationSize=" + AllocationSize
+ ",lastAccessTime=" + Extensions.CreateDate(LastAccessTime) + ",endOfFile=" + EndOfFile + ",fileType=" + FileType + ",deviceState=" + DeviceState
+ ",lastWriteTime=" + Extensions.CreateDate(LastWriteTime)
+ ",changeTime=" + Extensions.CreateDate(ChangeTime)
+ ",extFileAttributes=0x" + Hexdump.ToHexString(ExtFileAttributes, 4)
+ ",allocationSize=" + AllocationSize
+ ",endOfFile=" + EndOfFile
+ ",fileType=" + FileType
+ ",deviceState=" + DeviceState
+ ",directory=" + Directory + "]"; + ",directory=" + Directory + "]";
} }
} }

View File

@ -50,7 +50,8 @@ namespace SharpCifs.Smb
return dialects.Length; return dialects.Length;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -62,9 +63,7 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComNegotiate[" return "SmbComNegotiate[" + base.ToString() + ",wordCount=" + WordCount
+ base.ToString()
+ ",wordCount=" + WordCount
+ ",dialects=NT LM 0.12]"; + ",dialects=NT LM 0.12]";
} }
} }

View File

@ -41,7 +41,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
int start = bufferIndex; int start = bufferIndex;
DialectIndex = ReadInt2(buffer, bufferIndex); DialectIndex = ReadInt2(buffer, bufferIndex);
@ -52,12 +53,12 @@ namespace SharpCifs.Smb
} }
Server.SecurityMode = buffer[bufferIndex++] & unchecked(0xFF); Server.SecurityMode = buffer[bufferIndex++] & unchecked(0xFF);
Server.Security = Server.SecurityMode & unchecked(0x01); Server.Security = Server.SecurityMode & unchecked(0x01);
Server.EncryptedPasswords Server.EncryptedPasswords = (Server.SecurityMode & unchecked(0x02)) == unchecked(
= (Server.SecurityMode & unchecked(0x02)) == unchecked(0x02); 0x02);
Server.SignaturesEnabled Server.SignaturesEnabled = (Server.SecurityMode & unchecked(0x04)) == unchecked(
= (Server.SecurityMode & unchecked(0x04)) == unchecked(0x04); 0x04);
Server.SignaturesRequired Server.SignaturesRequired = (Server.SecurityMode & unchecked(0x08)) == unchecked(
= (Server.SecurityMode & unchecked(0x08)) == unchecked(0x08); 0x08);
Server.MaxMpxCount = ReadInt2(buffer, bufferIndex); Server.MaxMpxCount = ReadInt2(buffer, bufferIndex);
bufferIndex += 2; bufferIndex += 2;
Server.MaxNumberVcs = ReadInt2(buffer, bufferIndex); Server.MaxNumberVcs = ReadInt2(buffer, bufferIndex);
@ -84,11 +85,8 @@ namespace SharpCifs.Smb
if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == 0) if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == 0)
{ {
Server.EncryptionKey = new byte[Server.EncryptionKeyLength]; Server.EncryptionKey = new byte[Server.EncryptionKeyLength];
Array.Copy(buffer, Array.Copy(buffer, bufferIndex, Server.EncryptionKey, 0, Server.EncryptionKeyLength
bufferIndex, );
Server.EncryptionKey,
0,
Server.EncryptionKeyLength);
bufferIndex += Server.EncryptionKeyLength; bufferIndex += Server.EncryptionKeyLength;
if (ByteCount > Server.EncryptionKeyLength) if (ByteCount > Server.EncryptionKeyLength)
{ {
@ -98,8 +96,8 @@ namespace SharpCifs.Smb
{ {
if ((Flags2 & SmbConstants.Flags2Unicode) == SmbConstants.Flags2Unicode) if ((Flags2 & SmbConstants.Flags2Unicode) == SmbConstants.Flags2Unicode)
{ {
while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)) while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)) || buffer
|| buffer[bufferIndex + len + 1] != unchecked(unchecked(0x00))) [bufferIndex + len + 1] != unchecked(unchecked(0x00)))
{ {
len += 2; len += 2;
if (len > 256) if (len > 256)
@ -107,10 +105,8 @@ namespace SharpCifs.Smb
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
} }
Server.OemDomainName = Runtime.GetStringForBytes(buffer, Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len
bufferIndex, , SmbConstants.UniEncoding);
len,
SmbConstants.UniEncoding);
} }
else else
{ {
@ -122,10 +118,8 @@ namespace SharpCifs.Smb
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
} }
Server.OemDomainName = Runtime.GetStringForBytes(buffer, Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len
bufferIndex, , SmbConstants.OemEncoding);
len,
SmbConstants.OemEncoding);
} }
} }
catch (UnsupportedEncodingException uee) catch (UnsupportedEncodingException uee)
@ -154,26 +148,17 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComNegotiateResponse[" return "SmbComNegotiateResponse[" + base.ToString() + ",wordCount=" +
+ base.ToString() WordCount + ",dialectIndex=" + DialectIndex + ",securityMode=0x" + Hexdump.ToHexString
+ ",wordCount=" + WordCount (Server.SecurityMode, 1) + ",security=" + (Server.Security == SmbConstants.SecurityShare ? "share"
+ ",dialectIndex=" + DialectIndex : "user") + ",encryptedPasswords=" + Server.EncryptedPasswords + ",maxMpxCount="
+ ",securityMode=0x" + Hexdump.ToHexString(Server.SecurityMode, 1) + Server.MaxMpxCount + ",maxNumberVcs=" + Server.MaxNumberVcs + ",maxBufferSize="
+ ",security=" + (Server.Security == SmbConstants.SecurityShare + Server.MaxBufferSize + ",maxRawSize=" + Server.MaxRawSize + ",sessionKey=0x"
? "share" + Hexdump.ToHexString(Server.SessionKey, 8) + ",capabilities=0x" + Hexdump.ToHexString
: "user") (Server.Capabilities, 8) + ",serverTime=" + Extensions.CreateDate(Server
+ ",encryptedPasswords=" + Server.EncryptedPasswords .ServerTime) + ",serverTimeZone=" + Server.ServerTimeZone + ",encryptionKeyLength="
+ ",maxMpxCount=" + Server.MaxMpxCount + Server.EncryptionKeyLength + ",byteCount=" + ByteCount + ",oemDomainName=" +
+ ",maxNumberVcs=" + Server.MaxNumberVcs Server.OemDomainName + "]";
+ ",maxBufferSize=" + Server.MaxBufferSize
+ ",maxRawSize=" + Server.MaxRawSize
+ ",sessionKey=0x" + Hexdump.ToHexString(Server.SessionKey, 8)
+ ",capabilities=0x" + Hexdump.ToHexString(Server.Capabilities, 8)
+ ",serverTime=" + Extensions.CreateDate(Server.ServerTime)
+ ",serverTimeZone=" + Server.ServerTimeZone
+ ",encryptionKeyLength=" + Server.EncryptionKeyLength
+ ",byteCount=" + ByteCount
+ ",oemDomainName=" + Server.OemDomainName + "]";
} }
} }
} }

View File

@ -18,7 +18,8 @@ namespace SharpCifs.Smb
{ {
internal abstract class SmbComNtTransactionResponse : SmbComTransactionResponse internal abstract class SmbComNtTransactionResponse : SmbComTransactionResponse
{ {
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
int start = bufferIndex; int start = bufferIndex;
buffer[bufferIndex++] = unchecked(unchecked(0x00)); buffer[bufferIndex++] = unchecked(unchecked(0x00));

View File

@ -49,8 +49,8 @@ namespace SharpCifs.Smb
private const int OpenFnTrunc = 0x02; private const int OpenFnTrunc = 0x02;
private static readonly int BatchLimit private static readonly int BatchLimit = Config.GetInt("jcifs.smb.client.OpenAndX.ReadAndX"
= Config.GetInt("jcifs.smb.client.OpenAndX.ReadAndX", 1); , 1);
internal int flags; internal int flags;
@ -66,10 +66,8 @@ namespace SharpCifs.Smb
internal int AllocationSize; internal int AllocationSize;
internal SmbComOpenAndX(string fileName, internal SmbComOpenAndX(string fileName, int access, int flags, ServerMessageBlock
int access, andx) : base(andx)
int flags,
ServerMessageBlock andx) : base(andx)
{ {
// flags (not the same as flags constructor argument) // flags (not the same as flags constructor argument)
// Access Mode Encoding for desiredAccess // Access Mode Encoding for desiredAccess
@ -87,9 +85,7 @@ namespace SharpCifs.Smb
DesiredAccess &= ~0x1; DesiredAccess &= ~0x1;
// Win98 doesn't like GENERIC_READ ?! -- get Access Denied. // Win98 doesn't like GENERIC_READ ?! -- get Access Denied.
// searchAttributes // searchAttributes
SearchAttributes = SmbConstants.AttrDirectory SearchAttributes = SmbConstants.AttrDirectory | SmbConstants.AttrHidden | SmbConstants.AttrSystem;
| SmbConstants.AttrHidden
| SmbConstants.AttrSystem;
// fileAttributes // fileAttributes
FileAttributes = 0; FileAttributes = 0;
// openFunction // openFunction
@ -170,7 +166,8 @@ namespace SharpCifs.Smb
return dstIndex - start; return dstIndex - start;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -182,16 +179,12 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComOpenAndX[" return "SmbComOpenAndX[" + base.ToString() + ",flags=0x" + Hexdump.ToHexString
+ base.ToString() (flags, 2) + ",desiredAccess=0x" + Hexdump.ToHexString(DesiredAccess, 4) + ",searchAttributes=0x"
+ ",flags=0x" + Hexdump.ToHexString(flags, 2) + Hexdump.ToHexString(SearchAttributes, 4) + ",fileAttributes=0x" + Hexdump.ToHexString
+ ",desiredAccess=0x" + Hexdump.ToHexString(DesiredAccess, 4) (FileAttributes, 4) + ",creationTime=" + Extensions.CreateDate(CreationTime
+ ",searchAttributes=0x" + Hexdump.ToHexString(SearchAttributes, 4) ) + ",openFunction=0x" + Hexdump.ToHexString(OpenFunction, 2) + ",allocationSize="
+ ",fileAttributes=0x" + Hexdump.ToHexString(FileAttributes, 4) + AllocationSize + ",fileName=" + Path + "]";
+ ",creationTime=" + Extensions.CreateDate(CreationTime)
+ ",openFunction=0x" + Hexdump.ToHexString(OpenFunction, 2)
+ ",allocationSize=" + AllocationSize
+ ",fileName=" + Path + "]";
} }
} }
} }

View File

@ -46,7 +46,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
int start = bufferIndex; int start = bufferIndex;
Fid = ReadInt2(buffer, bufferIndex); Fid = ReadInt2(buffer, bufferIndex);
@ -77,17 +78,10 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComOpenAndXResponse[" return "SmbComOpenAndXResponse[" + base.ToString() + ",fid=" + Fid + ",fileAttributes="
+ base.ToString() + FileAttributes + ",lastWriteTime=" + LastWriteTime + ",dataSize=" + DataSize
+ ",fid=" + Fid + ",grantedAccess=" + GrantedAccess + ",fileType=" + FileType + ",deviceState="
+ ",fileAttributes=" + FileAttributes + DeviceState + ",action=" + Action + ",serverFid=" + ServerFid + "]";
+ ",lastWriteTime=" + LastWriteTime
+ ",dataSize=" + DataSize
+ ",grantedAccess=" + GrantedAccess
+ ",fileType=" + FileType
+ ",deviceState=" + DeviceState
+ ",action=" + Action
+ ",serverFid=" + ServerFid + "]";
} }
} }
} }

View File

@ -37,7 +37,8 @@ namespace SharpCifs.Smb
return dstIndex - start; return dstIndex - start;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -49,9 +50,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComQueryInformation[" return "SmbComQueryInformation[" + base.ToString() + ",filename=" + Path
+ base.ToString() + "]";
+ ",filename=" + Path + "]";
} }
} }
} }

View File

@ -65,7 +65,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
if (WordCount == 0) if (WordCount == 0)
{ {
@ -86,11 +87,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComQueryInformationResponse[" return "SmbComQueryInformationResponse[" + base.ToString() + ",fileAttributes=0x"
+ base.ToString() + Hexdump.ToHexString(_fileAttributes, 4) + ",lastWriteTime=" + Extensions.CreateDate
+ ",fileAttributes=0x" + Hexdump.ToHexString(_fileAttributes, 4) (_lastWriteTime) + ",fileSize=" + _fileSize + "]";
+ ",lastWriteTime=" + Extensions.CreateDate(_lastWriteTime)
+ ",fileSize=" + _fileSize + "]";
} }
} }
} }

View File

@ -18,8 +18,8 @@ namespace SharpCifs.Smb
{ {
internal class SmbComReadAndX : AndXServerMessageBlock internal class SmbComReadAndX : AndXServerMessageBlock
{ {
private static readonly int BatchLimit private static readonly int BatchLimit = Config.GetInt("jcifs.smb.client.ReadAndX.Close"
= Config.GetInt("jcifs.smb.client.ReadAndX.Close", 1); , 1);
private long _offset; private long _offset;
@ -39,10 +39,8 @@ namespace SharpCifs.Smb
_openTimeout = unchecked((int)(0xFFFFFFFF)); _openTimeout = unchecked((int)(0xFFFFFFFF));
} }
internal SmbComReadAndX(int fid, internal SmbComReadAndX(int fid, long offset, int maxCount, ServerMessageBlock andx
long offset, ) : base(andx)
int maxCount,
ServerMessageBlock andx) : base(andx)
{ {
this._fid = fid; this._fid = fid;
this._offset = offset; this._offset = offset;
@ -88,7 +86,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -100,15 +99,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComReadAndX[" return "SmbComReadAndX[" + base.ToString() + ",fid=" + _fid + ",offset="
+ base.ToString() + _offset + ",maxCount=" + MaxCount + ",minCount=" + MinCount + ",openTimeout="
+ ",fid=" + _fid + _openTimeout + ",remaining=" + Remaining + ",offset=" + _offset + "]";
+ ",offset=" + _offset
+ ",maxCount=" + MaxCount
+ ",minCount=" + MinCount
+ ",openTimeout=" + _openTimeout
+ ",remaining=" + Remaining
+ ",offset=" + _offset + "]";
} }
} }
} }

View File

@ -54,7 +54,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
int start = bufferIndex; int start = bufferIndex;
bufferIndex += 2; bufferIndex += 2;
@ -78,11 +79,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComReadAndXResponse[" return "SmbComReadAndXResponse[" + base.ToString() + ",dataCompactionMode="
+ base.ToString() + DataCompactionMode + ",dataLength=" + DataLength + ",dataOffset=" + DataOffset
+ ",dataCompactionMode=" + DataCompactionMode + "]";
+ ",dataLength=" + DataLength
+ ",dataOffset=" + DataOffset + "]";
} }
} }
} }

View File

@ -31,9 +31,7 @@ namespace SharpCifs.Smb
Command = SmbComRename; Command = SmbComRename;
this._oldFileName = oldFileName; this._oldFileName = oldFileName;
this._newFileName = newFileName; this._newFileName = newFileName;
_searchAttributes = SmbConstants.AttrHidden _searchAttributes = SmbConstants.AttrHidden | SmbConstants.AttrSystem | SmbConstants.AttrDirectory;
| SmbConstants.AttrSystem
| SmbConstants.AttrDirectory;
} }
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
@ -56,7 +54,8 @@ namespace SharpCifs.Smb
return dstIndex - start; return dstIndex - start;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -68,11 +67,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComRename[" return "SmbComRename[" + base.ToString() + ",searchAttributes=0x" + Hexdump
+ base.ToString() .ToHexString(_searchAttributes, 4) + ",oldFileName=" + _oldFileName + ",newFileName="
+ ",searchAttributes=0x" + Hexdump.ToHexString(_searchAttributes, 4) + _newFileName + "]";
+ ",oldFileName=" + _oldFileName
+ ",newFileName=" + _newFileName + "]";
} }
} }
} }

View File

@ -22,11 +22,11 @@ namespace SharpCifs.Smb
{ {
internal class SmbComSessionSetupAndX : AndXServerMessageBlock internal class SmbComSessionSetupAndX : AndXServerMessageBlock
{ {
private static readonly int BatchLimit private static readonly int BatchLimit = Config.GetInt("jcifs.smb.client.SessionSetupAndX.TreeConnectAndX"
= Config.GetInt("jcifs.smb.client.SessionSetupAndX.TreeConnectAndX", 1); , 1);
private static readonly bool DisablePlainTextPasswords private static readonly bool DisablePlainTextPasswords = Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords"
= Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords", true); , true);
private byte[] _lmHash; private byte[] _lmHash;
@ -47,9 +47,8 @@ namespace SharpCifs.Smb
internal object Cred; internal object Cred;
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal SmbComSessionSetupAndX(SmbSession session, internal SmbComSessionSetupAndX(SmbSession session, ServerMessageBlock andx, object
ServerMessageBlock andx, cred) : base(andx)
object cred) : base(andx)
{ {
Command = SmbComSessionSetupAndx; Command = SmbComSessionSetupAndx;
this.Session = session; this.Session = session;
@ -209,7 +208,8 @@ namespace SharpCifs.Smb
return dstIndex - start; return dstIndex - start;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -221,22 +221,12 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
string result = "SmbComSessionSetupAndX[" string result = "SmbComSessionSetupAndX[" + base.ToString() + ",snd_buf_size="
+ base.ToString() + Session.transport.SndBufSize + ",maxMpxCount=" + Session.transport.MaxMpxCount
+ ",snd_buf_size=" + Session.transport.SndBufSize + ",VC_NUMBER=" + SmbConstants.VcNumber + ",sessionKey=" + _sessionKey + ",lmHash.length="
+ ",maxMpxCount=" + Session.transport.MaxMpxCount + (_lmHash == null ? 0 : _lmHash.Length) + ",ntHash.length=" + (_ntHash == null ?
+ ",VC_NUMBER=" + SmbConstants.VcNumber 0 : _ntHash.Length) + ",capabilities=" + _capabilities + ",accountName=" + _accountName
+ ",sessionKey=" + _sessionKey + ",primaryDomain=" + _primaryDomain + ",NATIVE_OS=" + SmbConstants.NativeOs
+ ",lmHash.length=" + (_lmHash == null
? 0
: _lmHash.Length)
+ ",ntHash.length=" + (_ntHash == null
? 0
: _ntHash.Length)
+ ",capabilities=" + _capabilities
+ ",accountName=" + _accountName
+ ",primaryDomain=" + _primaryDomain
+ ",NATIVE_OS=" + SmbConstants.NativeOs
+ ",NATIVE_LANMAN=" + SmbConstants.NativeLanman + "]"; + ",NATIVE_LANMAN=" + SmbConstants.NativeLanman + "]";
return result; return result;
} }

View File

@ -44,12 +44,11 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
int start = bufferIndex; int start = bufferIndex;
IsLoggedInAsGuest = (buffer[bufferIndex] & 0x01) == 0x01 IsLoggedInAsGuest = (buffer[bufferIndex] & 0x01) == 0x01 ? true : false;
? true
: false;
bufferIndex += 2; bufferIndex += 2;
if (ExtendedSecurity) if (ExtendedSecurity)
{ {
@ -70,11 +69,13 @@ namespace SharpCifs.Smb
} }
_nativeOs = ReadString(buffer, bufferIndex); _nativeOs = ReadString(buffer, bufferIndex);
bufferIndex += StringWireLength(_nativeOs, bufferIndex); bufferIndex += StringWireLength(_nativeOs, bufferIndex);
_nativeLanMan = ReadString(buffer, bufferIndex, start + ByteCount, 255, UseUnicode); _nativeLanMan = ReadString(buffer, bufferIndex, start + ByteCount, 255, UseUnicode
);
bufferIndex += StringWireLength(_nativeLanMan, bufferIndex); bufferIndex += StringWireLength(_nativeLanMan, bufferIndex);
if (!ExtendedSecurity) if (!ExtendedSecurity)
{ {
_primaryDomain = ReadString(buffer, bufferIndex, start + ByteCount, 255, UseUnicode); _primaryDomain = ReadString(buffer, bufferIndex, start + ByteCount, 255, UseUnicode
);
bufferIndex += StringWireLength(_primaryDomain, bufferIndex); bufferIndex += StringWireLength(_primaryDomain, bufferIndex);
} }
return bufferIndex - start; return bufferIndex - start;
@ -82,12 +83,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
string result = "SmbComSessionSetupAndXResponse[" string result = "SmbComSessionSetupAndXResponse[" + base.ToString() +
+ base.ToString() ",isLoggedInAsGuest=" + IsLoggedInAsGuest + ",nativeOs=" + _nativeOs + ",nativeLanMan="
+ ",isLoggedInAsGuest=" + IsLoggedInAsGuest + _nativeLanMan + ",primaryDomain=" + _primaryDomain + "]";
+ ",nativeOs=" + _nativeOs
+ ",nativeLanMan=" + _nativeLanMan
+ ",primaryDomain=" + _primaryDomain + "]";
return result; return result;
} }
} }

View File

@ -21,8 +21,8 @@ namespace SharpCifs.Smb
{ {
internal abstract class SmbComTransaction : ServerMessageBlock internal abstract class SmbComTransaction : ServerMessageBlock
{ {
private static readonly int DefaultMaxDataCount private static readonly int DefaultMaxDataCount = Config.GetInt("jcifs.smb.client.transaction_buf_size"
= Config.GetInt("jcifs.smb.client.transaction_buf_size", TransactionBufSize) - 512; , TransactionBufSize) - 512;
private const int PrimarySetupOffset = 61; private const int PrimarySetupOffset = 61;
@ -70,11 +70,14 @@ namespace SharpCifs.Smb
internal const int NetServerEnum3 = unchecked(0x00D7); internal const int NetServerEnum3 = unchecked(0x00D7);
internal const byte TransPeekNamedPipe = unchecked(unchecked(0x23)); internal const byte TransPeekNamedPipe = unchecked(unchecked(0x23
));
internal const byte TransWaitNamedPipe = unchecked(unchecked(0x53)); internal const byte TransWaitNamedPipe = unchecked(unchecked(0x53
));
internal const byte TransCallNamedPipe = unchecked(unchecked(0x54)); internal const byte TransCallNamedPipe = unchecked(unchecked(0x54
));
internal const byte TransTransactNamedPipe = unchecked(unchecked(0x26)); internal const byte TransTransactNamedPipe = unchecked(unchecked(0x26));
@ -208,8 +211,8 @@ namespace SharpCifs.Smb
available -= _pad1; available -= _pad1;
DataCount = Math.Min(TotalDataCount - DataDisplacement, available); DataCount = Math.Min(TotalDataCount - DataDisplacement, available);
} }
if ((ParameterDisplacement + ParameterCount) >= TotalParameterCount if ((ParameterDisplacement + ParameterCount) >= TotalParameterCount && (DataDisplacement
&& (DataDisplacement + DataCount) >= TotalDataCount) + DataCount) >= TotalDataCount)
{ {
_hasMore = false; _hasMore = false;
} }
@ -303,7 +306,8 @@ namespace SharpCifs.Smb
return dstIndex - start; return dstIndex - start;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -319,31 +323,24 @@ namespace SharpCifs.Smb
internal abstract int WriteDataWireFormat(byte[] dst, int dstIndex); internal abstract int WriteDataWireFormat(byte[] dst, int dstIndex);
internal abstract int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len); internal abstract int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
);
internal abstract int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len); internal abstract int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len);
internal abstract int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len); internal abstract int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len);
public override string ToString() public override string ToString()
{ {
return base.ToString() return base.ToString() + ",totalParameterCount=" + TotalParameterCount
+ ",totalParameterCount=" + TotalParameterCount + ",totalDataCount=" + TotalDataCount + ",maxParameterCount=" + MaxParameterCount
+ ",totalDataCount=" + TotalDataCount + ",maxDataCount=" + MaxDataCount + ",maxSetupCount=" + (int)MaxSetupCount + ",flags=0x"
+ ",maxParameterCount=" + MaxParameterCount + Hexdump.ToHexString(_flags, 2) + ",timeout=" + Timeout + ",parameterCount=" +
+ ",maxDataCount=" + MaxDataCount ParameterCount + ",parameterOffset=" + ParameterOffset + ",parameterDisplacement="
+ ",maxSetupCount=" + (int)MaxSetupCount + ParameterDisplacement + ",dataCount=" + DataCount + ",dataOffset=" + DataOffset
+ ",flags=0x" + Hexdump.ToHexString(_flags, 2) + ",dataDisplacement=" + DataDisplacement + ",setupCount=" + SetupCount + ",pad="
+ ",timeout=" + Timeout + _pad + ",pad1=" + _pad1;
+ ",parameterCount=" + ParameterCount
+ ",parameterOffset=" + ParameterOffset
+ ",parameterDisplacement=" + ParameterDisplacement
+ ",dataCount=" + DataCount
+ ",dataOffset=" + DataOffset
+ ",dataDisplacement=" + DataDisplacement
+ ",setupCount=" + SetupCount
+ ",pad=" + _pad
+ ",pad1=" + _pad1;
} }
} }
} }

View File

@ -108,7 +108,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
int start = bufferIndex; int start = bufferIndex;
TotalParameterCount = ReadInt2(buffer, bufferIndex); TotalParameterCount = ReadInt2(buffer, bufferIndex);
@ -151,30 +152,22 @@ namespace SharpCifs.Smb
if (ParameterCount > 0) if (ParameterCount > 0)
{ {
bufferIndex += _pad = ParameterOffset - (bufferIndex - HeaderStart); bufferIndex += _pad = ParameterOffset - (bufferIndex - HeaderStart);
Array.Copy(buffer, Array.Copy(buffer, bufferIndex, TxnBuf, BufParameterStart + ParameterDisplacement
bufferIndex, , ParameterCount);
TxnBuf,
BufParameterStart + ParameterDisplacement,
ParameterCount);
bufferIndex += ParameterCount; bufferIndex += ParameterCount;
} }
if (DataCount > 0) if (DataCount > 0)
{ {
bufferIndex += _pad1 = DataOffset - (bufferIndex - HeaderStart); bufferIndex += _pad1 = DataOffset - (bufferIndex - HeaderStart);
Array.Copy(buffer, Array.Copy(buffer, bufferIndex, TxnBuf, BufDataStart + DataDisplacement,
bufferIndex,
TxnBuf,
BufDataStart + DataDisplacement,
DataCount); DataCount);
bufferIndex += DataCount; bufferIndex += DataCount;
} }
if (!_parametersDone if (!_parametersDone && (ParameterDisplacement + ParameterCount) == TotalParameterCount)
&& (ParameterDisplacement + ParameterCount) == TotalParameterCount)
{ {
_parametersDone = true; _parametersDone = true;
} }
if (!_dataDone if (!_dataDone && (DataDisplacement + DataCount) == TotalDataCount)
&& (DataDisplacement + DataCount) == TotalDataCount)
{ {
_dataDone = true; _dataDone = true;
} }
@ -193,26 +186,21 @@ namespace SharpCifs.Smb
internal abstract int WriteDataWireFormat(byte[] dst, int dstIndex); internal abstract int WriteDataWireFormat(byte[] dst, int dstIndex);
internal abstract int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len); internal abstract int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
);
internal abstract int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len); internal abstract int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len);
internal abstract int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len); internal abstract int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len);
public override string ToString() public override string ToString()
{ {
return base.ToString() return base.ToString() + ",totalParameterCount=" + TotalParameterCount
+ ",totalParameterCount=" + TotalParameterCount + ",totalDataCount=" + TotalDataCount + ",parameterCount=" + ParameterCount + ",parameterOffset="
+ ",totalDataCount=" + TotalDataCount + ParameterOffset + ",parameterDisplacement=" + ParameterDisplacement + ",dataCount="
+ ",parameterCount=" + ParameterCount + DataCount + ",dataOffset=" + DataOffset + ",dataDisplacement=" + DataDisplacement
+ ",parameterOffset=" + ParameterOffset + ",setupCount=" + SetupCount + ",pad=" + _pad + ",pad1=" + _pad1;
+ ",parameterDisplacement=" + ParameterDisplacement
+ ",dataCount=" + DataCount
+ ",dataOffset=" + DataOffset
+ ",dataDisplacement=" + DataDisplacement
+ ",setupCount=" + SetupCount
+ ",pad=" + _pad
+ ",pad1=" + _pad1;
} }
} }
} }

View File

@ -22,8 +22,8 @@ namespace SharpCifs.Smb
{ {
internal class SmbComTreeConnectAndX : AndXServerMessageBlock internal class SmbComTreeConnectAndX : AndXServerMessageBlock
{ {
private static readonly bool DisablePlainTextPasswords private static readonly bool DisablePlainTextPasswords = Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords"
= Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords", true); , true);
private SmbSession _session; private SmbSession _session;
@ -42,11 +42,13 @@ namespace SharpCifs.Smb
static SmbComTreeConnectAndX() static SmbComTreeConnectAndX()
{ {
string s; string s;
if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CheckDirectory")) != null) if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CheckDirectory")) !=
null)
{ {
_batchLimits[0] = byte.Parse(s); _batchLimits[0] = byte.Parse(s);
} }
if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CreateDirectory")) != null) if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CreateDirectory"))
!= null)
{ {
_batchLimits[2] = byte.Parse(s); _batchLimits[2] = byte.Parse(s);
} }
@ -54,7 +56,8 @@ namespace SharpCifs.Smb
{ {
_batchLimits[3] = byte.Parse(s); _batchLimits[3] = byte.Parse(s);
} }
if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.DeleteDirectory")) != null) if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.DeleteDirectory"))
!= null)
{ {
_batchLimits[4] = byte.Parse(s); _batchLimits[4] = byte.Parse(s);
} }
@ -70,16 +73,15 @@ namespace SharpCifs.Smb
{ {
_batchLimits[7] = byte.Parse(s); _batchLimits[7] = byte.Parse(s);
} }
if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.QueryInformation")) != null) if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.QueryInformation"))
!= null)
{ {
_batchLimits[8] = byte.Parse(s); _batchLimits[8] = byte.Parse(s);
} }
} }
internal SmbComTreeConnectAndX(SmbSession session, internal SmbComTreeConnectAndX(SmbSession session, string path, string service, ServerMessageBlock
string path, andx) : base(andx)
string service,
ServerMessageBlock andx) : base(andx)
{ {
this._session = session; this._session = session;
this.path = path; this.path = path;
@ -138,8 +140,8 @@ namespace SharpCifs.Smb
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{ {
if (_session.transport.Server.Security == SmbConstants.SecurityShare if (_session.transport.Server.Security == SmbConstants.SecurityShare && (_session.Auth.HashesExternal
&& (_session.Auth.HashesExternal || _session.Auth.Password.Length > 0)) || _session.Auth.Password.Length > 0))
{ {
if (_session.transport.Server.EncryptedPasswords) if (_session.transport.Server.EncryptedPasswords)
{ {
@ -163,9 +165,8 @@ namespace SharpCifs.Smb
// no password in tree connect // no password in tree connect
_passwordLength = 1; _passwordLength = 1;
} }
dst[dstIndex++] = _disconnectTid dst[dstIndex++] = _disconnectTid ? unchecked((byte)unchecked(0x01)) : unchecked(
? unchecked((byte)unchecked(0x01)) (byte)unchecked(0x00));
: unchecked((byte)unchecked(0x00));
dst[dstIndex++] = unchecked(unchecked(0x00)); dst[dstIndex++] = unchecked(unchecked(0x00));
WriteInt2(_passwordLength, dst, dstIndex); WriteInt2(_passwordLength, dst, dstIndex);
return 4; return 4;
@ -174,14 +175,10 @@ namespace SharpCifs.Smb
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{ {
int start = dstIndex; int start = dstIndex;
if (_session.transport.Server.Security == SmbConstants.SecurityShare if (_session.transport.Server.Security == SmbConstants.SecurityShare && (_session.Auth.HashesExternal
&& (_session.Auth.HashesExternal || _session.Auth.Password.Length > 0)) || _session.Auth.Password.Length > 0))
{ {
Array.Copy(_password, Array.Copy(_password, 0, dst, dstIndex, _passwordLength);
0,
dst,
dstIndex,
_passwordLength);
dstIndex += _passwordLength; dstIndex += _passwordLength;
} }
else else
@ -194,11 +191,8 @@ namespace SharpCifs.Smb
{ {
// Array.Copy(Runtime.GetBytesForString(_service, "ASCII"), 0, dst, dstIndex // Array.Copy(Runtime.GetBytesForString(_service, "ASCII"), 0, dst, dstIndex
//, _service.Length); //, _service.Length);
Array.Copy(Runtime.GetBytesForString(_service, "UTF-8"), Array.Copy(Runtime.GetBytesForString(_service, "UTF-8"), 0, dst, dstIndex
0, , _service.Length);
dst,
dstIndex,
_service.Length);
} }
catch (UnsupportedEncodingException) catch (UnsupportedEncodingException)
{ {
@ -209,7 +203,8 @@ namespace SharpCifs.Smb
return dstIndex - start; return dstIndex - start;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -221,13 +216,10 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
string result = "SmbComTreeConnectAndX[" string result = "SmbComTreeConnectAndX[" + base.ToString() + ",disconnectTid="
+ base.ToString() + _disconnectTid + ",passwordLength=" + _passwordLength + ",password=" + Hexdump.
+ ",disconnectTid=" + _disconnectTid ToHexString(_password, _passwordLength, 0) + ",path=" + path + ",service=" + _service
+ ",passwordLength=" + _passwordLength + "]";
+ ",password=" + Hexdump.ToHexString(_password, _passwordLength, 0)
+ ",path=" + path
+ ",service=" + _service + "]";
return result; return result;
} }
} }

View File

@ -47,7 +47,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
SupportSearchBits = (buffer[bufferIndex] & SmbSupportSearchBits) == SmbSupportSearchBits; SupportSearchBits = (buffer[bufferIndex] & SmbSupportSearchBits) == SmbSupportSearchBits;
ShareIsInDfs = (buffer[bufferIndex] & SmbShareIsInDfs) == SmbShareIsInDfs; ShareIsInDfs = (buffer[bufferIndex] & SmbShareIsInDfs) == SmbShareIsInDfs;
@ -74,12 +75,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
string result = "SmbComTreeConnectAndXResponse[" string result = "SmbComTreeConnectAndXResponse[" + base.ToString() + ",supportSearchBits="
+ base.ToString() + SupportSearchBits + ",shareIsInDfs=" + ShareIsInDfs + ",service=" + Service +
+ ",supportSearchBits=" + SupportSearchBits ",nativeFileSystem=" + NativeFileSystem + "]";
+ ",shareIsInDfs=" + ShareIsInDfs
+ ",service=" + Service
+ ",nativeFileSystem=" + NativeFileSystem + "]";
return result; return result;
} }
} }

View File

@ -33,7 +33,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }

View File

@ -37,7 +37,8 @@ namespace SharpCifs.Smb
Command = SmbComWrite; Command = SmbComWrite;
} }
internal SmbComWrite(int fid, int offset, int remaining, byte[] b, int off, int len) internal SmbComWrite(int fid, int offset, int remaining, byte[] b, int off, int len
)
{ {
this._fid = fid; this._fid = fid;
_count = len; _count = len;
@ -48,12 +49,8 @@ namespace SharpCifs.Smb
Command = SmbComWrite; Command = SmbComWrite;
} }
internal virtual void SetParam(int fid, internal virtual void SetParam(int fid, long offset, int remaining, byte[] b, int
long offset, off, int len)
int remaining,
byte[] b,
int off,
int len)
{ {
this._fid = fid; this._fid = fid;
this._offset = (int)(offset & unchecked(0xFFFFFFFFL)); this._offset = (int)(offset & unchecked(0xFFFFFFFFL));
@ -89,7 +86,8 @@ namespace SharpCifs.Smb
return dstIndex - start; return dstIndex - start;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -101,12 +99,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComWrite[" return "SmbComWrite[" + base.ToString() + ",fid=" + _fid + ",count=" +
+ base.ToString() _count + ",offset=" + _offset + ",remaining=" + _remaining + "]";
+ ",fid=" + _fid
+ ",count=" + _count
+ ",offset=" + _offset
+ ",remaining=" + _remaining + "]";
} }
} }
} }

View File

@ -20,11 +20,11 @@ namespace SharpCifs.Smb
{ {
internal class SmbComWriteAndX : AndXServerMessageBlock internal class SmbComWriteAndX : AndXServerMessageBlock
{ {
private static readonly int ReadAndxBatchLimit private static readonly int ReadAndxBatchLimit = Config.GetInt("jcifs.smb.client.WriteAndX.ReadAndX"
= Config.GetInt("jcifs.smb.client.WriteAndX.ReadAndX", 1); , 1);
private static readonly int CloseBatchLimit private static readonly int CloseBatchLimit = Config.GetInt("jcifs.smb.client.WriteAndX.Close"
= Config.GetInt("jcifs.smb.client.WriteAndX.Close", 1); , 1);
private int _fid; private int _fid;
@ -49,13 +49,8 @@ namespace SharpCifs.Smb
Command = SmbComWriteAndx; Command = SmbComWriteAndx;
} }
internal SmbComWriteAndX(int fid, internal SmbComWriteAndX(int fid, long offset, int remaining, byte[] b, int off,
long offset, int len, ServerMessageBlock andx) : base(andx)
int remaining,
byte[] b,
int off,
int len,
ServerMessageBlock andx) : base(andx)
{ {
this._fid = fid; this._fid = fid;
this._offset = offset; this._offset = offset;
@ -66,12 +61,8 @@ namespace SharpCifs.Smb
Command = SmbComWriteAndx; Command = SmbComWriteAndx;
} }
internal virtual void SetParam(int fid, internal virtual void SetParam(int fid, long offset, int remaining, byte[] b, int
long offset, off, int len)
int remaining,
byte[] b,
int off,
int len)
{ {
this._fid = fid; this._fid = fid;
this._offset = offset; this._offset = offset;
@ -138,7 +129,8 @@ namespace SharpCifs.Smb
return dstIndex - start; return dstIndex - start;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
return 0; return 0;
} }
@ -150,14 +142,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComWriteAndX[" return "SmbComWriteAndX[" + base.ToString() + ",fid=" + _fid + ",offset="
+ base.ToString() + _offset + ",writeMode=" + WriteMode + ",remaining=" + _remaining + ",dataLength="
+ ",fid=" + _fid + _dataLength + ",dataOffset=" + _dataOffset + "]";
+ ",offset=" + _offset
+ ",writeMode=" + WriteMode
+ ",remaining=" + _remaining
+ ",dataLength=" + _dataLength
+ ",dataOffset=" + _dataOffset + "]";
} }
} }
} }

View File

@ -30,7 +30,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
Count = ReadInt2(buffer, bufferIndex) & unchecked(0xFFFFL); Count = ReadInt2(buffer, bufferIndex) & unchecked(0xFFFFL);
return 8; return 8;

View File

@ -30,7 +30,8 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex) internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{ {
Count = ReadInt2(buffer, bufferIndex) & unchecked(0xFFFFL); Count = ReadInt2(buffer, bufferIndex) & unchecked(0xFFFFL);
return 8; return 8;

View File

@ -23,61 +23,6 @@ namespace SharpCifs.Smb
{ {
internal static class SmbConstants internal static class SmbConstants
{ {
internal static void ApplyConfig()
{
SmbConstants.Laddr = Config.GetLocalHost();
SmbConstants.Lport = Config.GetInt("jcifs.smb.client.lport", 0);
SmbConstants.MaxMpxCount = Config.GetInt("jcifs.smb.client.maxMpxCount", SmbConstants.DefaultMaxMpxCount);
SmbConstants.SndBufSize = Config.GetInt("jcifs.smb.client.snd_buf_size", SmbConstants.DefaultSndBufSize);
SmbConstants.RcvBufSize = Config.GetInt("jcifs.smb.client.rcv_buf_size", SmbConstants.DefaultRcvBufSize);
SmbConstants.UseUnicode = Config.GetBoolean("jcifs.smb.client.useUnicode", true);
SmbConstants.ForceUnicode = Config.GetBoolean("jcifs.smb.client.useUnicode", false);
SmbConstants.UseNtstatus = Config.GetBoolean("jcifs.smb.client.useNtStatus", true);
SmbConstants.Signpref = Config.GetBoolean("jcifs.smb.client.signingPreferred", false);
SmbConstants.UseNtsmbs = Config.GetBoolean("jcifs.smb.client.useNTSmbs", true);
SmbConstants.UseExtsec = Config.GetBoolean("jcifs.smb.client.useExtendedSecurity", true);
SmbConstants.NetbiosHostname = Config.GetProperty("jcifs.netbios.hostname", null);
SmbConstants.LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility", 3);
SmbConstants.UseBatching = Config.GetBoolean("jcifs.smb.client.useBatching", true);
SmbConstants.OemEncoding = Config.GetProperty("jcifs.encoding", Config.DefaultOemEncoding);
SmbConstants.DefaultFlags2 =
SmbConstants.Flags2LongFilenames
| SmbConstants.Flags2ExtendedAttributes
| (SmbConstants.UseExtsec
? SmbConstants.Flags2ExtendedSecurityNegotiation
: 0)
| (SmbConstants.Signpref
? SmbConstants.Flags2SecuritySignatures
: 0)
| (SmbConstants.UseNtstatus
? SmbConstants.Flags2Status32
: 0)
| (SmbConstants.UseUnicode
? SmbConstants.Flags2Unicode
: 0);
SmbConstants.DefaultCapabilities =
(SmbConstants.UseNtsmbs
? SmbConstants.CapNtSmbs
: 0)
| (SmbConstants.UseNtstatus
? SmbConstants.CapStatus32
: 0)
| (SmbConstants.UseUnicode
? SmbConstants.CapUnicode
: 0)
| SmbConstants.CapDfs;
SmbConstants.Flags2 = Config.GetInt("jcifs.smb.client.flags2", SmbConstants.DefaultFlags2);
SmbConstants.Capabilities = Config.GetInt("jcifs.smb.client.capabilities", SmbConstants.DefaultCapabilities);
SmbConstants.TcpNodelay = Config.GetBoolean("jcifs.smb.client.tcpNoDelay", false);
SmbConstants.ResponseTimeout = Config.GetInt("jcifs.smb.client.responseTimeout", SmbConstants.DefaultResponseTimeout);
SmbConstants.SsnLimit = Config.GetInt("jcifs.smb.client.ssnLimit", SmbConstants.DefaultSsnLimit);
SmbConstants.SoTimeout = Config.GetInt("jcifs.smb.client.soTimeout", SmbConstants.DefaultSoTimeout);
SmbConstants.ConnTimeout = Config.GetInt("jcifs.smb.client.connTimeout", SmbConstants.DefaultConnTimeout);
SmbConstants.NativeOs = Config.GetProperty("jcifs.smb.client.nativeOs", Runtime.GetProperty("os.name"));
SmbConstants.NativeLanman = Config.GetProperty("jcifs.smb.client.nativeLanMan", "jCIFS");
}
public static readonly int DefaultPort = 445; public static readonly int DefaultPort = 445;
public static readonly int DefaultMaxMpxCount = 10; public static readonly int DefaultMaxMpxCount = 10;
@ -94,44 +39,41 @@ namespace SharpCifs.Smb
public static readonly int DefaultConnTimeout = 35000; public static readonly int DefaultConnTimeout = 35000;
public static IPAddress Laddr { get; internal set; } public static readonly IPAddress Laddr = Config.GetLocalHost();
= Config.GetLocalHost();
public static int Lport { get; internal set; } public static readonly int Lport = Config.GetInt("jcifs.smb.client.lport", 0);
= Config.GetInt("jcifs.smb.client.lport", 0);
public static int MaxMpxCount { get; internal set; } public static readonly int MaxMpxCount = Config.GetInt("jcifs.smb.client.maxMpxCount", DefaultMaxMpxCount
= Config.GetInt("jcifs.smb.client.maxMpxCount", DefaultMaxMpxCount); );
public static int SndBufSize { get; internal set; } public static readonly int SndBufSize = Config.GetInt("jcifs.smb.client.snd_buf_size", DefaultSndBufSize
= Config.GetInt("jcifs.smb.client.snd_buf_size", DefaultSndBufSize); );
public static int RcvBufSize { get; internal set; } public static readonly int RcvBufSize = Config.GetInt("jcifs.smb.client.rcv_buf_size", DefaultRcvBufSize
= Config.GetInt("jcifs.smb.client.rcv_buf_size", DefaultRcvBufSize); );
public static bool UseUnicode { get; internal set; } public static readonly bool UseUnicode = Config.GetBoolean("jcifs.smb.client.useUnicode",
= Config.GetBoolean("jcifs.smb.client.useUnicode", true); true);
public static bool ForceUnicode { get; internal set; } public static readonly bool ForceUnicode = Config.GetBoolean("jcifs.smb.client.useUnicode"
= Config.GetBoolean("jcifs.smb.client.useUnicode", false); , false);
public static bool UseNtstatus { get; internal set; } public static readonly bool UseNtstatus = Config.GetBoolean("jcifs.smb.client.useNtStatus"
= Config.GetBoolean("jcifs.smb.client.useNtStatus", true); , true);
public static bool Signpref { get; internal set; } public static readonly bool Signpref = Config.GetBoolean("jcifs.smb.client.signingPreferred"
= Config.GetBoolean("jcifs.smb.client.signingPreferred", false); , false);
public static bool UseNtsmbs { get; internal set; } public static readonly bool UseNtsmbs = Config.GetBoolean("jcifs.smb.client.useNTSmbs", true
= Config.GetBoolean("jcifs.smb.client.useNTSmbs", true); );
public static bool UseExtsec { get; internal set; } public static readonly bool UseExtsec = Config.GetBoolean("jcifs.smb.client.useExtendedSecurity"
= Config.GetBoolean("jcifs.smb.client.useExtendedSecurity", true); , true);
public static string NetbiosHostname { get; internal set; } public static readonly string NetbiosHostname = Config.GetProperty("jcifs.netbios.hostname"
= Config.GetProperty("jcifs.netbios.hostname", null); , null);
public static int LmCompatibility { get; internal set; } public static readonly int LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility", 3);
= Config.GetInt("jcifs.smb.lmCompatibility", 3);
public static readonly int FlagsNone = unchecked(0x00); public static readonly int FlagsNone = unchecked(0x00);
@ -285,70 +227,50 @@ namespace SharpCifs.Smb
public static readonly TimeZoneInfo Tz = TimeZoneInfo.Local; public static readonly TimeZoneInfo Tz = TimeZoneInfo.Local;
public static bool UseBatching { get; internal set; } public static readonly bool UseBatching = Config.GetBoolean("jcifs.smb.client.useBatching"
= Config.GetBoolean("jcifs.smb.client.useBatching", true); , true);
public static string OemEncoding { get; internal set; } public static readonly string OemEncoding = Config.GetProperty("jcifs.encoding", Config.DefaultOemEncoding
= Config.GetProperty("jcifs.encoding", Config.DefaultOemEncoding); );
public static string UniEncoding = "UTF-16LE"; public static readonly string UniEncoding = "UTF-16LE";
public static int DefaultFlags2 { get; internal set; } public static readonly int DefaultFlags2 = Flags2LongFilenames | Flags2ExtendedAttributes
= Flags2LongFilenames | (UseExtsec ? Flags2ExtendedSecurityNegotiation : 0) | (Signpref ? Flags2SecuritySignatures
| Flags2ExtendedAttributes : 0) | (UseNtstatus ? Flags2Status32 : 0) | (UseUnicode ? Flags2Unicode : 0
| (UseExtsec );
? Flags2ExtendedSecurityNegotiation
: 0)
| (Signpref
? Flags2SecuritySignatures
: 0)
| (UseNtstatus
? Flags2Status32
: 0)
| (UseUnicode
? Flags2Unicode
: 0);
public static int DefaultCapabilities { get; internal set; } public static readonly int DefaultCapabilities = (UseNtsmbs ? CapNtSmbs : 0) | (UseNtstatus
= (UseNtsmbs ? CapStatus32 : 0) | (UseUnicode ? CapUnicode : 0) | CapDfs;
? CapNtSmbs
: 0)
| (UseNtstatus
? CapStatus32
: 0)
| (UseUnicode
? CapUnicode
: 0)
| CapDfs;
public static int Flags2 { get; internal set; } public static readonly int Flags2 = Config.GetInt("jcifs.smb.client.flags2", DefaultFlags2
= Config.GetInt("jcifs.smb.client.flags2", DefaultFlags2); );
public static int Capabilities { get; internal set; } public static readonly int Capabilities = Config.GetInt("jcifs.smb.client.capabilities", DefaultCapabilities
= Config.GetInt("jcifs.smb.client.capabilities", DefaultCapabilities); );
public static bool TcpNodelay { get; internal set; } public static readonly bool TcpNodelay = Config.GetBoolean("jcifs.smb.client.tcpNoDelay",
= Config.GetBoolean("jcifs.smb.client.tcpNoDelay", false); false);
public static int ResponseTimeout { get; internal set; } public static readonly int ResponseTimeout = Config.GetInt("jcifs.smb.client.responseTimeout"
= Config.GetInt("jcifs.smb.client.responseTimeout", DefaultResponseTimeout); , DefaultResponseTimeout);
public static readonly List<SmbTransport> Connections = new List<SmbTransport>(); public static readonly List<SmbTransport> Connections = new List<SmbTransport>();
public static int SsnLimit { get; internal set; } public static readonly int SsnLimit = Config.GetInt("jcifs.smb.client.ssnLimit", DefaultSsnLimit
= Config.GetInt("jcifs.smb.client.ssnLimit", DefaultSsnLimit); );
public static int SoTimeout { get; internal set; } public static readonly int SoTimeout = Config.GetInt("jcifs.smb.client.soTimeout", DefaultSoTimeout
= Config.GetInt("jcifs.smb.client.soTimeout", DefaultSoTimeout); );
public static int ConnTimeout { get; internal set; } public static readonly int ConnTimeout = Config.GetInt("jcifs.smb.client.connTimeout", DefaultConnTimeout
= Config.GetInt("jcifs.smb.client.connTimeout", DefaultConnTimeout); );
public static string NativeOs { get; internal set; } public static readonly string NativeOs = Config.GetProperty("jcifs.smb.client.nativeOs", Runtime
= Config.GetProperty("jcifs.smb.client.nativeOs", Runtime.GetProperty("os.name")); .GetProperty("os.name"));
public static string NativeLanman { get; internal set; } public static readonly string NativeLanman = Config.GetProperty("jcifs.smb.client.nativeLanMan"
= Config.GetProperty("jcifs.smb.client.nativeLanMan", "jCIFS"); , "jCIFS");
public static readonly int VcNumber = 1; public static readonly int VcNumber = 1;

View File

@ -163,8 +163,8 @@ namespace SharpCifs.Smb
{ {
} }
internal SmbException(int errcode, Exception rootCause) internal SmbException(int errcode, Exception rootCause) : base(GetMessageByCode(errcode
: base(GetMessageByCode(errcode)) ))
{ {
_status = GetStatusByCode(errcode); _status = GetStatusByCode(errcode);
this._rootCause = rootCause; this._rootCause = rootCause;
@ -181,14 +181,10 @@ namespace SharpCifs.Smb
_status = NtStatus.NtStatusUnsuccessful; _status = NtStatus.NtStatusUnsuccessful;
} }
public SmbException(int errcode, bool winerr) public SmbException(int errcode, bool winerr) : base(winerr ? GetMessageByWinerrCode
: base(winerr (errcode) : GetMessageByCode(errcode))
? GetMessageByWinerrCode(errcode)
: GetMessageByCode(errcode))
{ {
_status = winerr _status = winerr ? errcode : GetStatusByCode(errcode);
? errcode
: GetStatusByCode(errcode);
} }
public virtual int GetNtStatus() public virtual int GetNtStatus()

View File

@ -24,7 +24,6 @@ using SharpCifs.Dcerpc.Msrpc;
using SharpCifs.Netbios; using SharpCifs.Netbios;
using SharpCifs.Util; using SharpCifs.Util;
using SharpCifs.Util.Sharpen; using SharpCifs.Util.Sharpen;
using System.Threading.Tasks;
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
@ -228,14 +227,6 @@ namespace SharpCifs.Smb
/// <seealso cref="FilePath">Sharpen.FilePath</seealso> /// <seealso cref="FilePath">Sharpen.FilePath</seealso>
public class SmbFile : UrlConnection public class SmbFile : UrlConnection
{ {
public static void Initialize()
{
SmbTransport.ClearCachedConnections();
SmbConstants.ApplyConfig();
}
internal const int ORdonly = 0x01; internal const int ORdonly = 0x01;
internal const int OWronly = 0x02; internal const int OWronly = 0x02;
@ -383,10 +374,10 @@ namespace SharpCifs.Smb
Sharpen.Runtime.PrintStackTrace(cnfe); Sharpen.Runtime.PrintStackTrace(cnfe);
}*/ }*/
AttrExpirationPeriod AttrExpirationPeriod = Config.GetLong("jcifs.smb.client.attrExpirationPeriod", DefaultAttrExpirationPeriod
= Config.GetLong("jcifs.smb.client.attrExpirationPeriod", DefaultAttrExpirationPeriod); );
IgnoreCopyToException IgnoreCopyToException = Config.GetBoolean("jcifs.smb.client.ignoreCopyToException"
= Config.GetBoolean("jcifs.smb.client.ignoreCopyToException", true); , true);
Dfs = new Dfs(); Dfs = new Dfs();
} }
@ -531,11 +522,11 @@ namespace SharpCifs.Smb
/// <exception cref="UnknownHostException">If the server or workgroup of the <tt>context</tt> file cannot be determined /// <exception cref="UnknownHostException">If the server or workgroup of the <tt>context</tt> file cannot be determined
/// </exception> /// </exception>
public SmbFile(SmbFile context, string name) public SmbFile(SmbFile context, string name)
: this(context.IsWorkgroup0() : this(context.IsWorkgroup0
? new Uri("smb://" + name) () ? new Uri("smb://" + name) : new Uri(context.Url.AbsoluteUri + name),
: new Uri(context.Url.AbsoluteUri + name),
context.Auth) context.Auth)
{ {
this._enableDfs = context.EnableDfs; this._enableDfs = context.EnableDfs;
if (!context.IsWorkgroup0()) if (!context.IsWorkgroup0())
@ -574,6 +565,7 @@ namespace SharpCifs.Smb
public SmbFile(string context, string name) public SmbFile(string context, string name)
: this(new Uri(context + name)) : this(new Uri(context + name))
{ {
} }
@ -590,8 +582,10 @@ namespace SharpCifs.Smb
/// <exception cref="System.UriFormatException">If the <code>url</code> parameter does not follow the prescribed syntax /// <exception cref="System.UriFormatException">If the <code>url</code> parameter does not follow the prescribed syntax
/// </exception> /// </exception>
public SmbFile(string url, NtlmPasswordAuthentication auth) public SmbFile(string url, NtlmPasswordAuthentication auth)
: this(new Uri(url, UriKind.RelativeOrAbsolute), auth) : this(new Uri(url, UriKind.RelativeOrAbsolute),
auth)
{ {
} }
/// <summary>Constructs an SmbFile representing a file on an SMB network.</summary> /// <summary>Constructs an SmbFile representing a file on an SMB network.</summary>
@ -610,7 +604,8 @@ namespace SharpCifs.Smb
/// <exception cref="System.UriFormatException">If the <code>url</code> parameter does not follow the prescribed syntax /// <exception cref="System.UriFormatException">If the <code>url</code> parameter does not follow the prescribed syntax
/// </exception> /// </exception>
public SmbFile(string url, NtlmPasswordAuthentication auth, int shareAccess) public SmbFile(string url, NtlmPasswordAuthentication auth, int shareAccess)
: this(new Uri(url), auth) : this
(new Uri(url), auth)
{ {
// Initially null; set by getUncPath; dir must end with '/' // Initially null; set by getUncPath; dir must end with '/'
// Can be null // Can be null
@ -619,7 +614,8 @@ namespace SharpCifs.Smb
// Initially null // Initially null
// Initially null; set by getUncPath; never ends with '/' // Initially null; set by getUncPath; never ends with '/'
// Initially 0; set by open() // Initially 0; set by open()
if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) != 0) if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) !=
0)
{ {
throw new RuntimeException("Illegal shareAccess parameter"); throw new RuntimeException("Illegal shareAccess parameter");
} }
@ -644,8 +640,11 @@ namespace SharpCifs.Smb
/// do not follow the prescribed syntax /// do not follow the prescribed syntax
/// </exception> /// </exception>
public SmbFile(string context, string name, NtlmPasswordAuthentication auth) public SmbFile(string context, string name, NtlmPasswordAuthentication auth)
: this(new Uri(context + name), auth) : this
(new Uri(context + name)
, auth)
{ {
} }
@ -673,13 +672,12 @@ namespace SharpCifs.Smb
/// If the <code>context</code> and <code>name</code> parameters /// If the <code>context</code> and <code>name</code> parameters
/// do not follow the prescribed syntax /// do not follow the prescribed syntax
/// </exception> /// </exception>
public SmbFile(string context, public SmbFile(string context, string name, NtlmPasswordAuthentication auth, int
string name, shareAccess)
NtlmPasswordAuthentication auth,
int shareAccess)
: this(new Uri(context + name), auth) : this(new Uri(context + name), auth)
{ {
if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) != 0) if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) !=
0)
{ {
throw new RuntimeException("Illegal shareAccess parameter"); throw new RuntimeException("Illegal shareAccess parameter");
} }
@ -711,12 +709,11 @@ namespace SharpCifs.Smb
/// </exception> /// </exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
public SmbFile(SmbFile context, string name, int shareAccess) public SmbFile(SmbFile context, string name, int shareAccess)
: this(context.IsWorkgroup0() : this(context.IsWorkgroup0() ? new Uri("smb://" + name) : new Uri(
? new Uri("smb://" + name) context.Url.AbsoluteUri + name), context.Auth)
: new Uri(context.Url.AbsoluteUri + name),
context.Auth)
{ {
if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) != 0) if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) !=
0)
{ {
throw new RuntimeException("Illegal shareAccess parameter"); throw new RuntimeException("Illegal shareAccess parameter");
} }
@ -746,7 +743,8 @@ namespace SharpCifs.Smb
/// </remarks> /// </remarks>
/// <param name="url">The URL of the target resource</param> /// <param name="url">The URL of the target resource</param>
protected SmbFile(Uri url) protected SmbFile(Uri url)
: this(url, new NtlmPasswordAuthentication(url.GetUserInfo())) : this(url, new NtlmPasswordAuthentication(url.GetUserInfo
()))
{ {
} }
@ -771,18 +769,16 @@ namespace SharpCifs.Smb
/// <exception cref="System.UriFormatException"></exception> /// <exception cref="System.UriFormatException"></exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
internal SmbFile(SmbFile context, /*internal SmbFile(Jcifs.Smb.SmbFile context, string name, int type, int attributes
string name, , long createTime, long lastModified, long size)
int type, : this(context.IsWorkgroup0() ?
int attributes, new Uri(null, "smb://" + name + "/") : new Uri(context.url,
long createTime, name + ((attributes & ATTR_DIRECTORY) > 0 ? "/" : string.Empty)))*/
long lastModified, internal SmbFile(SmbFile context, string name, int type, int attributes
long size) , long createTime, long lastModified, long size)
: this(context.IsWorkgroup0() : this(context.IsWorkgroup0() ?
? new Uri("smb://" + name + "/") new Uri("smb://" + name + "/") : new Uri(context.Url.AbsoluteUri +
: new Uri(context.Url.AbsoluteUri + name + ((attributes & AttrDirectory) > 0 name + ((attributes & AttrDirectory) > 0 ? "/" : string.Empty)))
? "/"
: string.Empty)))
{ {
Auth = context.Auth; Auth = context.Auth;
if (context._share != null) if (context._share != null)
@ -850,7 +846,8 @@ namespace SharpCifs.Smb
return; return;
} }
Connect0(); Connect0();
DfsReferral dr = Dfs.Resolve(Tree.Session.transport.TconHostName, Tree.Share, Unc, Auth); DfsReferral dr = Dfs.Resolve(Tree.Session.transport.TconHostName, Tree.Share, Unc
, Auth);
if (dr != null) if (dr != null)
{ {
string service = null; string service = null;
@ -949,10 +946,8 @@ namespace SharpCifs.Smb
dunc = "\\" + dr.Path + dunc; dunc = "\\" + dr.Path + dunc;
} }
Unc = dunc; Unc = dunc;
if (request != null if (request != null && request.Path != null && request.Path.EndsWith("\\") && dunc
&& request.Path != null .EndsWith("\\") == false)
&& request.Path.EndsWith("\\")
&& dunc.EndsWith("\\") == false)
{ {
dunc += "\\"; dunc += "\\";
} }
@ -964,10 +959,8 @@ namespace SharpCifs.Smb
} }
else else
{ {
if (Tree.InDomainDfs if (Tree.InDomainDfs && !(request is NtTransQuerySecurityDesc) && !(request is SmbComClose
&& !(request is NtTransQuerySecurityDesc) ) && !(request is SmbComFindClose2))
&& !(request is SmbComClose)
&& !(request is SmbComFindClose2))
{ {
throw new SmbException(NtStatus.NtStatusNotFound, false); throw new SmbException(NtStatus.NtStatusNotFound, false);
} }
@ -979,7 +972,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response) internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response
)
{ {
for (; ; ) for (; ; )
{ {
@ -1105,8 +1099,8 @@ namespace SharpCifs.Smb
{ {
throw; throw;
} }
Addresses = UniAddress.GetAllByName(NtlmPasswordAuthentication.DefaultDomain, Addresses = UniAddress.GetAllByName(NtlmPasswordAuthentication.DefaultDomain, true
true); );
} }
} }
else else
@ -1207,8 +1201,8 @@ namespace SharpCifs.Smb
} }
else else
{ {
if ((a = NtlmAuthenticator.RequestNtlmPasswordAuthentication(Url.ToString(), sae)) if ((a = NtlmAuthenticator.RequestNtlmPasswordAuthentication(Url.ToString(), sae)
!= null) ) != null)
{ {
Auth = a; Auth = a;
ssn = trans.GetSmbSession(Auth); ssn = trans.GetSmbSession(Auth);
@ -1297,13 +1291,8 @@ namespace SharpCifs.Smb
if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs)) if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs))
{ {
SmbComNtCreateAndXResponse response = new SmbComNtCreateAndXResponse(); SmbComNtCreateAndXResponse response = new SmbComNtCreateAndXResponse();
SmbComNtCreateAndX request = new SmbComNtCreateAndX(Unc, SmbComNtCreateAndX request = new SmbComNtCreateAndX(Unc, flags, access, _shareAccess
flags, , attrs, options, null);
access,
_shareAccess,
attrs,
options,
null);
if (this is SmbNamedPipe) if (this is SmbNamedPipe)
{ {
request.Flags0 |= 0x16; request.Flags0 |= 0x16;
@ -1521,10 +1510,8 @@ namespace SharpCifs.Smb
i++; i++;
break; break;
} }
if ((i + 1) < length if ((i + 1) < length && instr[i] == '.' && instr[i + 1] == '.' && ((i + 2) >= length
&& instr[i] == '.' || instr[i + 2] == '/'))
&& instr[i + 1] == '.'
&& ((i + 2) >= length || instr[i + 2] == '/'))
{ {
i += 2; i += 2;
if (o == 1) if (o == 1)
@ -1781,17 +1768,15 @@ namespace SharpCifs.Smb
} }
if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs)) if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs))
{ {
Trans2QueryPathInformationResponse response Trans2QueryPathInformationResponse response = new Trans2QueryPathInformationResponse
= new Trans2QueryPathInformationResponse(infoLevel); (infoLevel);
Send(new Trans2QueryPathInformation(path, infoLevel), response); Send(new Trans2QueryPathInformation(path, infoLevel), response);
return response.Info; return response.Info;
} }
else else
{ {
SmbComQueryInformationResponse response SmbComQueryInformationResponse response = new SmbComQueryInformationResponse(Tree
= new SmbComQueryInformationResponse(Tree.Session.transport.Server.ServerTimeZone .Session.transport.Server.ServerTimeZone * 1000 * 60L);
* 1000
* 60L);
Send(new SmbComQueryInformation(path), response); Send(new SmbComQueryInformation(path), response);
return response; return response;
} }
@ -1850,8 +1835,8 @@ namespace SharpCifs.Smb
else else
{ {
// treeConnect is good enough // treeConnect is good enough
IInfo info = QueryPath(GetUncPath0(), IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO
Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO); );
_attributes = info.GetAttributes(); _attributes = info.GetAttributes();
_createTime = info.GetCreateTime(); _createTime = info.GetCreateTime();
_lastModified = info.GetLastWriteTime(); _lastModified = info.GetLastWriteTime();
@ -2189,10 +2174,8 @@ namespace SharpCifs.Smb
/// <exception cref="SmbException"></exception> /// <exception cref="SmbException"></exception>
public virtual SmbFile[] ListFiles(string wildcard) public virtual SmbFile[] ListFiles(string wildcard)
{ {
return ListFiles(wildcard, return ListFiles(wildcard, AttrDirectory | AttrHidden | AttrSystem, null, null
AttrDirectory | AttrHidden | AttrSystem, );
null,
null);
} }
/// <summary>List the contents of this SMB resource.</summary> /// <summary>List the contents of this SMB resource.</summary>
@ -2225,10 +2208,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual string[] List(string wildcard, internal virtual string[] List(string wildcard, int searchAttributes, ISmbFilenameFilter
int searchAttributes, fnf, ISmbFileFilter ff)
ISmbFilenameFilter fnf,
ISmbFileFilter ff)
{ {
List<object> list = new List<object>(); List<object> list = new List<object>();
DoEnum(list, false, wildcard, searchAttributes, fnf, ff); DoEnum(list, false, wildcard, searchAttributes, fnf, ff);
@ -2237,10 +2218,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual SmbFile[] ListFiles(string wildcard, internal virtual SmbFile[] ListFiles(string wildcard, int searchAttributes
int searchAttributes, , ISmbFilenameFilter fnf, ISmbFileFilter ff)
ISmbFilenameFilter fnf,
ISmbFileFilter ff)
{ {
List<object> list = new List<object>(); List<object> list = new List<object>();
DoEnum(list, true, wildcard, searchAttributes, fnf, ff); DoEnum(list, true, wildcard, searchAttributes, fnf, ff);
@ -2249,12 +2228,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual void DoEnum(List<object> list, internal virtual void DoEnum(List<object> list, bool files, string wildcard, int searchAttributes
bool files, , ISmbFilenameFilter fnf, ISmbFileFilter ff)
string wildcard,
int searchAttributes,
ISmbFilenameFilter fnf,
ISmbFileFilter ff)
{ {
if (ff != null && ff is DosFileFilter) if (ff != null && ff is DosFileFilter)
{ {
@ -2267,9 +2242,7 @@ namespace SharpCifs.Smb
} }
try try
{ {
int hostlen = Url.GetHost() != null int hostlen = Url.GetHost() != null ? Url.GetHost().Length : 0;
? Url.GetHost().Length
: 0;
if (hostlen == 0 || GetType() == TypeWorkgroup) if (hostlen == 0 || GetType() == TypeWorkgroup)
{ {
DoNetServerEnum(list, files, wildcard, searchAttributes, fnf, ff); DoNetServerEnum(list, files, wildcard, searchAttributes, fnf, ff);
@ -2312,12 +2285,8 @@ namespace SharpCifs.Smb
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
/// <exception cref="System.UriFormatException"></exception> /// <exception cref="System.UriFormatException"></exception>
internal virtual void DoShareEnum(List<object> list, internal virtual void DoShareEnum(List<object> list, bool files, string wildcard, int
bool files, searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
string wildcard,
int searchAttributes,
ISmbFilenameFilter fnf,
ISmbFileFilter ff)
{ {
string p = Url.AbsolutePath; string p = Url.AbsolutePath;
IOException last = null; IOException last = null;
@ -2428,13 +2397,8 @@ namespace SharpCifs.Smb
if (name.Length > 0) if (name.Length > 0)
{ {
// if !files we don't need to create SmbFiles here // if !files we don't need to create SmbFiles here
SmbFile f = new SmbFile(this, SmbFile f = new SmbFile(this, name, e.GetType(), AttrReadonly
name, | AttrDirectory, 0L, 0L, 0L);
e.GetType(),
AttrReadonly | AttrDirectory,
0L,
0L,
0L);
if (ff != null && ff.Accept(f) == false) if (ff != null && ff.Accept(f) == false)
{ {
continue; continue;
@ -2457,10 +2421,8 @@ namespace SharpCifs.Smb
MsrpcDfsRootEnum rpc; MsrpcDfsRootEnum rpc;
DcerpcHandle handle = null; DcerpcHandle handle = null;
IFileEntry[] entries; IFileEntry[] entries;
handle = DcerpcHandle.GetHandle("ncacn_np:" handle = DcerpcHandle.GetHandle("ncacn_np:" + GetAddress().GetHostAddress() + "[\\PIPE\\netdfs]"
+ GetAddress().GetHostAddress() , Auth);
+ "[\\PIPE\\netdfs]",
Auth);
try try
{ {
rpc = new MsrpcDfsRootEnum(GetServer()); rpc = new MsrpcDfsRootEnum(GetServer());
@ -2493,10 +2455,8 @@ namespace SharpCifs.Smb
MsrpcShareEnum rpc; MsrpcShareEnum rpc;
DcerpcHandle handle; DcerpcHandle handle;
rpc = new MsrpcShareEnum(Url.GetHost()); rpc = new MsrpcShareEnum(Url.GetHost());
handle = DcerpcHandle.GetHandle("ncacn_np:" handle = DcerpcHandle.GetHandle("ncacn_np:" + GetAddress().GetHostAddress() + "[\\PIPE\\srvsvc]"
+ GetAddress().GetHostAddress() , Auth);
+ "[\\PIPE\\srvsvc]",
Auth);
try try
{ {
handle.Sendrecv(rpc); handle.Sendrecv(rpc);
@ -2538,23 +2498,17 @@ namespace SharpCifs.Smb
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
/// <exception cref="System.UriFormatException"></exception> /// <exception cref="System.UriFormatException"></exception>
internal virtual void DoNetServerEnum(List<object> list, internal virtual void DoNetServerEnum(List<object> list, bool files, string wildcard
bool files, , int searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
string wildcard,
int searchAttributes,
ISmbFilenameFilter fnf,
ISmbFileFilter ff)
{ {
int listType = Url.GetHost().Length == 0 int listType = Url.GetHost().Length == 0 ? 0 : GetType();
? 0
: GetType();
SmbComTransaction req; SmbComTransaction req;
SmbComTransactionResponse resp; SmbComTransactionResponse resp;
if (listType == 0) if (listType == 0)
{ {
Connect0(); Connect0();
req = new NetServerEnum2(Tree.Session.transport.Server.OemDomainName, req = new NetServerEnum2(Tree.Session.transport.Server.OemDomainName, NetServerEnum2
NetServerEnum2.SvTypeDomainEnum); .SvTypeDomainEnum);
resp = new NetServerEnum2Response(); resp = new NetServerEnum2Response();
} }
else else
@ -2591,13 +2545,8 @@ namespace SharpCifs.Smb
if (name.Length > 0) if (name.Length > 0)
{ {
// if !files we don't need to create SmbFiles here // if !files we don't need to create SmbFiles here
SmbFile f = new SmbFile(this, SmbFile f = new SmbFile(this, name, e.GetType(), AttrReadonly
name, | AttrDirectory, 0L, 0L, 0L);
e.GetType(),
AttrReadonly | AttrDirectory,
0L,
0L,
0L);
if (ff != null && ff.Accept(f) == false) if (ff != null && ff.Accept(f) == false)
{ {
continue; continue;
@ -2626,12 +2575,8 @@ namespace SharpCifs.Smb
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
/// <exception cref="System.UriFormatException"></exception> /// <exception cref="System.UriFormatException"></exception>
internal virtual void DoFindFirstNext(List<object> list, internal virtual void DoFindFirstNext(List<object> list, bool files, string wildcard
bool files, , int searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff)
string wildcard,
int searchAttributes,
ISmbFilenameFilter fnf,
ISmbFileFilter ff)
{ {
SmbComTransaction req; SmbComTransaction req;
Trans2FindFirst2Response resp; Trans2FindFirst2Response resp;
@ -2675,13 +2620,8 @@ namespace SharpCifs.Smb
} }
if (name.Length > 0) if (name.Length > 0)
{ {
SmbFile f = new SmbFile(this, SmbFile f = new SmbFile(this, name, TypeFilesystem, e.GetAttributes
name, (), e.CreateTime(), e.LastModified(), e.Length());
TypeFilesystem,
e.GetAttributes(),
e.CreateTime(),
e.LastModified(),
e.Length());
if (ff != null && ff.Accept(f) == false) if (ff != null && ff.Accept(f) == false)
{ {
continue; continue;
@ -2782,10 +2722,7 @@ namespace SharpCifs.Smb
: base("JCIFS-WriterThread") : base("JCIFS-WriterThread")
{ {
this._enclosing = enclosing; this._enclosing = enclosing;
UseNtSmbs = this._enclosing.Tree UseNtSmbs = this._enclosing.Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs);
.Session
.transport
.HasCapability(SmbConstants.CapNtSmbs);
if (UseNtSmbs) if (UseNtSmbs)
{ {
Reqx = new SmbComWriteAndX(); Reqx = new SmbComWriteAndX();
@ -2858,12 +2795,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual void CopyTo0(SmbFile dest, internal virtual void CopyTo0(SmbFile dest, byte[][] b, int bsize, WriterThread
byte[][] b, w, SmbComReadAndX req, SmbComReadAndXResponse resp)
int bsize,
WriterThread w,
SmbComReadAndX req,
SmbComReadAndXResponse resp)
{ {
int i; int i;
if (_attrExpiration < Runtime.CurrentTimeMillis()) if (_attrExpiration < Runtime.CurrentTimeMillis())
@ -2872,8 +2805,8 @@ namespace SharpCifs.Smb
_createTime = 0L; _createTime = 0L;
_lastModified = 0L; _lastModified = 0L;
_isExists = false; _isExists = false;
IInfo info = QueryPath(GetUncPath0(), IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO
Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO); );
_attributes = info.GetAttributes(); _attributes = info.GetAttributes();
_createTime = info.GetCreateTime(); _createTime = info.GetCreateTime();
_lastModified = info.GetLastWriteTime(); _lastModified = info.GetLastWriteTime();
@ -2894,8 +2827,8 @@ namespace SharpCifs.Smb
} }
catch (SmbException se) catch (SmbException se)
{ {
if (se.GetNtStatus() != NtStatus.NtStatusAccessDenied if (se.GetNtStatus() != NtStatus.NtStatusAccessDenied && se.GetNtStatus() != NtStatus
&& se.GetNtStatus() != NtStatus.NtStatusObjectNameCollision) .NtStatusObjectNameCollision)
{ {
throw; throw;
} }
@ -2906,13 +2839,8 @@ namespace SharpCifs.Smb
{ {
for (i = 0; i < files.Length; i++) for (i = 0; i < files.Length; i++)
{ {
ndest = new SmbFile(dest, ndest = new SmbFile(dest, files[i].GetName(), files[i].Type, files[i]._attributes,
files[i].GetName(), files[i]._createTime, files[i]._lastModified, files[i]._size);
files[i].Type,
files[i]._attributes,
files[i]._createTime,
files[i]._lastModified,
files[i]._size);
files[i].CopyTo0(ndest, b, bsize, w, req, resp); files[i].CopyTo0(ndest, b, bsize, w, req, resp);
} }
} }
@ -2933,20 +2861,16 @@ namespace SharpCifs.Smb
Open(ORdonly, 0, AttrNormal, 0); Open(ORdonly, 0, AttrNormal, 0);
try try
{ {
dest.Open(OCreat | OWronly | OTrunc, dest.Open(OCreat | OWronly | OTrunc, SmbConstants.FileWriteData |
SmbConstants.FileWriteData | SmbConstants.FileWriteAttributes, SmbConstants.FileWriteAttributes, _attributes, 0);
_attributes,
0);
} }
catch (SmbAuthException sae) catch (SmbAuthException sae)
{ {
if ((dest._attributes & AttrReadonly) != 0) if ((dest._attributes & AttrReadonly) != 0)
{ {
dest.SetPathInformation(dest._attributes & ~AttrReadonly, 0L, 0L); dest.SetPathInformation(dest._attributes & ~AttrReadonly, 0L, 0L);
dest.Open(OCreat | OWronly | OTrunc, dest.Open(OCreat | OWronly | OTrunc, SmbConstants.FileWriteData |
SmbConstants.FileWriteData | SmbConstants.FileWriteAttributes, SmbConstants.FileWriteAttributes, _attributes, 0);
_attributes,
0);
} }
else else
{ {
@ -2990,19 +2914,16 @@ namespace SharpCifs.Smb
i = i == 1 ? 0 : 1; i = i == 1 ? 0 : 1;
off += resp.DataLength; off += resp.DataLength;
} }
dest.Send(new Trans2SetFileInformation(dest.Fid, dest.Send(new Trans2SetFileInformation(dest.Fid, _attributes, _createTime, _lastModified
_attributes, ), new Trans2SetFileInformationResponse());
_createTime,
_lastModified),
new Trans2SetFileInformationResponse());
dest.Close(0L); dest.Close(0L);
} }
catch (SmbException se) catch (SmbException se)
{ {
if (IgnoreCopyToException == false) if (IgnoreCopyToException == false)
{ {
throw new SmbException("Failed to copy file from " throw new SmbException("Failed to copy file from [" + ToString() + "] to ["
+ "[" + ToString() + "] to [" + dest + "]", se); + dest + "]", se);
} }
if (Log.Level > 1) if (Log.Level > 1)
{ {
@ -3055,8 +2976,8 @@ namespace SharpCifs.Smb
ResolveDfs(null); ResolveDfs(null);
try try
{ {
if (GetAddress().Equals(dest.GetAddress()) if (GetAddress().Equals(dest.GetAddress()) && _canon.RegionMatches(true, 0, dest._canon
&& _canon.RegionMatches(true, 0, dest._canon, 0, Math.Min(_canon.Length, dest._canon.Length))) , 0, Math.Min(_canon.Length, dest._canon.Length)))
{ {
throw new SmbException("Source and destination paths overlap."); throw new SmbException("Source and destination paths overlap.");
} }
@ -3066,8 +2987,7 @@ namespace SharpCifs.Smb
} }
w = new WriterThread(this); w = new WriterThread(this);
w.SetDaemon(true); w.SetDaemon(true);
w.Start(true); w.Start();
SmbTransport t1 = Tree.Session.transport; SmbTransport t1 = Tree.Session.transport;
SmbTransport t2 = dest.Tree.Session.transport; SmbTransport t2 = dest.Tree.Session.transport;
if (t1.SndBufSize < t2.SndBufSize) if (t1.SndBufSize < t2.SndBufSize)
@ -3123,8 +3043,8 @@ namespace SharpCifs.Smb
_createTime = 0L; _createTime = 0L;
_lastModified = 0L; _lastModified = 0L;
_isExists = false; _isExists = false;
IInfo info = QueryPath(GetUncPath0(), IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO
Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO); );
_attributes = info.GetAttributes(); _attributes = info.GetAttributes();
_createTime = info.GetCreateTime(); _createTime = info.GetCreateTime();
_lastModified = info.GetLastWriteTime(); _lastModified = info.GetLastWriteTime();
@ -3143,7 +3063,8 @@ namespace SharpCifs.Smb
{ {
try try
{ {
SmbFile[] l = ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null); SmbFile[] l = ListFiles("*", AttrDirectory | AttrHidden | AttrSystem, null, null
);
for (int i = 0; i < l.Length; i++) for (int i = 0; i < l.Length; i++)
{ {
l[i].Delete(); l[i].Delete();
@ -3196,8 +3117,8 @@ namespace SharpCifs.Smb
{ {
if (GetUncPath0().Length > 1 && Type != TypeNamedPipe) if (GetUncPath0().Length > 1 && Type != TypeNamedPipe)
{ {
IInfo info = QueryPath(GetUncPath0(), IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_STANDARD_INFO
Trans2QueryPathInformationResponse.SMB_QUERY_FILE_STANDARD_INFO); );
_size = info.GetSize(); _size = info.GetSize();
} }
else else
@ -3351,14 +3272,10 @@ namespace SharpCifs.Smb
int dir; int dir;
Exists(); Exists();
dir = _attributes & AttrDirectory; dir = _attributes & AttrDirectory;
f = Open0(ORdonly, f = Open0(ORdonly, SmbConstants.FileWriteAttributes, dir, dir != 0 ? 0x0001
SmbConstants.FileWriteAttributes,
dir,
dir != 0
? 0x0001
: 0x0040); : 0x0040);
Send(new Trans2SetFileInformation(f, attrs | dir, ctime, mtime), Send(new Trans2SetFileInformation(f, attrs | dir, ctime, mtime), new Trans2SetFileInformationResponse
new Trans2SetFileInformationResponse()); ());
Close(f, 0L); Close(f, 0L);
_attrExpiration = 0; _attrExpiration = 0;
} }
@ -3513,7 +3430,8 @@ namespace SharpCifs.Smb
return hash + _canon.ToUpper().GetHashCode(); return hash + _canon.ToUpper().GetHashCode();
} }
protected internal virtual bool PathNamesPossiblyEqual(string path1, string path2) protected internal virtual bool PathNamesPossiblyEqual(string path1, string path2
)
{ {
int p1; int p1;
int p2; int p2;
@ -3728,7 +3646,8 @@ namespace SharpCifs.Smb
Ace[] aces; Ace[] aces;
f = Open0(ORdonly, SmbConstants.ReadControl, 0, IsDirectory() ? 1 : 0); f = Open0(ORdonly, SmbConstants.ReadControl, 0, IsDirectory() ? 1 : 0);
NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc(f, 0x04); NtTransQuerySecurityDesc request = new NtTransQuerySecurityDesc(f, 0x04);
NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse(); NtTransQuerySecurityDescResponse response = new NtTransQuerySecurityDescResponse(
);
try try
{ {
Send(request, response); Send(request, response);

View File

@ -91,8 +91,8 @@ namespace SharpCifs.Smb
{ {
file.Connect0(); file.Connect0();
} }
_readSize = Math.Min(file.Tree.Session.transport.RcvBufSize - 70, _readSize = Math.Min(file.Tree.Session.transport.RcvBufSize - 70, file.Tree.Session
file.Tree.Session.transport.Server.MaxBufferSize - 70); .transport.Server.MaxBufferSize - 70);
} }
protected internal virtual IOException SeToIoe(SmbException se) protected internal virtual IOException SeToIoe(SmbException se)
@ -194,9 +194,7 @@ namespace SharpCifs.Smb
int n; int n;
do do
{ {
r = len > _readSize r = len > _readSize ? _readSize : len;
? _readSize
: len;
if (File.Log.Level >= 4) if (File.Log.Level >= 4)
{ {
File.Log.WriteLine("read: len=" + len + ",r=" + r + ",fp=" + _fp); File.Log.WriteLine("read: len=" + len + ",r=" + r + ",fp=" + _fp);
@ -209,13 +207,12 @@ namespace SharpCifs.Smb
{ {
request.MinCount = request.MaxCount = request.Remaining = 1024; request.MinCount = request.MaxCount = request.Remaining = 1024;
} }
//ここで読み込んでいるらしい。 //ここで読み込んでいるらしい。
File.Send(request, response); File.Send(request, response);
} }
catch (SmbException se) catch (SmbException se)
{ {
if (File.Type == SmbFile.TypeNamedPipe if (File.Type == SmbFile.TypeNamedPipe && se.GetNtStatus() == NtStatus.NtStatusPipeBroken)
&& se.GetNtStatus() == NtStatus.NtStatusPipeBroken)
{ {
return -1; return -1;
} }
@ -233,6 +230,7 @@ namespace SharpCifs.Smb
} }
while (len > 0 && n == r); while (len > 0 && n == r);
return (int)(_fp - start); return (int)(_fp - start);
} }
@ -257,12 +255,13 @@ namespace SharpCifs.Smb
try try
{ {
pipe = (SmbNamedPipe)File; pipe = (SmbNamedPipe)File;
File.Open(SmbFile.OExcl, pipe.PipeType & 0xFF0000, SmbFile.AttrNormal, 0); File.Open(SmbFile.OExcl, pipe.PipeType & 0xFF0000, SmbFile.AttrNormal
, 0);
req = new TransPeekNamedPipe(File.Unc, File.Fid); req = new TransPeekNamedPipe(File.Unc, File.Fid);
resp = new TransPeekNamedPipeResponse(pipe); resp = new TransPeekNamedPipeResponse(pipe);
pipe.Send(req, resp); pipe.Send(req, resp);
if (resp.status == TransPeekNamedPipeResponse.StatusDisconnected if (resp.status == TransPeekNamedPipeResponse.StatusDisconnected || resp.status
|| resp.status == TransPeekNamedPipeResponse.StatusServerEndClosed) == TransPeekNamedPipeResponse.StatusServerEndClosed)
{ {
File.Opened = false; File.Opened = false;
return 0; return 0;
@ -301,8 +300,7 @@ namespace SharpCifs.Smb
/// Add by dobes /// Add by dobes
/// mod interface to WrappedSystemStream readable, for random access. /// mod interface to WrappedSystemStream readable, for random access.
/// </remarks> /// </remarks>
internal override long Position internal override long Position {
{
get { return this._fp; } get { return this._fp; }
set set
{ {

View File

@ -100,7 +100,8 @@ namespace SharpCifs.Smb
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
/// <exception cref="System.UriFormatException"></exception> /// <exception cref="System.UriFormatException"></exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
public SmbFileOutputStream(string url, bool append) : this(new SmbFile(url), append) public SmbFileOutputStream(string url, bool append) : this(new SmbFile(url), append
)
{ {
} }
@ -119,12 +120,9 @@ namespace SharpCifs.Smb
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
/// <exception cref="System.UriFormatException"></exception> /// <exception cref="System.UriFormatException"></exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
public SmbFileOutputStream(SmbFile file, bool append) public SmbFileOutputStream(SmbFile file, bool append) : this(file, append, append
: this(file, ? SmbFile.OCreat | SmbFile.OWronly | SmbFile.OAppend : SmbFile.OCreat | SmbFile
append, .OWronly | SmbFile.OTrunc)
append
? SmbFile.OCreat | SmbFile.OWronly | SmbFile.OAppend
: SmbFile.OCreat | SmbFile.OWronly | SmbFile.OTrunc)
{ {
} }
@ -152,8 +150,8 @@ namespace SharpCifs.Smb
/// <exception cref="Jcifs.Smb.SmbException"></exception> /// <exception cref="Jcifs.Smb.SmbException"></exception>
/// <exception cref="System.UriFormatException"></exception> /// <exception cref="System.UriFormatException"></exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
public SmbFileOutputStream(string url, int shareAccess) public SmbFileOutputStream(string url, int shareAccess) : this(new SmbFile(url, string.Empty
: this(new SmbFile(url, string.Empty, null, shareAccess), false) , null, shareAccess), false)
{ {
} }
@ -184,16 +182,15 @@ namespace SharpCifs.Smb
if (file is SmbNamedPipe && file.Unc.StartsWith("\\pipe\\")) if (file is SmbNamedPipe && file.Unc.StartsWith("\\pipe\\"))
{ {
file.Unc = Runtime.Substring(file.Unc, 5); file.Unc = Runtime.Substring(file.Unc, 5);
file.Send(new TransWaitNamedPipe("\\pipe" + file.Unc), file.Send(new TransWaitNamedPipe("\\pipe" + file.Unc), new TransWaitNamedPipeResponse
new TransWaitNamedPipeResponse()); ());
} }
file.Open(openFlags, file.Open(openFlags, _access | SmbConstants.FileWriteData, SmbFile.AttrNormal,
_access | SmbConstants.FileWriteData,
SmbFile.AttrNormal,
0); 0);
this._openFlags &= ~(SmbFile.OCreat | SmbFile.OTrunc); this._openFlags &= ~(SmbFile.OCreat | SmbFile.OTrunc);
_writeSize = file.Tree.Session.transport.SndBufSize - 70; _writeSize = file.Tree.Session.transport.SndBufSize - 70;
_useNtSmbs = file.Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs); _useNtSmbs = file.Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs
);
if (_useNtSmbs) if (_useNtSmbs)
{ {
_reqx = new SmbComWriteAndX(); _reqx = new SmbComWriteAndX();
@ -255,9 +252,7 @@ namespace SharpCifs.Smb
// ensure file is open // ensure file is open
if (_file.IsOpen() == false) if (_file.IsOpen() == false)
{ {
_file.Open(_openFlags, _file.Open(_openFlags, _access | SmbConstants.FileWriteData, SmbFile.AttrNormal,
_access | SmbConstants.FileWriteData,
SmbFile.AttrNormal,
0); 0);
if (_append) if (_append)
{ {
@ -280,8 +275,8 @@ namespace SharpCifs.Smb
{ {
if (_file.IsOpen() == false && _file is SmbNamedPipe) if (_file.IsOpen() == false && _file is SmbNamedPipe)
{ {
_file.Send(new TransWaitNamedPipe("\\pipe" + _file.Unc), _file.Send(new TransWaitNamedPipe("\\pipe" + _file.Unc), new TransWaitNamedPipeResponse
new TransWaitNamedPipeResponse()); ());
} }
WriteDirect(b, off, len, 0); WriteDirect(b, off, len, 0);
} }
@ -300,12 +295,10 @@ namespace SharpCifs.Smb
throw new IOException("Bad file descriptor"); throw new IOException("Bad file descriptor");
} }
EnsureOpen(); EnsureOpen();
/* /*if (file.log.level >= 4)
if (file.log.level >= 4)
{ {
file.log.WriteLine("write: fid=" + file.fid + ",off=" + off + ",len=" + len); file.log.WriteLine("write: fid=" + file.fid + ",off=" + off + ",len=" + len);
} }*/
*/
int w; int w;
do do
{ {

View File

@ -128,8 +128,8 @@ namespace SharpCifs.Smb
/// <exception cref="System.UriFormatException"></exception> /// <exception cref="System.UriFormatException"></exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
public SmbNamedPipe(string url, int pipeType, NtlmPasswordAuthentication auth) public SmbNamedPipe(string url, int pipeType, NtlmPasswordAuthentication auth) :
: base(url, auth) base(url, auth)
{ {
this.PipeType = pipeType; this.PipeType = pipeType;
Type = TypeNamedPipe; Type = TypeNamedPipe;
@ -137,8 +137,8 @@ namespace SharpCifs.Smb
/// <exception cref="System.UriFormatException"></exception> /// <exception cref="System.UriFormatException"></exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
public SmbNamedPipe(Uri url, int pipeType, NtlmPasswordAuthentication auth) public SmbNamedPipe(Uri url, int pipeType, NtlmPasswordAuthentication auth) : base
: base(url, auth) (url, auth)
{ {
this.PipeType = pipeType; this.PipeType = pipeType;
Type = TypeNamedPipe; Type = TypeNamedPipe;
@ -163,15 +163,15 @@ namespace SharpCifs.Smb
{ {
if (PipeIn == null) if (PipeIn == null)
{ {
if ((PipeType & PipeTypeCall) == PipeTypeCall if ((PipeType & PipeTypeCall) == PipeTypeCall || (PipeType & PipeTypeTransact
|| (PipeType & PipeTypeTransact) == PipeTypeTransact) ) == PipeTypeTransact)
{ {
PipeIn = new TransactNamedPipeInputStream(this); PipeIn = new TransactNamedPipeInputStream(this);
} }
else else
{ {
PipeIn = new SmbFileInputStream(this, PipeIn = new SmbFileInputStream(this, (PipeType & unchecked((int)(0xFFFF00FF))) |
(PipeType & unchecked((int)(0xFFFF00FF))) | OExcl); OExcl);
} }
} }
return PipeIn; return PipeIn;
@ -193,16 +193,15 @@ namespace SharpCifs.Smb
{ {
if (PipeOut == null) if (PipeOut == null)
{ {
if ((PipeType & PipeTypeCall) == PipeTypeCall if ((PipeType & PipeTypeCall) == PipeTypeCall || (PipeType & PipeTypeTransact
|| (PipeType & PipeTypeTransact) == PipeTypeTransact) ) == PipeTypeTransact)
{ {
PipeOut = new TransactNamedPipeOutputStream(this); PipeOut = new TransactNamedPipeOutputStream(this);
} }
else else
{ {
PipeOut = new SmbFileOutputStream(this, PipeOut = new SmbFileOutputStream(this, false, (PipeType & unchecked((int)(0xFFFF00FF
false, ))) | OExcl);
(PipeType & unchecked((int)(0xFFFF00FF))) | OExcl);
} }
} }
return PipeOut; return PipeOut;

View File

@ -49,8 +49,8 @@ namespace SharpCifs.Smb
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
/// <exception cref="System.UriFormatException"></exception> /// <exception cref="System.UriFormatException"></exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
public SmbRandomAccessFile(string url, string mode, int shareAccess) public SmbRandomAccessFile(string url, string mode, int shareAccess) : this(new SmbFile
: this(new SmbFile(url, string.Empty, null, shareAccess), mode) (url, string.Empty, null, shareAccess), mode)
{ {
} }
@ -196,8 +196,8 @@ namespace SharpCifs.Smb
do do
{ {
w = len > _writeSize ? _writeSize : len; w = len > _writeSize ? _writeSize : len;
_file.Send(new SmbComWriteAndX(_file.Fid, _fp, len - w, b, off, w, null), _file.Send(new SmbComWriteAndX(_file.Fid, _fp, len - w, b, off, w, null), _writeAndxResp
_writeAndxResp); );
_fp += _writeAndxResp.Count; _fp += _writeAndxResp.Count;
len -= (int)_writeAndxResp.Count; len -= (int)_writeAndxResp.Count;
off += (int)_writeAndxResp.Count; off += (int)_writeAndxResp.Count;
@ -232,13 +232,7 @@ namespace SharpCifs.Smb
_file.Open(_openFlags, 0, SmbFile.AttrNormal, _options); _file.Open(_openFlags, 0, SmbFile.AttrNormal, _options);
} }
SmbComWriteResponse rsp = new SmbComWriteResponse(); SmbComWriteResponse rsp = new SmbComWriteResponse();
_file.Send(new SmbComWrite(_file.Fid, _file.Send(new SmbComWrite(_file.Fid, (int)(newLength & unchecked(0xFFFFFFFFL)), 0, _tmp, 0, 0), rsp);
(int)(newLength & unchecked(0xFFFFFFFFL)),
0,
_tmp,
0,
0),
rsp);
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
@ -468,10 +462,8 @@ namespace SharpCifs.Smb
Write(b, 0, b.Length); Write(b, 0, b.Length);
} }
/*
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
public void WriteChars(string s) /* public void WriteChars(string s)
{ {
int clen = s.Length; int clen = s.Length;
int blen = 2 * clen; int blen = 2 * clen;
@ -484,8 +476,7 @@ namespace SharpCifs.Smb
b[j++] = unchecked((byte)((char)(((uchar)c[i]) >> 0))); b[j++] = unchecked((byte)((char)(((uchar)c[i]) >> 0)));
} }
Write(b, 0, blen); Write(b, 0, blen);
} }*/
*/
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
public void WriteUtf(string str) public void WriteUtf(string str)
@ -497,11 +488,7 @@ namespace SharpCifs.Smb
for (int i = 0; i < len; i++) for (int i = 0; i < len; i++)
{ {
ch = str[i]; ch = str[i];
size += ch > unchecked(0x07F) size += ch > unchecked(0x07F) ? (ch > unchecked(0x7FF) ? 3 : 2) : 1;
? (ch > unchecked(0x7FF)
? 3
: 2)
: 1;
} }
dst = new byte[size]; dst = new byte[size];
WriteShort(size); WriteShort(size);

View File

@ -25,20 +25,20 @@ namespace SharpCifs.Smb
{ {
public sealed class SmbSession public sealed class SmbSession
{ {
private static readonly string LogonShare private static readonly string LogonShare = Config.GetProperty("jcifs.smb.client.logonShare"
= Config.GetProperty("jcifs.smb.client.logonShare", null); , null);
private static readonly int LookupRespLimit private static readonly int LookupRespLimit = Config.GetInt("jcifs.netbios.lookupRespLimit"
= Config.GetInt("jcifs.netbios.lookupRespLimit", 3); , 3);
private static readonly string Domain private static readonly string Domain = Config.GetProperty("jcifs.smb.client.domain"
= Config.GetProperty("jcifs.smb.client.domain", null); , null);
private static readonly string Username private static readonly string Username = Config.GetProperty("jcifs.smb.client.username"
= Config.GetProperty("jcifs.smb.client.username", null); , null);
private static readonly int CachePolicy private static readonly int CachePolicy = Config.GetInt("jcifs.netbios.cachePolicy"
= Config.GetInt("jcifs.netbios.cachePolicy", 60 * 10) * 60; , 60 * 10) * 60;
internal static NbtAddress[] DcList; internal static NbtAddress[] DcList;
@ -56,15 +56,15 @@ namespace SharpCifs.Smb
trans.Connect(); trans.Connect();
if (SmbTransport.LogStatic.Level >= 3) if (SmbTransport.LogStatic.Level >= 3)
{ {
SmbTransport.LogStatic.WriteLine( SmbTransport.LogStatic.WriteLine("Default credentials (jcifs.smb.client.username/password)"
"Default credentials (jcifs.smb.client.username/password)" + " not specified. SMB signing may not work propertly." + " Skipping DC interrogation."
+ " not specified. SMB signing may not work propertly." );
+ " Skipping DC interrogation.");
} }
} }
else else
{ {
SmbSession ssn = trans.GetSmbSession(NtlmPasswordAuthentication.Default); SmbSession ssn = trans.GetSmbSession(NtlmPasswordAuthentication.Default
);
ssn.GetSmbTree(LogonShare, null).TreeConnect(null, null); ssn.GetSmbTree(LogonShare, null).TreeConnect(null, null);
} }
return new NtlmChallenge(trans.Server.EncryptionKey, dc); return new NtlmChallenge(trans.Server.EncryptionKey, dc);
@ -86,7 +86,8 @@ namespace SharpCifs.Smb
{ {
if (DcListExpiration < now) if (DcListExpiration < now)
{ {
NbtAddress[] list = NbtAddress.GetAllByName(Domain, 0x1C, null, null); NbtAddress[] list = NbtAddress.GetAllByName(Domain, 0x1C, null,
null);
DcListExpiration = now + CachePolicy * 1000L; DcListExpiration = now + CachePolicy * 1000L;
if (list != null && list.Length > 0) if (list != null && list.Length > 0)
{ {
@ -130,8 +131,8 @@ namespace SharpCifs.Smb
while (retry-- > 0); while (retry-- > 0);
DcListExpiration = now + 1000 * 60 * 15; DcListExpiration = now + 1000 * 60 * 15;
} }
throw new UnknownHostException( throw new UnknownHostException("Failed to negotiate with a suitable domain controller for "
"Failed to negotiate with a suitable domain controller for " + Domain); + Domain);
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
@ -173,11 +174,11 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
public static void Logon(UniAddress dc, int port, NtlmPasswordAuthentication auth) public static void Logon(UniAddress dc, int port, NtlmPasswordAuthentication auth
)
{ {
SmbTree tree = SmbTransport.GetSmbTransport(dc, port) SmbTree tree = SmbTransport.GetSmbTransport(dc, port).GetSmbSession(auth).GetSmbTree
.GetSmbSession(auth) (LogonShare, null);
.GetSmbTree(LogonShare, null);
if (LogonShare == null) if (LogonShare == null)
{ {
tree.TreeConnect(null, null); tree.TreeConnect(null, null);
@ -190,19 +191,6 @@ namespace SharpCifs.Smb
} }
} }
/// <summary>
/// Clear All Cached Transport-Connections
/// </summary>
/// <remarks>
/// Alias of SmbTransport.ClearCachedConnections
/// </remarks>
public static void ClearCachedConnections()
{
SmbTransport.ClearCachedConnections();
}
internal int ConnectionState; internal int ConnectionState;
internal int Uid; internal int Uid;
@ -225,11 +213,8 @@ namespace SharpCifs.Smb
internal string NetbiosName; internal string NetbiosName;
internal SmbSession(UniAddress address, internal SmbSession(UniAddress address, int port, IPAddress localAddr, int localPort
int port, , NtlmPasswordAuthentication auth)
IPAddress localAddr,
int localPort,
NtlmPasswordAuthentication auth)
{ {
// Transport parameters allows trans to be removed from CONNECTIONS // Transport parameters allows trans to be removed from CONNECTIONS
this._address = address; this._address = address;
@ -250,16 +235,14 @@ namespace SharpCifs.Smb
{ {
share = "IPC$"; share = "IPC$";
} }
/* /*for (IEnumeration e = trees.GetEnumerator(); e.MoveNext(); )
for (IEnumeration e = trees.GetEnumerator(); e.MoveNext(); )
{ {
t = (SmbTree)e.Current; t = (SmbTree)e.Current;
if (t.Matches(share, service)) if (t.Matches(share, service))
{ {
return t; return t;
} }
} }*/
*/
foreach (var e in Trees) foreach (var e in Trees)
{ {
t = (SmbTree)e; t = (SmbTree)e;
@ -286,11 +269,8 @@ namespace SharpCifs.Smb
{ {
if (transport == null) if (transport == null)
{ {
transport = SmbTransport.GetSmbTransport(_address, transport = SmbTransport.GetSmbTransport(_address, _port, _localAddr, _localPort, null
_port, );
_localAddr,
_localPort,
null);
} }
return transport; return transport;
} }
@ -338,7 +318,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal void SessionSetup(ServerMessageBlock andx, ServerMessageBlock andxResponse) internal void SessionSetup(ServerMessageBlock andx, ServerMessageBlock andxResponse
)
{ {
lock (Transport()) lock (Transport())
{ {
@ -371,8 +352,8 @@ namespace SharpCifs.Smb
transport.Connect(); transport.Connect();
if (transport.Log.Level >= 4) if (transport.Log.Level >= 4)
{ {
transport.Log.WriteLine("sessionSetup: accountName=" + Auth.Username transport.Log.WriteLine("sessionSetup: accountName=" + Auth.Username + ",primaryDomain="
+ ",primaryDomain=" + Auth.Domain); + Auth.Domain);
} }
Uid = 0; Uid = 0;
do do
@ -381,8 +362,8 @@ namespace SharpCifs.Smb
{ {
case 10: case 10:
{ {
if (Auth != NtlmPasswordAuthentication.Anonymous if (Auth != NtlmPasswordAuthentication.Anonymous && transport.HasCapability(SmbConstants
&& transport.HasCapability(SmbConstants.CapExtendedSecurity)) .CapExtendedSecurity))
{ {
state = 20; state = 20;
break; break;
@ -391,18 +372,15 @@ namespace SharpCifs.Smb
response = new SmbComSessionSetupAndXResponse(andxResponse); response = new SmbComSessionSetupAndXResponse(andxResponse);
if (transport.IsSignatureSetupRequired(Auth)) if (transport.IsSignatureSetupRequired(Auth))
{ {
if (Auth.HashesExternal if (Auth.HashesExternal && NtlmPasswordAuthentication.DefaultPassword != NtlmPasswordAuthentication
&& NtlmPasswordAuthentication.DefaultPassword .Blank)
!= NtlmPasswordAuthentication.Blank)
{ {
transport.GetSmbSession(NtlmPasswordAuthentication.Default) transport.GetSmbSession(NtlmPasswordAuthentication.Default).GetSmbTree(LogonShare
.GetSmbTree(LogonShare, null) , null).TreeConnect(null, null);
.TreeConnect(null, null);
} }
else else
{ {
byte[] signingKey byte[] signingKey = Auth.GetSigningKey(transport.Server.EncryptionKey);
= Auth.GetSigningKey(transport.Server.EncryptionKey);
request.Digest = new SigningDigest(signingKey, false); request.Digest = new SigningDigest(signingKey, false);
} }
} }
@ -419,10 +397,9 @@ namespace SharpCifs.Smb
{ {
ex = se; ex = se;
} }
if (response.IsLoggedInAsGuest if (response.IsLoggedInAsGuest && Runtime.EqualsIgnoreCase("GUEST", Auth.
&& Runtime.EqualsIgnoreCase("GUEST", Auth.Username) == false Username) == false && transport.Server.Security != SmbConstants.SecurityShare &&
&& transport.Server.Security != SmbConstants.SecurityShare Auth != NtlmPasswordAuthentication.Anonymous)
&& Auth != NtlmPasswordAuthentication.Anonymous)
{ {
throw new SmbAuthException(NtStatus.NtStatusLogonFailure); throw new SmbAuthException(NtStatus.NtStatusLogonFailure);
} }
@ -444,9 +421,8 @@ namespace SharpCifs.Smb
{ {
if (nctx == null) if (nctx == null)
{ {
bool doSigning bool doSigning = (transport.Flags2 & SmbConstants.Flags2SecuritySignatures
= (transport.Flags2 ) != 0;
& SmbConstants.Flags2SecuritySignatures) != 0;
nctx = new NtlmContext(Auth, doSigning); nctx = new NtlmContext(Auth, doSigning);
} }
if (SmbTransport.LogStatic.Level >= 4) if (SmbTransport.LogStatic.Level >= 4)
@ -509,9 +485,8 @@ namespace SharpCifs.Smb
{ {
} }
} }
if (response.IsLoggedInAsGuest if (response.IsLoggedInAsGuest && Runtime.EqualsIgnoreCase("GUEST", Auth.
&& Runtime.EqualsIgnoreCase("GUEST", Auth.Username) Username) == false)
== false)
{ {
throw new SmbAuthException(NtStatus.NtStatusLogonFailure); throw new SmbAuthException(NtStatus.NtStatusLogonFailure);
} }
@ -588,10 +563,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbSession[accountName=" + Auth.Username return "SmbSession[accountName=" + Auth.Username + ",primaryDomain=" + Auth.Domain
+ ",primaryDomain=" + Auth.Domain + ",uid=" + Uid + ",connectionState=" + ConnectionState + "]";
+ ",uid=" + Uid
+ ",connectionState=" + ConnectionState + "]";
} }
} }
} }

View File

@ -97,10 +97,8 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbShareInfo[" return "SmbShareInfo[" + "netName=" + NetName + ",type=0x" + Hexdump.ToHexString
+ "netName=" + NetName (Type, 8) + ",remark=" + Remark + "]";
+ ",type=0x" + Hexdump.ToHexString(Type, 8)
+ ",remark=" + Remark + "]";
} }
} }
} }

View File

@ -31,30 +31,25 @@ namespace SharpCifs.Smb
{ {
internal static readonly byte[] Buf = new byte[0xFFFF]; internal static readonly byte[] Buf = new byte[0xFFFF];
internal static readonly SmbComNegotiate NegotiateRequest = new SmbComNegotiate(); internal static readonly SmbComNegotiate NegotiateRequest = new SmbComNegotiate(
);
internal static LogStream LogStatic = LogStream.GetInstance(); internal static LogStream LogStatic = LogStream.GetInstance();
internal static Hashtable DfsRoots = null; internal static Hashtable DfsRoots = null;
internal static SmbTransport GetSmbTransport(UniAddress address, int port) internal static SmbTransport GetSmbTransport(UniAddress address, int port
)
{ {
lock (typeof(SmbTransport)) lock (typeof(SmbTransport))
{ {
return GetSmbTransport(address, return GetSmbTransport(address, port, SmbConstants.Laddr, SmbConstants.Lport, null);
port,
SmbConstants.Laddr,
SmbConstants.Lport,
null);
} }
} }
internal static SmbTransport GetSmbTransport(UniAddress address, internal static SmbTransport GetSmbTransport(UniAddress address, int port
int port, , IPAddress localAddr, int localPort, string hostName)
IPAddress localAddr,
int localPort,
string hostName)
{ {
lock (typeof(SmbTransport)) lock (typeof(SmbTransport))
{ {
@ -64,19 +59,18 @@ namespace SharpCifs.Smb
{ {
if (SmbConstants.SsnLimit != 1) if (SmbConstants.SsnLimit != 1)
{ {
conn = SmbConstants.Connections conn =
.FirstOrDefault(c => c.Matches(address, SmbConstants.Connections.FirstOrDefault(
port, c =>
localAddr, c.Matches(address, port, localAddr, localPort, hostName) &&
localPort, (SmbConstants.SsnLimit ==
hostName) 0 || c.Sessions.Count < SmbConstants.SsnLimit));
&& (SmbConstants.SsnLimit == 0
|| c.Sessions.Count < SmbConstants.SsnLimit));
if (conn != null) if (conn != null)
{ {
return conn; return conn;
} }
} }
conn = new SmbTransport(address, port, localAddr, localPort); conn = new SmbTransport(address, port, localAddr, localPort);
@ -86,26 +80,6 @@ namespace SharpCifs.Smb
} }
} }
/// <summary>
/// Clear All Cached Transport-Connections
/// </summary>
public static void ClearCachedConnections()
{
lock (typeof(SmbTransport))
lock (SmbConstants.Connections)
{
foreach (var transport in SmbConstants.Connections)
{
try { transport.Disconnect(true); }
catch (Exception) {}
}
SmbConstants.Connections.Clear();
}
}
internal class ServerData internal class ServerData
{ {
internal byte Flags; internal byte Flags;
@ -200,10 +174,8 @@ namespace SharpCifs.Smb
internal string TconHostName; internal string TconHostName;
internal SmbTransport(UniAddress address, internal SmbTransport(UniAddress address, int port, IPAddress localAddr, int localPort
int port, )
IPAddress localAddr,
int localPort)
{ {
Server = new ServerData(this); Server = new ServerData(this);
this.Address = address; this.Address = address;
@ -234,8 +206,7 @@ namespace SharpCifs.Smb
return ssn; return ssn;
} }
if (SmbConstants.SoTimeout > 0 if (SmbConstants.SoTimeout > 0 && SessionExpiration < (now = Runtime.CurrentTimeMillis()))
&& SessionExpiration < (now = Runtime.CurrentTimeMillis()))
{ {
SessionExpiration = now + SmbConstants.SoTimeout; SessionExpiration = now + SmbConstants.SoTimeout;
@ -251,25 +222,16 @@ namespace SharpCifs.Smb
} }
} }
internal virtual bool Matches(UniAddress address, internal virtual bool Matches(UniAddress address, int port, IPAddress localAddr,
int port, int localPort, string hostName)
IPAddress localAddr,
int localPort,
string hostName)
{ {
if (hostName == null) if (hostName == null)
{ {
hostName = address.GetHostName(); hostName = address.GetHostName();
} }
return (TconHostName == null return (TconHostName == null || Runtime.EqualsIgnoreCase(hostName, TconHostName)) && address.Equals(this.Address) && (port == -1 || port == this.Port
|| Runtime.EqualsIgnoreCase(hostName, TconHostName)) || (port == 445 && this.Port == 139)) && (localAddr == this.LocalAddr || (localAddr
&& address.Equals(this.Address) != null && localAddr.Equals(this.LocalAddr))) && localPort == this.LocalPort;
&& (port == -1
|| port == this.Port
|| (port == 445 && this.Port == 139))
&& (localAddr == this.LocalAddr
|| (localAddr != null && localAddr.Equals(this.LocalAddr)))
&& localPort == this.LocalPort;
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
@ -288,36 +250,31 @@ namespace SharpCifs.Smb
internal virtual bool IsSignatureSetupRequired(NtlmPasswordAuthentication auth) internal virtual bool IsSignatureSetupRequired(NtlmPasswordAuthentication auth)
{ {
return (Flags2 & SmbConstants.Flags2SecuritySignatures) != 0 return (Flags2 & SmbConstants.Flags2SecuritySignatures) != 0 && Digest ==
&& Digest == null null && auth != NtlmPasswordAuthentication.Null && NtlmPasswordAuthentication.Null
&& auth != NtlmPasswordAuthentication.Null .Equals(auth) == false;
&& NtlmPasswordAuthentication.Null.Equals(auth) == false;
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal virtual void Ssn139() internal virtual void Ssn139()
{ {
Name calledName = new Name(Address.FirstCalledName(), 0x20, null); Name calledName = new Name(Address.FirstCalledName(), 0x20, null
);
do do
{ {
Socket = new SocketEx(AddressFamily.InterNetwork, Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketType.Stream, if (LocalAddr != null)
ProtocolType.Tcp); {
Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort));
//TCPローカルポートは、毎回空いているものを使う。 }
//https://blogs.msdn.microsoft.com/dgorti/2005/09/18/only-one-usage-of-each-socket-address-protocolnetwork-addressport-is-normally-permitted/
Socket.Bind(new IPEndPoint(LocalAddr, 0));
Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()),
139),
SmbConstants.ConnTimeout);
Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()), 139), SmbConstants.ConnTimeout);
Socket.SoTimeOut = SmbConstants.SoTimeout; Socket.SoTimeOut = SmbConstants.SoTimeout;
Out = Socket.GetOutputStream(); Out = Socket.GetOutputStream();
In = Socket.GetInputStream(); In = Socket.GetInputStream();
SessionServicePacket ssp = new SessionRequestPacket(calledName, SessionServicePacket ssp = new SessionRequestPacket(calledName, NbtAddress.GetLocalName
NbtAddress.GetLocalName()); ());
Out.Write(Sbuf, 0, ssp.WriteWireFormat(Sbuf, 0)); Out.Write(Sbuf, 0, ssp.WriteWireFormat(Sbuf, 0));
if (Readn(In, Sbuf, 0, 4) < 4) if (Readn(In, Sbuf, 0, 4) < 4)
{ {
@ -360,8 +317,7 @@ namespace SharpCifs.Smb
default: default:
{ {
Disconnect(true); Disconnect(true);
throw new NbtException(NbtException.ErrSsnSrvc, throw new NbtException(NbtException.ErrSsnSrvc, errorCode);
errorCode);
} }
} }
break; break;
@ -370,8 +326,8 @@ namespace SharpCifs.Smb
case -1: case -1:
{ {
Disconnect(true); Disconnect(true);
throw new NbtException(NbtException.ErrSsnSrvc, throw new NbtException(NbtException.ErrSsnSrvc, NbtException.ConnectionRefused
NbtException.ConnectionRefused); );
} }
default: default:
@ -401,18 +357,13 @@ namespace SharpCifs.Smb
port = SmbConstants.DefaultPort; port = SmbConstants.DefaultPort;
} }
// 445 // 445
Socket = new SocketEx(AddressFamily.InterNetwork, Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketType.Stream, if (LocalAddr != null)
ProtocolType.Tcp); {
Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort));
//TCPローカルポートは、毎回空いているものを使う。 }
//https://blogs.msdn.microsoft.com/dgorti/2005/09/18/only-one-usage-of-each-socket-address-protocolnetwork-addressport-is-normally-permitted/
Socket.Bind(new IPEndPoint(LocalAddr, 0));
Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()),
port), // <- 445
SmbConstants.ConnTimeout);
Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()), port), SmbConstants.ConnTimeout);
Socket.SoTimeOut = SmbConstants.SoTimeout; Socket.SoTimeOut = SmbConstants.SoTimeout;
Out = Socket.GetOutputStream(); Out = Socket.GetOutputStream();
In = Socket.GetInputStream(); In = Socket.GetInputStream();
@ -479,28 +430,21 @@ namespace SharpCifs.Smb
} }
catch (ConnectException) catch (ConnectException)
{ {
Port = (Port == -1 || Port == SmbConstants.DefaultPort) Port = (Port == -1 || Port == SmbConstants.DefaultPort) ? 139 : SmbConstants.DefaultPort;
? 139
: SmbConstants.DefaultPort;
Negotiate(Port, resp); Negotiate(Port, resp);
} }
if (resp.DialectIndex > 10) if (resp.DialectIndex > 10)
{ {
throw new SmbException("This client does not support the negotiated dialect."); throw new SmbException("This client does not support the negotiated dialect.");
} }
if ( if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) != SmbConstants.CapExtendedSecurity && Server
(Server.Capabilities & SmbConstants.CapExtendedSecurity) .EncryptionKeyLength != 8 && SmbConstants.LmCompatibility == 0)
!= SmbConstants.CapExtendedSecurity
&& Server.EncryptionKeyLength != 8
&& SmbConstants.LmCompatibility == 0
)
{ {
throw new SmbException("Unexpected encryption key length: " throw new SmbException("Unexpected encryption key length: " + Server.EncryptionKeyLength
+ Server.EncryptionKeyLength); );
} }
TconHostName = Address.GetHostName(); TconHostName = Address.GetHostName();
if (Server.SignaturesRequired if (Server.SignaturesRequired || (Server.SignaturesEnabled && SmbConstants.Signpref))
|| (Server.SignaturesEnabled && SmbConstants.Signpref))
{ {
Flags2 |= SmbConstants.Flags2SecuritySignatures; Flags2 |= SmbConstants.Flags2SecuritySignatures;
} }
@ -515,8 +459,7 @@ namespace SharpCifs.Smb
} }
SndBufSize = Math.Min(SndBufSize, Server.MaxBufferSize); SndBufSize = Math.Min(SndBufSize, Server.MaxBufferSize);
Capabilities &= Server.Capabilities; Capabilities &= Server.Capabilities;
if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == SmbConstants.CapExtendedSecurity)
== SmbConstants.CapExtendedSecurity)
{ {
Capabilities |= SmbConstants.CapExtendedSecurity; Capabilities |= SmbConstants.CapExtendedSecurity;
} }
@ -551,7 +494,6 @@ namespace SharpCifs.Smb
//Socket.`Close` method deleted //Socket.`Close` method deleted
//Socket.Close(); //Socket.Close();
Socket.Shutdown(SocketShutdown.Both);
Socket.Dispose(); Socket.Dispose();
} }
finally finally
@ -633,8 +575,8 @@ namespace SharpCifs.Smb
{ {
Log.WriteLine(smb); Log.WriteLine(smb);
} }
while (smb is AndXServerMessageBlock while (smb is AndXServerMessageBlock && (smb = ((AndXServerMessageBlock)smb).Andx
&& (smb = ((AndXServerMessageBlock)smb).Andx) != null); ) != null);
if (Log.Level >= 6) if (Log.Level >= 6)
{ {
Hexdump.ToHexdump(Log, Buf, 4, n); Hexdump.ToHexdump(Log, Buf, 4, n);
@ -674,9 +616,7 @@ namespace SharpCifs.Smb
{ {
ServerMessageBlock resp = (ServerMessageBlock)response; ServerMessageBlock resp = (ServerMessageBlock)response;
resp.UseUnicode = UseUnicode; resp.UseUnicode = UseUnicode;
resp.ExtendedSecurity resp.ExtendedSecurity = (Capabilities & SmbConstants.CapExtendedSecurity) == SmbConstants.CapExtendedSecurity;
= (Capabilities & SmbConstants.CapExtendedSecurity)
== SmbConstants.CapExtendedSecurity;
lock (Buf) lock (Buf)
{ {
Array.Copy(Sbuf, 0, Buf, 0, 4 + SmbConstants.HeaderLength); Array.Copy(Sbuf, 0, Buf, 0, 4 + SmbConstants.HeaderLength);
@ -686,10 +626,8 @@ namespace SharpCifs.Smb
throw new IOException("Invalid payload size: " + size); throw new IOException("Invalid payload size: " + size);
} }
int errorCode = Encdec.Dec_uint32le(Buf, 9) & unchecked((int)(0xFFFFFFFF)); int errorCode = Encdec.Dec_uint32le(Buf, 9) & unchecked((int)(0xFFFFFFFF));
if (resp.Command == ServerMessageBlock.SmbComReadAndx if (resp.Command == ServerMessageBlock.SmbComReadAndx && (errorCode == 0 || errorCode
&& (errorCode == 0 == unchecked((int)(0x80000005))))
|| errorCode == unchecked((int)(0x80000005)))
)
{ {
// overflow indicator normal for pipe // overflow indicator normal for pipe
SmbComReadAndXResponse r = (SmbComReadAndXResponse)resp; SmbComReadAndXResponse r = (SmbComReadAndXResponse)resp;
@ -746,7 +684,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual void CheckStatus(ServerMessageBlock req, ServerMessageBlock resp) internal virtual void CheckStatus(ServerMessageBlock req, ServerMessageBlock resp
)
{ {
resp.ErrorCode = SmbException.GetStatusByCode(resp.ErrorCode); resp.ErrorCode = SmbException.GetStatusByCode(resp.ErrorCode);
switch (resp.ErrorCode) switch (resp.ErrorCode)
@ -807,7 +746,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response) internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response
)
{ {
Connect(); Connect();
request.Flags2 |= Flags2; request.Flags2 |= Flags2;
@ -869,8 +809,7 @@ namespace SharpCifs.Smb
timeout = resp.Expiration - Runtime.CurrentTimeMillis(); timeout = resp.Expiration - Runtime.CurrentTimeMillis();
if (timeout <= 0) if (timeout <= 0)
{ {
throw new TransportException( throw new TransportException(this + " timedout waiting for response to " + req);
this + " timedout waiting for response to " + req);
} }
} }
if (response.ErrorCode != 0) if (response.ErrorCode != 0)
@ -952,9 +891,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual DfsReferral GetDfsReferrals(NtlmPasswordAuthentication auth, internal virtual DfsReferral GetDfsReferrals(NtlmPasswordAuthentication auth, string
string path, path, int rn)
int rn)
{ {
SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null); SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null);
Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse(); Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();
@ -1001,8 +939,7 @@ namespace SharpCifs.Smb
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual DfsReferral[] __getDfsReferrals(NtlmPasswordAuthentication auth, internal virtual DfsReferral[] __getDfsReferrals(NtlmPasswordAuthentication auth,
string path, string path, int rn)
int rn)
{ {
SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null); SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null);
Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse(); Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();

View File

@ -56,10 +56,9 @@ namespace SharpCifs.Smb
internal virtual bool Matches(string share, string service) internal virtual bool Matches(string share, string service)
{ {
return Runtime.EqualsIgnoreCase(this.Share, share) return Runtime.EqualsIgnoreCase(this.Share, share) && (service == null ||
&& (service == null service.StartsWith("??") || Runtime.EqualsIgnoreCase(this.Service, service
|| service.StartsWith("??") ));
|| Runtime.EqualsIgnoreCase(this.Service, service));
} }
public override bool Equals(object obj) public override bool Equals(object obj)
@ -73,7 +72,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response) internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response
)
{ {
lock (Session.Transport()) lock (Session.Transport())
{ {
@ -103,8 +103,7 @@ namespace SharpCifs.Smb
case ServerMessageBlock.SmbComTransaction: case ServerMessageBlock.SmbComTransaction:
case ServerMessageBlock.SmbComTransaction2: case ServerMessageBlock.SmbComTransaction2:
{ {
switch (((SmbComTransaction)request).SubCommand switch (((SmbComTransaction)request).SubCommand & unchecked(0xFF))
& unchecked(0xFF))
{ {
case SmbComTransaction.NetShareEnum: case SmbComTransaction.NetShareEnum:
case SmbComTransaction.NetServerEnum2: case SmbComTransaction.NetServerEnum2:
@ -120,8 +119,7 @@ namespace SharpCifs.Smb
default: default:
{ {
throw new SmbException( throw new SmbException("Invalid operation for " + Service + " service");
"Invalid operation for " + Service + " service");
} }
} }
break; break;
@ -129,19 +127,15 @@ namespace SharpCifs.Smb
default: default:
{ {
throw new SmbException( throw new SmbException("Invalid operation for " + Service + " service" + request);
"Invalid operation for " + Service + " service" + request);
} }
} }
} }
request.Tid = Tid; request.Tid = Tid;
if (InDfs if (InDfs && !Service.Equals("IPC") && !string.IsNullOrEmpty(request.Path))
&& !Service.Equals("IPC")
&& !string.IsNullOrEmpty(request.Path))
{ {
request.Flags2 = SmbConstants.Flags2ResolvePathsInDfs; request.Flags2 = SmbConstants.Flags2ResolvePathsInDfs;
request.Path = '\\' + Session.Transport().TconHostName request.Path = '\\' + Session.Transport().TconHostName + '\\' + Share + request.Path;
+ '\\' + Share + request.Path;
} }
try try
{ {
@ -159,8 +153,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual void TreeConnect(ServerMessageBlock andx, internal virtual void TreeConnect(ServerMessageBlock andx, ServerMessageBlock andxResponse
ServerMessageBlock andxResponse) )
{ {
lock (Session.Transport()) lock (Session.Transport())
{ {
@ -190,14 +184,13 @@ namespace SharpCifs.Smb
Service = Service0; Service = Service0;
if (Session.transport.Log.Level >= 4) if (Session.transport.Log.Level >= 4)
{ {
Session.transport.Log.WriteLine( Session.transport.Log.WriteLine("treeConnect: unc=" + unc + ",service=" + Service
"treeConnect: unc=" + unc );
+ ",service=" + Service);
} }
SmbComTreeConnectAndXResponse response SmbComTreeConnectAndXResponse response = new SmbComTreeConnectAndXResponse(andxResponse
= new SmbComTreeConnectAndXResponse(andxResponse); );
SmbComTreeConnectAndX request SmbComTreeConnectAndX request = new SmbComTreeConnectAndX(Session, unc, Service,
= new SmbComTreeConnectAndX(Session, unc, Service, andx); andx);
Session.Send(request, response); Session.Send(request, response);
Tid = response.Tid; Tid = response.Tid;
Service = response.Service; Service = response.Service;
@ -249,12 +242,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbTree[share=" + Share return "SmbTree[share=" + Share + ",service=" + Service + ",tid=" + Tid + ",inDfs="
+ ",service=" + Service + InDfs + ",inDomainDfs=" + InDomainDfs + ",connectionState=" + ConnectionState
+ ",tid=" + Tid + "]";
+ ",inDfs=" + InDfs
+ ",inDomainDfs=" + InDomainDfs
+ ",connectionState=" + ConnectionState + "]";
} }
} }
} }

View File

@ -58,11 +58,11 @@ namespace SharpCifs.Smb
internal const int SmbFileBothDirectoryInfo = unchecked(0x104); internal const int SmbFileBothDirectoryInfo = unchecked(0x104);
internal static readonly int ListSize internal static readonly int ListSize = Config.GetInt("jcifs.smb.client.listSize"
= Config.GetInt("jcifs.smb.client.listSize", DefaultListSize); , DefaultListSize);
internal static readonly int ListCount internal static readonly int ListCount = Config.GetInt("jcifs.smb.client.listCount"
= Config.GetInt("jcifs.smb.client.listCount", DefaultListCount); , DefaultListCount);
internal Trans2FindFirst2(string filename, string wildcard, int searchAttributes) internal Trans2FindFirst2(string filename, string wildcard, int searchAttributes)
{ {
@ -117,14 +117,14 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{ {
return 0; return 0;
} }
internal override int ReadParametersWireFormat(byte[] buffer, internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
int bufferIndex, len)
int len)
{ {
return 0; return 0;
} }
@ -136,14 +136,11 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "Trans2FindFirst2[" return "Trans2FindFirst2[" + base.ToString() + ",searchAttributes=0x"
+ base.ToString() + Hexdump.ToHexString(_searchAttributes, 2) + ",searchCount=" + ListCount + ",flags=0x"
+ ",searchAttributes=0x" + Hexdump.ToHexString(_searchAttributes, 2) + Hexdump.ToHexString(_flags, 2) + ",informationLevel=0x" + Hexdump.ToHexString(
+ ",searchCount=" + ListCount _informationLevel, 3) + ",searchStorageType=" + _searchStorageType + ",filename="
+ ",flags=0x" + Hexdump.ToHexString(_flags, 2) + Path + "]";
+ ",informationLevel=0x" + Hexdump.ToHexString(_informationLevel, 3)
+ ",searchStorageType=" + _searchStorageType
+ ",filename=" + Path + "]";
} }
} }
} }

View File

@ -98,21 +98,15 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbFindFileBothDirectoryInfo[" return "SmbFindFileBothDirectoryInfo[" + "nextEntryOffset=" + NextEntryOffset
+ "nextEntryOffset=" + NextEntryOffset + ",fileIndex=" + FileIndex + ",creationTime=" + Extensions.CreateDate
+ ",fileIndex=" + FileIndex (CreationTime) + ",lastAccessTime=" + Extensions.CreateDate(LastAccessTime
+ ",creationTime=" + Extensions.CreateDate(CreationTime) ) + ",lastWriteTime=" + Extensions.CreateDate(LastWriteTime) + ",changeTime="
+ ",lastAccessTime=" + Extensions.CreateDate(LastAccessTime) + Extensions.CreateDate(ChangeTime) + ",endOfFile=" + EndOfFile
+ ",lastWriteTime=" + Extensions.CreateDate(LastWriteTime) + ",allocationSize=" + AllocationSize + ",extFileAttributes=" + ExtFileAttributes
+ ",changeTime=" + Extensions.CreateDate(ChangeTime) + ",fileNameLength=" + FileNameLength + ",eaSize=" + EaSize + ",shortNameLength="
+ ",endOfFile=" + EndOfFile + ShortNameLength + ",shortName=" + ShortName + ",filename=" + Filename
+ ",allocationSize=" + AllocationSize + "]";
+ ",extFileAttributes=" + ExtFileAttributes
+ ",fileNameLength=" + FileNameLength
+ ",eaSize=" + EaSize
+ ",shortNameLength=" + ShortNameLength
+ ",shortName=" + ShortName
+ ",filename=" + Filename + "]";
} }
internal SmbFindFileBothDirectoryInfo(Trans2FindFirst2Response enclosing) internal SmbFindFileBothDirectoryInfo(Trans2FindFirst2Response enclosing)
@ -151,10 +145,7 @@ namespace SharpCifs.Smb
if (UseUnicode) if (UseUnicode)
{ {
// should Unicode alignment be corrected for here? // should Unicode alignment be corrected for here?
str = Runtime.GetStringForBytes(src, str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.UniEncoding);
srcIndex,
len,
SmbConstants.UniEncoding);
} }
else else
{ {
@ -162,10 +153,8 @@ namespace SharpCifs.Smb
{ {
len--; len--;
} }
str = Runtime.GetStringForBytes(src, str = Runtime.GetStringForBytes(src, srcIndex, len, SmbConstants.OemEncoding
srcIndex, );
len,
SmbConstants.OemEncoding);
} }
} }
catch (UnsupportedEncodingException uee) catch (UnsupportedEncodingException uee)
@ -193,14 +182,14 @@ namespace SharpCifs.Smb
return 0; return 0;
} }
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len) internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{ {
return 0; return 0;
} }
internal override int ReadParametersWireFormat(byte[] buffer, internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
int bufferIndex, len)
int len)
{ {
int start = bufferIndex; int start = bufferIndex;
if (SubCommand == Smb.SmbComTransaction.Trans2FindFirst2) if (SubCommand == Smb.SmbComTransaction.Trans2FindFirst2)
@ -210,9 +199,7 @@ namespace SharpCifs.Smb
} }
NumEntries = ReadInt2(buffer, bufferIndex); NumEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2; bufferIndex += 2;
IsEndOfSearch = (buffer[bufferIndex] & unchecked(0x01)) == unchecked(0x01) IsEndOfSearch = (buffer[bufferIndex] & unchecked(0x01)) == unchecked(0x01) ? true : false;
? true
: false;
bufferIndex += 2; bufferIndex += 2;
EaErrorOffset = ReadInt2(buffer, bufferIndex); EaErrorOffset = ReadInt2(buffer, bufferIndex);
bufferIndex += 2; bufferIndex += 2;
@ -244,9 +231,8 @@ namespace SharpCifs.Smb
// e.shortNameLength = buffer[bufferIndex + 68] & 0xFF; // e.shortNameLength = buffer[bufferIndex + 68] & 0xFF;
// e.shortName = readString( buffer, bufferIndex + 70, e.shortNameLength ); // e.shortName = readString( buffer, bufferIndex + 70, e.shortNameLength );
e.Filename = ReadString(buffer, bufferIndex + 94, e.FileNameLength); e.Filename = ReadString(buffer, bufferIndex + 94, e.FileNameLength);
if (LastNameBufferIndex >= bufferIndex if (LastNameBufferIndex >= bufferIndex && (e.NextEntryOffset == 0 || LastNameBufferIndex
&& (e.NextEntryOffset == 0 < (bufferIndex + e.NextEntryOffset)))
|| LastNameBufferIndex < (bufferIndex + e.NextEntryOffset)))
{ {
LastName = e.Filename; LastName = e.Filename;
ResumeKey = e.FileIndex; ResumeKey = e.FileIndex;
@ -268,13 +254,9 @@ namespace SharpCifs.Smb
{ {
c = "Trans2FindNext2Response["; c = "Trans2FindNext2Response[";
} }
return c + base.ToString() return c + base.ToString() + ",sid=" + Sid + ",searchCount=" + NumEntries
+ ",sid=" + Sid + ",isEndOfSearch=" + IsEndOfSearch + ",eaErrorOffset=" + EaErrorOffset + ",lastNameOffset="
+ ",searchCount=" + NumEntries + LastNameOffset + ",lastName=" + LastName + "]";
+ ",isEndOfSearch=" + IsEndOfSearch
+ ",eaErrorOffset=" + EaErrorOffset
+ ",lastNameOffset=" + LastNameOffset
+ ",lastName=" + LastName + "]";
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show More