Merge pull request #2739 from MediaBrowser/beta

Beta
This commit is contained in:
Luke 2017-07-01 12:24:26 -04:00 committed by GitHub
commit ff3713153a
471 changed files with 30774 additions and 27108 deletions

View File

@ -32,7 +32,8 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL"> <Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.4.4.10\lib\net45\NLog.dll</HintPath> <HintPath>..\packages\NLog.4.4.11\lib\net45\NLog.dll</HintPath>
<Private>True</Private>
</Reference> </Reference>
<Reference Include="ServiceStack.Text, Version=4.5.8.0, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="ServiceStack.Text, Version=4.5.8.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\ServiceStack.Text.4.5.8\lib\net45\ServiceStack.Text.dll</HintPath> <HintPath>..\packages\ServiceStack.Text.4.5.8\lib\net45\ServiceStack.Text.dll</HintPath>
@ -227,6 +228,7 @@
<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" />
@ -317,6 +319,23 @@
<Compile Include="ScheduledTasks\WeeklyTrigger.cs" /> <Compile Include="ScheduledTasks\WeeklyTrigger.cs" />
<Compile Include="Serialization\JsonSerializer.cs" /> <Compile Include="Serialization\JsonSerializer.cs" />
<Compile Include="Serialization\XmlSerializer.cs" /> <Compile Include="Serialization\XmlSerializer.cs" />
<Compile Include="TextEncoding\NLangDetect\Detector.cs" />
<Compile Include="TextEncoding\NLangDetect\DetectorFactory.cs" />
<Compile Include="TextEncoding\NLangDetect\ErrorCode.cs" />
<Compile Include="TextEncoding\NLangDetect\Extensions\CharExtensions.cs" />
<Compile Include="TextEncoding\NLangDetect\Extensions\RandomExtensions.cs" />
<Compile Include="TextEncoding\NLangDetect\Extensions\StringExtensions.cs" />
<Compile Include="TextEncoding\NLangDetect\Extensions\UnicodeBlock.cs" />
<Compile Include="TextEncoding\NLangDetect\GenProfile.cs" />
<Compile Include="TextEncoding\NLangDetect\InternalException.cs" />
<Compile Include="TextEncoding\NLangDetect\Language.cs" />
<Compile Include="TextEncoding\NLangDetect\LanguageDetector.cs" />
<Compile Include="TextEncoding\NLangDetect\NLangDetectException.cs" />
<Compile Include="TextEncoding\NLangDetect\ProbVector.cs" />
<Compile Include="TextEncoding\NLangDetect\Utils\LangProfile.cs" />
<Compile Include="TextEncoding\NLangDetect\Utils\Messages.cs" />
<Compile Include="TextEncoding\NLangDetect\Utils\NGram.cs" />
<Compile Include="TextEncoding\NLangDetect\Utils\TagExtractor.cs" />
<Compile Include="TextEncoding\TextEncoding.cs" /> <Compile Include="TextEncoding\TextEncoding.cs" />
<Compile Include="TextEncoding\TextEncodingDetect.cs" /> <Compile Include="TextEncoding\TextEncodingDetect.cs" />
<Compile Include="TextEncoding\UniversalDetector\CharsetDetector.cs" /> <Compile Include="TextEncoding\UniversalDetector\CharsetDetector.cs" />
@ -368,7 +387,62 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="packages.config" /> <None Include="packages.config" />
<None Include="TextEncoding\NLangDetect\Profiles\afr" />
<None Include="TextEncoding\NLangDetect\Profiles\ara" />
<None Include="TextEncoding\NLangDetect\Profiles\bul" />
<None Include="TextEncoding\NLangDetect\Profiles\ben" />
<None Include="TextEncoding\NLangDetect\Profiles\ces" />
<None Include="TextEncoding\NLangDetect\Profiles\dan" />
<None Include="TextEncoding\NLangDetect\Profiles\deu" />
<None Include="TextEncoding\NLangDetect\Profiles\ell" />
<None Include="TextEncoding\NLangDetect\Profiles\eng" />
<None Include="TextEncoding\NLangDetect\Profiles\spa" />
<None Include="TextEncoding\NLangDetect\Profiles\est" />
<None Include="TextEncoding\NLangDetect\Profiles\fas" />
<None Include="TextEncoding\NLangDetect\Profiles\fin" />
<None Include="TextEncoding\NLangDetect\Profiles\fra" />
<None Include="TextEncoding\NLangDetect\Profiles\guj" />
<None Include="TextEncoding\NLangDetect\Profiles\heb" />
<None Include="TextEncoding\NLangDetect\Profiles\hin" />
<None Include="TextEncoding\NLangDetect\Profiles\hrv" />
<None Include="TextEncoding\NLangDetect\Profiles\hun" />
<None Include="TextEncoding\NLangDetect\Profiles\ind" />
<None Include="TextEncoding\NLangDetect\Profiles\ita" />
<None Include="TextEncoding\NLangDetect\Profiles\jpn" />
<None Include="TextEncoding\NLangDetect\Profiles\kan" />
<None Include="TextEncoding\NLangDetect\Profiles\kor" />
<None Include="TextEncoding\NLangDetect\Profiles\lit" />
<None Include="TextEncoding\NLangDetect\Profiles\lav" />
<None Include="TextEncoding\NLangDetect\Profiles\mkd" />
<None Include="TextEncoding\NLangDetect\Profiles\mal" />
<None Include="TextEncoding\NLangDetect\Profiles\mar" />
<None Include="TextEncoding\NLangDetect\Profiles\nep" />
<None Include="TextEncoding\NLangDetect\Profiles\nld" />
<None Include="TextEncoding\NLangDetect\Profiles\nor" />
<None Include="TextEncoding\NLangDetect\Profiles\pan" />
<None Include="TextEncoding\NLangDetect\Profiles\pol" />
<None Include="TextEncoding\NLangDetect\Profiles\por" />
<None Include="TextEncoding\NLangDetect\Profiles\ron" />
<None Include="TextEncoding\NLangDetect\Profiles\rus" />
<None Include="TextEncoding\NLangDetect\Profiles\slk" />
<None Include="TextEncoding\NLangDetect\Profiles\slv" />
<None Include="TextEncoding\NLangDetect\Profiles\som" />
<None Include="TextEncoding\NLangDetect\Profiles\sqi" />
<None Include="TextEncoding\NLangDetect\Profiles\swe" />
<None Include="TextEncoding\NLangDetect\Profiles\swa" />
<None Include="TextEncoding\NLangDetect\Profiles\tam" />
<None Include="TextEncoding\NLangDetect\Profiles\tel" />
<None Include="TextEncoding\NLangDetect\Profiles\tha" />
<None Include="TextEncoding\NLangDetect\Profiles\tgl" />
<None Include="TextEncoding\NLangDetect\Profiles\tur" />
<None Include="TextEncoding\NLangDetect\Profiles\ukr" />
<None Include="TextEncoding\NLangDetect\Profiles\urd" />
<None Include="TextEncoding\NLangDetect\Profiles\vie" />
<EmbeddedResource Include="TextEncoding\NLangDetect\Profiles\zh-cn" />
<EmbeddedResource Include="TextEncoding\NLangDetect\Profiles\zh-tw" />
<EmbeddedResource Include="TextEncoding\NLangDetect\Utils\messages.properties" />
</ItemGroup> </ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -21,14 +21,17 @@ namespace SharpCifs.Dcerpc
{ {
public class DcerpcBind : DcerpcMessage public class DcerpcBind : DcerpcMessage
{ {
internal static readonly string[] ResultMessage = { "0", "DCERPC_BIND_ERR_ABSTRACT_SYNTAX_NOT_SUPPORTED" internal static readonly string[] ResultMessage =
, "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,7 +103,8 @@ 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();
@ -115,7 +116,8 @@ namespace SharpCifs.Dcerpc
} }
} }
ret += "]"; ret += "]";
return ret; */ return ret;
*/
return null; return null;
} }
} }

View File

@ -18,8 +18,7 @@ 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,13 +36,29 @@ namespace SharpCifs.Dcerpc
public static int DcerpcFaultProtoError = unchecked(0x1c01000b); public static int DcerpcFaultProtoError = unchecked(0x1c01000b);
public static int[] DcerpcFaultCodes = { DcerpcFaultOther, DcerpcFaultAccessDenied public static int[] DcerpcFaultCodes = {
, DcerpcFaultCantPerform, DcerpcFaultNdr, DcerpcFaultInvalidTag, DcerpcFaultContextMismatch DcerpcFaultOther,
, DcerpcFaultOpRngError, DcerpcFaultUnkIf, DcerpcFaultProtoError }; DcerpcFaultAccessDenied,
DcerpcFaultCantPerform,
DcerpcFaultNdr,
DcerpcFaultInvalidTag,
DcerpcFaultContextMismatch,
DcerpcFaultOpRngError,
DcerpcFaultUnkIf,
DcerpcFaultProtoError
};
public static string[] DcerpcFaultMessages = { "DCERPC_FAULT_OTHER" public static string[] DcerpcFaultMessages =
, "DCERPC_FAULT_ACCESS_DENIED", "DCERPC_FAULT_CANT_PERFORM", "DCERPC_FAULT_NDR", {
"DCERPC_FAULT_INVALID_TAG", "DCERPC_FAULT_CONTEXT_MISMATCH", "DCERPC_FAULT_OP_RNG_ERROR" "DCERPC_FAULT_OTHER",
, "DCERPC_FAULT_UNK_IF", "DCERPC_FAULT_PROTO_ERROR" }; "DCERPC_FAULT_ACCESS_DENIED",
"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,8 +213,10 @@ namespace SharpCifs.Dcerpc
{ {
msg.Flags &= ~DcerpcConstants.DcerpcFirstFrag; msg.Flags &= ~DcerpcConstants.DcerpcFirstFrag;
} }
if ((msg.Flags & (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag)) != (DcerpcConstants.DcerpcFirstFrag | if (
DcerpcConstants.DcerpcLastFrag)) (msg.Flags & (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag))
!= (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag)
)
{ {
buf.Start = off; buf.Start = off;
buf.Reset(); buf.Reset();
@ -315,8 +317,7 @@ 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, protected internal abstract void DoSendFragment(byte[] buf, int off, int length, bool isDirect);
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,8 +38,7 @@ 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 url = "smb://" + Binding.Server + "/IPC$/" + Runtime.Substring(Binding.Endpoint, 6);
, 6);
string @params = string.Empty; string @params = string.Empty;
string server; string server;
string address; string address;
@ -57,13 +56,15 @@ namespace SharpCifs.Dcerpc
{ {
url += "?" + Runtime.Substring(@params, 1); url += "?" + Runtime.Substring(@params, 1);
} }
Pipe = new SmbNamedPipe(url, (unchecked(0x2019F) << 16) | SmbNamedPipe.PipeTypeRdwr Pipe = new SmbNamedPipe(url,
| SmbNamedPipe.PipeTypeDceTransact, auth); (unchecked(0x2019F) << 16)
| 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, protected internal override void DoSendFragment(byte[] buf, int off, int length, bool isDirect)
bool isDirect)
{ {
if (Out != null && Out.IsOpen() == false) if (Out != null && Out.IsOpen() == false)
{ {

View File

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

View File

@ -18,8 +18,11 @@ 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, new Lsarpc.LsarObjectAttributes(), access, policyHandle) : base(server,
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 public MsrpcQueryInformationPolicy(LsaPolicyHandle policyHandle, short level, NdrObject info)
info) : base(policyHandle, level, 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,8 +18,11 @@ namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcSamrOpenAlias : Samr.SamrOpenAlias public class MsrpcSamrOpenAlias : Samr.SamrOpenAlias
{ {
public MsrpcSamrOpenAlias(SamrDomainHandle handle, int access, int rid, SamrAliasHandle public MsrpcSamrOpenAlias(SamrDomainHandle handle,
aliasHandle) : base(handle, access, rid, aliasHandle) int access,
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,8 +18,11 @@ namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcSamrOpenDomain : Samr.SamrOpenDomain public class MsrpcSamrOpenDomain : Samr.SamrOpenDomain
{ {
public MsrpcSamrOpenDomain(SamrPolicyHandle handle, int access, Rpc.SidT sid, SamrDomainHandle public MsrpcSamrOpenDomain(SamrPolicyHandle handle,
domainHandle) : base(handle, access, sid, domainHandle) int access,
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) : base("\\\\" + server, 1, new Srvsvc.ShareInfoCtr1 public MsrpcShareEnum(string server)
(), -1, 0, 0) : base("\\\\" + server, 1, new Srvsvc.ShareInfoCtr1(), -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) : base(server, sharename public MsrpcShareGetInfo(string server, string sharename)
, 502, new Srvsvc.ShareInfo502()) : base(server, sharename, 502, new Srvsvc.ShareInfo502())
{ {
Ptype = 0; Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;

View File

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

View File

@ -21,8 +21,10 @@ 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, SamrDomainHandle domainHandle, int access public SamrAliasHandle(DcerpcHandle handle,
, int rid) SamrDomainHandle domainHandle,
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,11 +21,12 @@ 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, SamrPolicyHandle policyHandle, int access public SamrDomainHandle(DcerpcHandle handle,
, Rpc.SidT sid) SamrPolicyHandle policyHandle,
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,8 +430,12 @@ namespace SharpCifs.Dcerpc.Msrpc
public int ResumeHandle; public int ResumeHandle;
public ShareEnumAll(string servername, int level, NdrObject info, int prefmaxlen, public ShareEnumAll(string servername,
int totalentries, int resumeHandle) int level,
NdrObject info,
int prefmaxlen,
int totalentries,
int resumeHandle)
{ {
this.Servername = servername; this.Servername = servername;
this.Level = level; this.Level = level;
@ -500,8 +504,7 @@ 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,8 +214,7 @@ namespace SharpCifs.Dcerpc.Ndr
i += 4; i += 4;
try try
{ {
Array.Copy(Runtime.GetBytesForString(s, "UTF-16LE"), 0, Buf, i, len Array.Copy(Runtime.GetBytesForString(s, "UTF-16LE"), 0, Buf, i, len * 2);
* 2);
} }
catch (UnsupportedEncodingException) catch (UnsupportedEncodingException)
{ {

View File

@ -78,8 +78,12 @@ namespace SharpCifs.Dcerpc
return value; return value;
} }
internal static readonly char[] Hexchars = { '0', '1', '2', '3', '4', internal static readonly char[] Hexchars =
'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)
{ {
@ -138,11 +142,17 @@ namespace SharpCifs.Dcerpc
public override string ToString() public override string ToString()
{ {
return Bin_to_hex(TimeLow, 8) + '-' + Bin_to_hex(TimeMid, 4) + '-' + Bin_to_hex return Bin_to_hex(TimeLow, 8)
(TimeHiAndVersion, 4) + '-' + Bin_to_hex(ClockSeqHiAndReserved, 2) + Bin_to_hex + '-' + Bin_to_hex(TimeMid, 4)
(ClockSeqLow, 2) + '-' + Bin_to_hex(Node[0], 2) + Bin_to_hex(Node[1], 2) + Bin_to_hex + '-' + Bin_to_hex(TimeHiAndVersion, 4)
(Node[2], 2) + Bin_to_hex(Node[3], 2) + Bin_to_hex(Node[4], 2) + Bin_to_hex(Node + '-' + Bin_to_hex(ClockSeqHiAndReserved, 2)
[5], 2); + Bin_to_hex(ClockSeqLow, 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,8 +23,7 @@ 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 = Config.GetProperty("jcifs.netbios.scope" private static readonly string DefaultScope
); = Config.GetProperty("jcifs.netbios.scope");
internal static readonly string OemEncoding = Config.GetProperty("jcifs.encoding" internal static readonly string OemEncoding
, Runtime.GetProperty("file.encoding")); = Config.GetProperty("jcifs.encoding", Runtime.GetProperty("file.encoding"));
public string name; public string name;
@ -69,19 +69,20 @@ 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)] = unchecked((byte)(((tmp[i] & unchecked(0xF0)) dst[dstIndex + (2 * i + 1)]
>> 4) + unchecked(0x41))); = unchecked((byte)(((tmp[i] & unchecked(0xF0)) >> 4) + unchecked(0x41)));
dst[dstIndex + (2 * i + 2)] = unchecked((byte)((tmp[i] & unchecked(0x0F)) dst[dstIndex + (2 * i + 2)]
+ unchecked(0x41))); = unchecked((byte)((tmp[i] & unchecked(0x0F)) + 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] = unchecked((byte)(((HexCode & unchecked(0xF0) dst[dstIndex + TypeOffset]
) >> 4) + unchecked(0x41))); = unchecked((byte)(((HexCode & unchecked(0xF0)) >> 4) + unchecked(0x41)));
dst[dstIndex + TypeOffset + 1] = unchecked((byte)((HexCode & unchecked(0x0F)) + unchecked(0x41))); dst[dstIndex + TypeOffset + 1]
= unchecked((byte)((HexCode & unchecked(0x0F)) + unchecked(0x41)));
} }
catch (UnsupportedEncodingException) catch (UnsupportedEncodingException)
{ {
@ -95,10 +96,17 @@ 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((byte)(((src[srcIndex + (2 * i + 1)] & unchecked(0xFF)) tmp[i] = unchecked(
- unchecked(0x41)) << 4)); (byte)(
tmp[i] |= unchecked((byte)(((src[srcIndex + (2 * i + 2)] & unchecked(0xFF) ((src[srcIndex + (2 * i + 1)] & unchecked(0xFF)) - unchecked(0x41)) << 4
) - 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;
@ -113,8 +121,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( HexCode |= ((src[srcIndex + TypeOffset + 1] & unchecked(0xFF)) - unchecked(0x41))
0x41)) & unchecked(0x0F); & unchecked(0x0F);
return ScopeOffset + ReadScopeWireFormat(src, srcIndex + ScopeOffset); return ScopeOffset + ReadScopeWireFormat(src, srcIndex + ScopeOffset);
} }
@ -130,9 +138,8 @@ namespace SharpCifs.Netbios
{ {
name = Runtime.GetStringForBytes(tmp, 0, length).Trim(); name = Runtime.GetStringForBytes(tmp, 0, length).Trim();
} }
catch (Exception ex) catch (Exception)
{ {
} }
HexCode = src[srcIndex + length]; HexCode = src[srcIndex + length];
@ -152,8 +159,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,8 +61,7 @@ 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,10 +21,13 @@ 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
{ {
@ -48,27 +51,29 @@ namespace SharpCifs.Netbios
internal const int ResolverWins = 3; internal const int ResolverWins = 3;
private static readonly int SndBufSize = Config.GetInt("jcifs.netbios.snd_buf_size" private static readonly int SndBufSize
, DefaultSndBufSize); = Config.GetInt("jcifs.netbios.snd_buf_size", DefaultSndBufSize);
private static readonly int RcvBufSize = Config.GetInt("jcifs.netbios.rcv_buf_size" private static readonly int RcvBufSize
, DefaultRcvBufSize); = Config.GetInt("jcifs.netbios.rcv_buf_size", DefaultRcvBufSize);
private static readonly int SoTimeout = Config.GetInt("jcifs.netbios.soTimeout", private static readonly int SoTimeout
DefaultSoTimeout); = Config.GetInt("jcifs.netbios.soTimeout", DefaultSoTimeout);
private static readonly int RetryCount = Config.GetInt("jcifs.netbios.retryCount" private static readonly int RetryCount
, DefaultRetryCount); = Config.GetInt("jcifs.netbios.retryCount", DefaultRetryCount);
private static readonly int RetryTimeout = Config.GetInt("jcifs.netbios.retryTimeout" private static readonly int RetryTimeout
, DefaultRetryTimeout); = Config.GetInt("jcifs.netbios.retryTimeout", DefaultRetryTimeout);
private static readonly int Lport = Config.GetInt("jcifs.netbios.lport", 137); private static readonly int Lport
= Config.GetInt("jcifs.netbios.lport", 137);
private static readonly IPAddress Laddr = Config.GetInetAddress("jcifs.netbios.laddr" private static readonly IPAddress Laddr
, null); = Config.GetInetAddress("jcifs.netbios.laddr", null);
private static readonly string Ro = Config.GetProperty("jcifs.resolveOrder"); private static readonly string Ro
= Config.GetProperty("jcifs.resolveOrder");
private static LogStream _log = LogStream.GetInstance(); private static LogStream _log = LogStream.GetInstance();
@ -82,7 +87,7 @@ namespace SharpCifs.Netbios
private byte[] _rcvBuf; private byte[] _rcvBuf;
private SocketEx _socket; private SocketEx _socketSender;
private Hashtable _responseTable = new Hashtable(); private Hashtable _responseTable = new Hashtable();
@ -94,6 +99,8 @@ 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;
@ -111,11 +118,15 @@ namespace SharpCifs.Netbios
this.laddr = laddr this.laddr = laddr
?? Config.GetLocalHost() ?? Config.GetLocalHost()
?? Extensions.GetAddressesByName(Dns.GetHostName()).FirstOrDefault(); ?? Extensions.GetLocalAddresses()?.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", Extensions.GetAddressByName("255.255.255.255")); Baddr = Config.GetInetAddress("jcifs.netbios.baddr",
Extensions.GetAddressByName("255.255.255.255"));
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -161,8 +172,8 @@ namespace SharpCifs.Netbios
{ {
if (_log.Level > 1) if (_log.Level > 1)
{ {
_log.WriteLine("NetBIOS resolveOrder specifies WINS however the " + "jcifs.netbios.wins property has not been set" _log.WriteLine("NetBIOS resolveOrder specifies WINS however the "
); + "jcifs.netbios.wins property has not been set");
} }
continue; continue;
} }
@ -208,53 +219,93 @@ 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 (_socket == null) if (
_socketSender == null
|| _socketSender.LocalEndPoint == null
|| _socketSender.GetLocalPort() != localPort
|| !IPAddress.Any.Equals(_socketSender.GetLocalInetAddress())
)
{ {
_socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); if (_socketSender != null)
{
_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)
{ {
_thread = new Thread(this); //new Sharpen.Thread(this, "JCIFS-NameServiceClient"); if (_thread != null)
{
_thread.Cancel(true);
_thread.Dispose();
}
_thread = new Thread(this);
_thread.SetDaemon(true); _thread.SetDaemon(true);
_thread.Start(); _thread.Start(true);
} }
} }
} }
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 (_socket != null) if (_socketSender != null)
{ {
//Socket.`Close` method deleted _socketSender.Dispose();
//_socket.Close(); _socketSender = null;
_socket.Dispose(); //Log.Out("NameSerciceClient.TryClose - _socketSender.Disposed");
_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;
@ -262,12 +313,38 @@ namespace SharpCifs.Netbios
try try
{ {
while (Thread.CurrentThread().Equals(_thread))
while (_thread == Thread.CurrentThread())
{ {
_socket.SoTimeOut = _closeTimeout; if (_thread.IsCanceled)
break;
int len = _socket.Receive(_rcvBuf, 0, RcvBufSize); var localPort = (SmbConstants.Lport == 0) ? _lport : SmbConstants.Lport;
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)
{ {
@ -284,12 +361,15 @@ 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, len); Hexdump.ToHexdump(_log, _rcvBuf, 0, this._recievedLength);
} }
if (response.IsResponse) if (response.IsResponse)
@ -300,7 +380,6 @@ namespace SharpCifs.Netbios
} }
} }
} }
} }
catch (TimeoutException) { } catch (TimeoutException) { }
catch (Exception ex) catch (Exception ex)
@ -316,10 +395,21 @@ 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, NameServicePacket response, internal virtual void Send(NameServicePacket request,
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)
@ -329,6 +419,7 @@ namespace SharpCifs.Netbios
lock (response) lock (response)
{ {
this._isActive = true;
while (max-- > 0) while (max-- > 0)
{ {
@ -338,45 +429,75 @@ 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);
_socket.Send(_sndBuf, 0, requestLenght, new IPEndPoint(request.Addr, _lport)); byte[] msg = new byte[requestLenght];
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)
@ -393,17 +514,24 @@ 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;
@ -440,10 +568,12 @@ 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)
{ {
int n; //Log.Out("NameSerciceClient.GetByName");
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;
@ -463,7 +593,9 @@ 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;
@ -471,9 +603,11 @@ 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
@ -496,7 +630,8 @@ namespace SharpCifs.Netbios
case ResolverWins: case ResolverWins:
case ResolverBcast: case ResolverBcast:
{ {
if (_resolveOrder[i] == ResolverWins && name.name != NbtAddress.MasterBrowserName if (_resolveOrder[i] == ResolverWins
&& name.name != NbtAddress.MasterBrowserName
&& name.HexCode != unchecked(0x1d)) && name.HexCode != unchecked(0x1d))
{ {
request.Addr = NbtAddress.GetWinsAddress(); request.Addr = NbtAddress.GetWinsAddress();
@ -522,11 +657,12 @@ 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)
{ {
response.AddrEntry[0].HostName.SrcHashCode
response.AddrEntry[0].HostName.SrcHashCode = request.Addr.GetHashCode(); = request.Addr.GetHashCode();
return response.AddrEntry[0]; return response.AddrEntry[0];
} }
if (_resolveOrder[i] == ResolverWins) if (_resolveOrder[i] == ResolverWins)
@ -542,12 +678,15 @@ 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;
@ -556,6 +695,7 @@ 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
@ -585,6 +725,8 @@ namespace SharpCifs.Netbios
internal virtual NbtAddress[] GetHosts() internal virtual NbtAddress[] GetHosts()
{ {
//Log.Out("NbtServiceClient.GetHosts");
try try
{ {
_waitResponse = false; _waitResponse = false;
@ -593,6 +735,8 @@ 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;
@ -605,19 +749,27 @@ namespace SharpCifs.Netbios
IPAddress addr = new IPAddress(addrBytes); IPAddress addr = new IPAddress(addrBytes);
//response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName, response = new NodeStatusResponse(
// (int)addr.Address, false, 0x20)); new NbtAddress(NbtAddress.UnknownName,
response = new NodeStatusResponse(new NbtAddress(NbtAddress.UnknownName, BitConverter.ToInt32(addr.GetAddressBytes(), 0),
BitConverter.ToInt32(addr.GetAddressBytes(), 0) , false, 0x20)); false,
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);
@ -626,28 +778,30 @@ 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(); _thread.Start(true);
_autoResetWaitReceive.WaitOne(); _autoResetWaitReceive.WaitOne();
List<NbtAddress> result = new List<NbtAddress>(); var result = new List<NbtAddress>();
foreach (var key in _responseTable.Keys) foreach (var key in _responseTable.Keys)
{ {
NodeStatusResponse resp = (NodeStatusResponse)_responseTable[key]; var 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
if (entry.HostName.HexCode == 0x20) .Where(entry => entry.HostName.HexCode == 0x20));
{
result.Add(entry);
}
}
}
} }
_responseTable.Clear(); _responseTable.Clear();

View File

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

View File

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

View File

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

View File

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

View File

@ -47,8 +47,7 @@ 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,8 +37,7 @@ 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,22 +54,24 @@ 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) + (src[srcIndex + 1] & unchecked( return ((src[srcIndex] & unchecked(0xFF)) << 8)
0xFF)); + (src[srcIndex + 1] & unchecked(0xFF));
} }
internal static int ReadInt4(byte[] src, int srcIndex) internal static int ReadInt4(byte[] src, int srcIndex)
{ {
return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked( return ((src[srcIndex] & unchecked(0xFF)) << 24)
0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src + ((src[srcIndex + 1] & unchecked(0xFF)) << 16)
[srcIndex + 3] & unchecked(0xFF)); + ((src[srcIndex + 2] & unchecked(0xFF)) << 8)
+ (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) + ((src[srcIndex++] & unchecked( return ((src[srcIndex++] & unchecked(0x01)) << 16)
0xFF)) << 8) + (src[srcIndex++] & unchecked(0xFF)); + ((src[srcIndex++] & unchecked(0xFF)) << 8)
+ (src[srcIndex++] & unchecked(0xFF));
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
@ -90,8 +92,7 @@ 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)
@ -118,8 +119,7 @@ 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,19 +138,17 @@ 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) + ReadInt2(buffer Length = ((buffer[bufferIndex] & unchecked(0x01)) << 16)
, bufferIndex + 1); + ReadInt2(buffer, 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,8 +170,7 @@ 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,10 +24,17 @@ 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 = { unchecked( protected internal static readonly byte[] NtlmsspSignature =
(byte)('N')), unchecked((byte)('T')), unchecked((byte)('L')), {
unchecked((byte)('M')), unchecked((byte)('S')), unchecked((byte unchecked((byte)('N')),
)('S')), unchecked((byte)('P')), unchecked(0) }; unchecked((byte)('T')),
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;
@ -75,14 +82,17 @@ namespace SharpCifs.Ntlmssp
/// </param> /// </param>
public virtual void SetFlag(int flag, bool value) public virtual void SetFlag(int flag, bool value)
{ {
SetFlags(value ? (GetFlags() | flag) : (GetFlags() & (unchecked((int)(0xffffffff) SetFlags(value
) ^ flag))); ? (GetFlags() | 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)) | ((src[index + 1] & unchecked(0xff)) << 8) | ((src[index + 2] & unchecked(0xff)) << 16) | ((src[index return (src[index] & unchecked(0xff))
+ 3] & unchecked(0xff)) << 24); | ((src[index + 1] & unchecked(0xff)) << 8)
| ((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)
@ -113,10 +123,14 @@ 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, int offset, int bodyOffset, internal static void WriteSecurityBuffer(byte[] dest,
int offset,
int bodyOffset,
byte[] src) byte[] src)
{ {
int length = (src != null) ? src.Length : 0; int length = (src != null)
? src.Length
: 0;
if (length == 0) if (length == 0)
{ {
return; return;

View File

@ -38,8 +38,9 @@ namespace SharpCifs.Ntlmssp
static Type1Message() static Type1Message()
{ {
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode" DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode", true)
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem); ? NtlmsspNegotiateUnicode
: 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
@ -60,8 +61,9 @@ 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(), GetDefaultDomain(), GetDefaultWorkstation public Type1Message() : this(GetDefaultFlags(),
()) GetDefaultDomain(),
GetDefaultWorkstation())
{ {
} }
@ -84,7 +86,8 @@ 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">If an error occurs while parsing the material. /// <exception cref="System.IO.IOException">
/// If an error occurs while parsing the material.
/// </exception> /// </exception>
public Type1Message(byte[] material) public Type1Message(byte[] material)
{ {
@ -136,8 +139,8 @@ namespace SharpCifs.Ntlmssp
{ {
hostInfo = true; hostInfo = true;
flags |= NtlmsspNegotiateOemDomainSupplied; flags |= NtlmsspNegotiateOemDomainSupplied;
domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(), GetOemEncoding domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(),
()); GetOemEncoding());
} }
else else
{ {
@ -148,16 +151,16 @@ namespace SharpCifs.Ntlmssp
{ {
hostInfo = true; hostInfo = true;
flags |= NtlmsspNegotiateOemWorkstationSupplied; flags |= NtlmsspNegotiateOemWorkstationSupplied;
workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(), GetOemEncoding workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(),
()); GetOemEncoding());
} }
else else
{ {
flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff)));
)));
} }
byte[] type1 = new byte[hostInfo ? (32 + domain.Length + workstation.Length) : 16 byte[] type1 = new byte[hostInfo
]; ? (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);
@ -178,9 +181,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>
@ -238,8 +241,7 @@ 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,8 +42,9 @@ namespace SharpCifs.Ntlmssp
static Type2Message() static Type2Message()
{ {
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode" DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode", true)
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem); ? NtlmsspNegotiateUnicode
: 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)
@ -76,8 +77,13 @@ namespace SharpCifs.Ntlmssp
{ {
} }
int serverLength = server.Length; int serverLength = server.Length;
byte[] targetInfo = new byte[(domainLength > 0 ? domainLength + 4 : 0) + (serverLength byte[] targetInfo = new byte[(domainLength > 0
> 0 ? serverLength + 4 : 0) + 4]; ? domainLength + 4
: 0)
+ (serverLength > 0
? serverLength + 4
: 0)
+ 4];
int offset = 0; int offset = 0;
if (domainLength > 0) if (domainLength > 0)
{ {
@ -129,9 +135,14 @@ 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, byte[] challenge, string target) : this(GetDefaultFlags public Type2Message(Type1Message type1,
(type1), challenge, (type1 != null && target == null && type1.GetFlag(NtlmsspRequestTarget byte[] challenge,
)) ? GetDefaultDomain() : target) string target)
: this(GetDefaultFlags(type1),
challenge,
(type1 != null && target == null && type1.GetFlag(NtlmsspRequestTarget))
? GetDefaultDomain()
: target)
{ {
} }
@ -254,9 +265,9 @@ namespace SharpCifs.Ntlmssp
{ {
if (!string.IsNullOrEmpty(targetName)) if (!string.IsNullOrEmpty(targetName))
{ {
target = (flags & NtlmsspNegotiateUnicode) != 0 ? Runtime.GetBytesForString target = (flags & NtlmsspNegotiateUnicode) != 0
(targetName, UniEncoding) : Runtime.GetBytesForString(targetName.ToUpper ? Runtime.GetBytesForString(targetName, UniEncoding)
(), GetOemEncoding()); : Runtime.GetBytesForString(targetName.ToUpper(), GetOemEncoding());
} }
else else
{ {
@ -281,8 +292,11 @@ namespace SharpCifs.Ntlmssp
{ {
data += 8; data += 8;
} }
byte[] type2 = new byte[data + target.Length + (targetInformation != null ? targetInformation byte[] type2 = new byte[data
.Length : 0)]; + target.Length
+ (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);
@ -310,11 +324,17 @@ 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 + ",challenge=" + (challenge == null ? "null" return "Type2Message[target=" + target
: "<" + challenge.Length + " bytes>") + ",context=" + (context == null ? "null" + ",challenge=" + (challenge == null
: "<" + context.Length + " bytes>") + ",targetInformation=" + (targetInformation ? "null"
== null ? "null" : "<" + targetInformation.Length + " bytes>") + ",flags=0x" + : "<" + challenge.Length + " bytes>")
Hexdump.ToHexString(GetFlags(), 8) + "]"; + ",context=" + (context == null
? "null"
: "<" + context.Length + " bytes>")
+ ",targetInformation=" + (targetInformation == null
? "null"
: "<" + targetInformation.Length + " bytes>")
+ ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
} }
/// <summary> /// <summary>
@ -348,7 +368,8 @@ namespace SharpCifs.Ntlmssp
} }
int flags = NtlmsspNegotiateNtlm; int flags = NtlmsspNegotiateNtlm;
int type1Flags = type1.GetFlags(); int type1Flags = type1.GetFlags();
flags |= ((type1Flags & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode flags |= ((type1Flags & NtlmsspNegotiateUnicode) != 0)
? NtlmsspNegotiateUnicode
: NtlmsspNegotiateOem; : NtlmsspNegotiateOem;
if ((type1Flags & NtlmsspRequestTarget) != 0) if ((type1Flags & NtlmsspRequestTarget) != 0)
{ {
@ -394,8 +415,10 @@ 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, ((flags & NtlmsspNegotiateUnicode target = Runtime.GetStringForBytes(bytes,
) != 0) ? UniEncoding : GetOemEncoding()); ((flags & NtlmsspNegotiateUnicode) != 0)
? UniEncoding
: GetOemEncoding());
} }
SetTarget(target); SetTarget(target);
for (int i1 = 24; i1 < 32; i1++) for (int i1 = 24; i1 < 32; i1++)

View File

@ -59,8 +59,9 @@ namespace SharpCifs.Ntlmssp
static Type3Message() static Type3Message()
{ {
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode" DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode", true)
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem); ? NtlmsspNegotiateUnicode
: 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);
@ -157,8 +158,12 @@ 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, string password, string domain, string user public Type3Message(Type2Message type2,
, string workstation, int flags) string password,
string domain,
string user,
string workstation,
int flags)
{ {
SetFlags(flags | GetDefaultFlags(type2)); SetFlags(flags | GetDefaultFlags(type2));
if (workstation == null) if (workstation == null)
@ -185,9 +190,12 @@ 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 = NtlmPasswordAuthentication.NtowFv1(password); byte[] responseKeyNt
byte[] ntlm2Response = NtlmPasswordAuthentication.GetNtlm2Response(responseKeyNt, = NtlmPasswordAuthentication.NtowFv1(password);
type2.GetChallenge(), clientChallenge); byte[] ntlm2Response
= NtlmPasswordAuthentication.GetNtlm2Response(responseKeyNt,
type2.GetChallenge(),
clientChallenge);
SetLmResponse(clientChallenge); SetLmResponse(clientChallenge);
SetNtResponse(ntlm2Response); SetNtResponse(ntlm2Response);
if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign) if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign)
@ -232,8 +240,8 @@ namespace SharpCifs.Ntlmssp
case 4: case 4:
case 5: case 5:
{ {
byte[] responseKeyNt1 = NtlmPasswordAuthentication.NtowFv2(domain, user, password byte[] responseKeyNt1
); = 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));
@ -284,8 +292,12 @@ 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, byte[] lmResponse, byte[] ntResponse, string domain public Type3Message(int flags,
, string user, string workstation) byte[] lmResponse,
byte[] ntResponse,
string domain,
string user,
string workstation)
{ {
SetFlags(flags); SetFlags(flags);
SetLmResponse(lmResponse); SetLmResponse(lmResponse);
@ -421,39 +433,61 @@ namespace SharpCifs.Ntlmssp
{ {
int flags = GetFlags(); int flags = GetFlags();
bool unicode = (flags & NtlmsspNegotiateUnicode) != 0; bool unicode = (flags & NtlmsspNegotiateUnicode) != 0;
string oem = unicode ? null : GetOemEncoding(); string oem = unicode
? null
: GetOemEncoding();
string domainName = GetDomain(); string domainName = GetDomain();
byte[] domain = null; byte[] domain = null;
if (!string.IsNullOrEmpty(domainName)) if (!string.IsNullOrEmpty(domainName))
{ {
domain = unicode ? Runtime.GetBytesForString(domainName, UniEncoding) : domain = unicode
Runtime.GetBytesForString(domainName, oem); ? Runtime.GetBytesForString(domainName, UniEncoding)
: Runtime.GetBytesForString(domainName, oem);
} }
int domainLength = (domain != null) ? domain.Length : 0; int domainLength = (domain != null)
? 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 ? Runtime.GetBytesForString(userName, UniEncoding) : Runtime.GetBytesForString user = unicode
(userName.ToUpper(), oem); ? Runtime.GetBytesForString(userName, UniEncoding)
: Runtime.GetBytesForString(userName.ToUpper(), oem);
} }
int userLength = (user != null) ? user.Length : 0; int userLength = (user != null)
? 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 ? Runtime.GetBytesForString(workstationName, UniEncoding workstation = unicode
) : Runtime.GetBytesForString(workstationName.ToUpper(), oem); ? Runtime.GetBytesForString(workstationName, UniEncoding)
: Runtime.GetBytesForString(workstationName.ToUpper(), oem);
} }
int workstationLength = (workstation != null) ? workstation.Length : 0; int workstationLength = (workstation != null)
? workstation.Length
: 0;
byte[] lmResponse = GetLMResponse(); byte[] lmResponse = GetLMResponse();
int lmLength = (lmResponse != null) ? lmResponse.Length : 0; int lmLength = (lmResponse != null)
? lmResponse.Length
: 0;
byte[] ntResponse = GetNTResponse(); byte[] ntResponse = GetNTResponse();
int ntLength = (ntResponse != null) ? ntResponse.Length : 0; int ntLength = (ntResponse != null)
? ntResponse.Length
: 0;
byte[] sessionKey = GetSessionKey(); byte[] sessionKey = GetSessionKey();
int keyLength = (sessionKey != null) ? sessionKey.Length : 0; int keyLength = (sessionKey != null)
byte[] type3 = new byte[64 + domainLength + userLength + workstationLength + lmLength ? sessionKey.Length
+ ntLength + keyLength]; : 0;
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;
@ -485,11 +519,19 @@ 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 + ",user=" + user + ",workstation=" + workstation return "Type3Message[domain=" + domain
+ ",lmResponse=" + (lmResponse == null ? "null" : "<" + lmResponse.Length + " bytes>" + ",user=" + user
) + ",ntResponse=" + (ntResponse == null ? "null" : "<" + ntResponse.Length + " bytes>" + ",workstation=" + workstation
) + ",sessionKey=" + (sessionKey == null ? "null" : "<" + sessionKey.Length + " bytes>" + ",lmResponse=" + (lmResponse == null
) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]"; ? "null"
: "<" + 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>
@ -522,7 +564,8 @@ namespace SharpCifs.Ntlmssp
return DefaultFlags; return DefaultFlags;
} }
int flags = NtlmsspNegotiateNtlm; int flags = NtlmsspNegotiateNtlm;
flags |= ((type2.GetFlags() & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode flags |= ((type2.GetFlags() & NtlmsspNegotiateUnicode) != 0)
? NtlmsspNegotiateUnicode
: NtlmsspNegotiateOem; : NtlmsspNegotiateOem;
return flags; return flags;
} }
@ -544,33 +587,47 @@ namespace SharpCifs.Ntlmssp
{ {
return null; return null;
} }
return NtlmPasswordAuthentication.GetPreNtlmResponse(password, type2.GetChallenge return NtlmPasswordAuthentication.GetPreNtlmResponse(password,
()); type2.GetChallenge());
} }
public static byte[] GetLMv2Response(Type2Message type2, string domain, string user public static byte[] GetLMv2Response(Type2Message type2,
, string password, byte[] clientChallenge) string domain,
string user,
string password,
byte[] clientChallenge)
{ {
if (type2 == null || domain == null || user == null || password == null || clientChallenge if (type2 == null
== null) || domain == null
|| user == null
|| password == null
|| clientChallenge == null)
{ {
return null; return null;
} }
return NtlmPasswordAuthentication.GetLMv2Response(domain, user, password, type2.GetChallenge return NtlmPasswordAuthentication.GetLMv2Response(domain,
(), clientChallenge); user,
password,
type2.GetChallenge(),
clientChallenge);
} }
public static byte[] GetNtlMv2Response(Type2Message type2, byte[] responseKeyNt, public static byte[] GetNtlMv2Response(Type2Message type2,
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() + MillisecondsBetween1970And1601 long nanos1601 = (Runtime.CurrentTimeMillis()
) * 10000L; + MillisecondsBetween1970And1601)
return NtlmPasswordAuthentication.GetNtlMv2Response(responseKeyNt, type2.GetChallenge * 10000L;
(), clientChallenge, nanos1601, type2.GetTargetInformation()); return NtlmPasswordAuthentication.GetNtlMv2Response(responseKeyNt,
type2.GetChallenge(),
clientChallenge,
nanos1601,
type2.GetTargetInformation());
} }
/// <summary> /// <summary>
@ -652,8 +709,11 @@ namespace SharpCifs.Ntlmssp
int flags; int flags;
string charset; string charset;
byte[] _sessionKey = null; byte[] _sessionKey = null;
if (lmResponseOffset == 52 || ntResponseOffset == 52 || domainOffset == 52 || userOffset if (lmResponseOffset == 52
== 52 || workstationOffset == 52) || ntResponseOffset == 52
|| domainOffset == 52
|| userOffset == 52
|| workstationOffset == 52)
{ {
flags = NtlmsspNegotiateNtlm | NtlmsspNegotiateOem; flags = NtlmsspNegotiateNtlm | NtlmsspNegotiateOem;
charset = GetOemEncoding(); charset = GetOemEncoding();
@ -662,8 +722,9 @@ namespace SharpCifs.Ntlmssp
{ {
_sessionKey = ReadSecurityBuffer(material, 52); _sessionKey = ReadSecurityBuffer(material, 52);
flags = ReadULong(material, 60); flags = ReadULong(material, 60);
charset = ((flags & NtlmsspNegotiateUnicode) != 0) ? UniEncoding : GetOemEncoding charset = ((flags & NtlmsspNegotiateUnicode) != 0)
(); ? 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,8 +181,7 @@ 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):
{ {
@ -276,10 +275,14 @@ namespace SharpCifs.Smb
int i; int i;
string str; string str;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.Append(IsAllow() ? "Allow " : "Deny "); sb.Append(IsAllow()
? "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() ? "Inherited " : "Direct "); sb.Append(IsInherited()
? "Inherited "
: "Direct ");
AppendCol(sb, GetApplyToText(), 34); AppendCol(sb, GetApplyToText(), 34);
return sb.ToString(); return sb.ToString();
} }

View File

@ -86,8 +86,9 @@ 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 || SmbConstants.UseBatching == false || BatchLevel >= GetBatchLimit(Andx.Command if (Andx == null
)) || SmbConstants.UseBatching == false
|| BatchLevel >= GetBatchLimit(Andx.Command))
{ {
_andxCommand = unchecked(unchecked(0xFF)); _andxCommand = unchecked(unchecked(0xFF));
Andx = null; Andx = null;
@ -109,8 +110,7 @@ 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,8 +123,7 @@ 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;
@ -185,13 +184,12 @@ 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)
@ -214,8 +212,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return base.ToString() + ",andxCommand=0x" + Hexdump.ToHexString(_andxCommand return base.ToString()
, 2) + ",andxOffset=" + _andxOffset; + ",andxCommand=0x" + Hexdump.ToHexString(_andxCommand, 2)
+ ",andxOffset=" + _andxOffset;
} }
} }
} }

View File

@ -18,8 +18,7 @@ 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];
@ -48,8 +47,7 @@ namespace SharpCifs.Smb
} }
} }
internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse rsp)
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 = Config.GetBoolean("jcifs.smb.client.dfs.strictView" internal static readonly bool StrictView
, false); = Config.GetBoolean("jcifs.smb.client.dfs.strictView", false);
internal static readonly long Ttl = Config.GetLong("jcifs.smb.client.dfs.ttl", 300 internal static readonly long Ttl
); = Config.GetLong("jcifs.smb.client.dfs.ttl", 300);
internal static readonly bool Disabled = Config.GetBoolean("jcifs.smb.client.dfs.disabled" internal static readonly bool Disabled
, false); = Config.GetBoolean("jcifs.smb.client.dfs.disabled", false);
internal static CacheEntry FalseEntry = new CacheEntry(0L); internal static CacheEntry FalseEntry = new CacheEntry(0L);
@ -106,8 +106,7 @@ 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)
@ -166,8 +165,11 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception> /// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual DfsReferral GetReferral(SmbTransport trans, string domain, string public virtual DfsReferral GetReferral(SmbTransport trans,
root, string path, NtlmPasswordAuthentication auth) string domain,
string root,
string path,
NtlmPasswordAuthentication auth)
{ {
if (Disabled) if (Disabled)
{ {
@ -201,8 +203,10 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception> /// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual DfsReferral Resolve(string domain, string root, string path, NtlmPasswordAuthentication public virtual DfsReferral Resolve(string domain,
auth) string root,
string path,
NtlmPasswordAuthentication auth)
{ {
lock (this) lock (this)
{ {

View File

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

View File

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

View File

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

View File

@ -28,7 +28,7 @@ namespace SharpCifs.Smb
Command = SmbComTransaction; Command = SmbComTransaction;
SubCommand = NetShareEnum; SubCommand = NetShareEnum;
// not really true be used by upper logic // not really true be used by upper logic
Name ="\\PIPE\\LANMAN"; Name = "\\PIPE\\LANMAN";
MaxParameterCount = 8; MaxParameterCount = 8;
// maxDataCount = 4096; why was this set? // maxDataCount = 4096; why was this set?
MaxSetupCount = 0x00; MaxSetupCount = 0x00;
@ -70,14 +70,12 @@ 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 internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len)
len)
{ {
return 0; return 0;
} }

View File

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

View File

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

View File

@ -38,14 +38,12 @@ 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 internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len)
len)
{ {
Length = ReadInt4(buffer, bufferIndex); Length = ReadInt4(buffer, bufferIndex);
return 4; return 4;

View File

@ -16,9 +16,11 @@
// 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>This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials. /// <summary>
/// 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>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>
/// 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
{ {
@ -35,7 +37,8 @@ namespace SharpCifs.Smb
} }
/// <summary>Set the default <tt>NtlmAuthenticator</tt>.</summary> /// <summary>Set the default <tt>NtlmAuthenticator</tt>.</summary>
/// <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. /// <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.
/// </remarks> /// </remarks>
public static void SetDefault(NtlmAuthenticator a) public static void SetDefault(NtlmAuthenticator a)
{ {
@ -59,12 +62,14 @@ namespace SharpCifs.Smb
return _sae; return _sae;
} }
/// <summary>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials. /// <summary>
/// Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
/// </summary> /// </summary>
/// <remarks>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials. /// <remarks>
/// Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
/// </remarks> /// </remarks>
public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string url,
url, SmbAuthException sae) SmbAuthException sae)
{ {
if (_auth == null) if (_auth == null)
{ {
@ -84,8 +89,7 @@ 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 return "NtlmChallenge[challenge=0x" + Hexdump.ToHexString(Challenge, 0, Challenge.Length * 2)
.Length * 2) + ",dc=" + Dc + "]"; + ",dc=" + Dc + "]";
} }
} }
} }

View File

@ -47,11 +47,14 @@ namespace SharpCifs.Smb
public NtlmContext(NtlmPasswordAuthentication auth, bool doSigning) public NtlmContext(NtlmPasswordAuthentication auth, bool doSigning)
{ {
this.Auth = auth; this.Auth = auth;
NtlmsspFlags = NtlmsspFlags | NtlmFlags.NtlmsspRequestTarget | NtlmFlags.NtlmsspNegotiateNtlm2 NtlmsspFlags = NtlmsspFlags
| NtlmFlags.NtlmsspRequestTarget
| NtlmFlags.NtlmsspNegotiateNtlm2
| NtlmFlags.NtlmsspNegotiate128; | NtlmFlags.NtlmsspNegotiate128;
if (doSigning) if (doSigning)
{ {
NtlmsspFlags |= NtlmFlags.NtlmsspNegotiateSign | NtlmFlags.NtlmsspNegotiateAlwaysSign NtlmsspFlags |= NtlmFlags.NtlmsspNegotiateSign
| NtlmFlags.NtlmsspNegotiateAlwaysSign
| NtlmFlags.NtlmsspNegotiateKeyExch; | NtlmFlags.NtlmsspNegotiateKeyExch;
} }
Workstation = Type1Message.GetDefaultWorkstation(); Workstation = Type1Message.GetDefaultWorkstation();
@ -60,9 +63,12 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
string ret = "NtlmContext[auth=" + Auth + ",ntlmsspFlags=0x" + Hexdump.ToHexString string ret = "NtlmContext[auth=" + Auth
(NtlmsspFlags, 8) + ",workstation=" + Workstation + ",isEstablished=" + isEstablished + ",ntlmsspFlags=0x" + Hexdump.ToHexString(NtlmsspFlags, 8)
+ ",state=" + State + ",serverChallenge="; + ",workstation=" + Workstation
+ ",isEstablished=" + isEstablished
+ ",state=" + State
+ ",serverChallenge=";
if (ServerChallenge == null) if (ServerChallenge == null)
{ {
ret += "null"; ret += "null";
@ -107,7 +113,7 @@ namespace SharpCifs.Smb
private string GetNtlmsspListItem(byte[] type2Token, int id0) private string GetNtlmsspListItem(byte[] type2Token, int id0)
{ {
int ri = 58; int ri = 58;
for (; ; ) for (;;)
{ {
int id = Encdec.Dec_uint16le(type2Token, ri); int id = Encdec.Dec_uint16le(type2Token, ri);
int len = Encdec.Dec_uint16le(type2Token, ri + 2); int len = Encdec.Dec_uint16le(type2Token, ri + 2);
@ -120,8 +126,10 @@ namespace SharpCifs.Smb
{ {
try try
{ {
return Runtime.GetStringForBytes(type2Token, ri, len, SmbConstants.UniEncoding return Runtime.GetStringForBytes(type2Token,
); ri,
len,
SmbConstants.UniEncoding);
} }
catch (UnsupportedEncodingException) catch (UnsupportedEncodingException)
{ {
@ -140,7 +148,9 @@ namespace SharpCifs.Smb
{ {
case 1: case 1:
{ {
Type1Message msg1 = new Type1Message(NtlmsspFlags, Auth.GetDomain(), Workstation); Type1Message msg1 = new Type1Message(NtlmsspFlags,
Auth.GetDomain(),
Workstation);
token = msg1.ToByteArray(); token = msg1.ToByteArray();
if (Log.Level >= 4) if (Log.Level >= 4)
{ {
@ -169,9 +179,13 @@ 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, Auth.GetPassword(), Auth.GetDomain(), Type3Message msg3 = new Type3Message(msg2,
Auth.GetUsername(), Workstation, NtlmsspFlags); Auth.GetPassword(),
Auth.GetDomain(),
Auth.GetUsername(),
Workstation,
NtlmsspFlags);
token = msg3.ToByteArray(); token = msg3.ToByteArray();
if (Log.Level >= 4) if (Log.Level >= 4)
{ {

View File

@ -33,14 +33,24 @@ namespace SharpCifs.Smb
public sealed class NtlmPasswordAuthentication : Principal public sealed class NtlmPasswordAuthentication : Principal
{ {
private static readonly int LmCompatibility = Config.GetInt("jcifs.smb.lmCompatibility" private static readonly int LmCompatibility
, 3); = Config.GetInt("jcifs.smb.lmCompatibility", 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 = { unchecked(unchecked(0x4b)), unchecked(unchecked(0x47)), unchecked(unchecked(0x53)), unchecked(unchecked(0x21)), unchecked(unchecked(0x40)), unchecked(unchecked(0x23)), unchecked(unchecked(0x24)), unchecked(unchecked(0x25)) }; 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))
};
// KGS!@#$% // KGS!@#$%
private static void E(byte[] key, byte[] data, byte[] e) private static void E(byte[] key, byte[] data, byte[] e)
@ -64,8 +74,8 @@ namespace SharpCifs.Smb
internal static readonly string Blank = string.Empty; internal static readonly string Blank = string.Empty;
public static readonly NtlmPasswordAuthentication Anonymous = new NtlmPasswordAuthentication public static readonly NtlmPasswordAuthentication Anonymous
(string.Empty, string.Empty, string.Empty); = new NtlmPasswordAuthentication(string.Empty, string.Empty, string.Empty);
internal static void InitDefaults() internal static void InitDefaults()
{ {
@ -78,9 +88,11 @@ namespace SharpCifs.Smb
DefaultPassword = Config.GetProperty("jcifs.smb.client.password", Blank); DefaultPassword = Config.GetProperty("jcifs.smb.client.password", Blank);
} }
/// <summary>Generate the ANSI DES hash for the password associated with these credentials. /// <summary>
/// Generate the ANSI DES hash for the password associated with these credentials.
/// </summary> /// </summary>
/// <remarks>Generate the ANSI DES hash for the password associated with these credentials. /// <remarks>
/// 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)
{ {
@ -108,9 +120,11 @@ namespace SharpCifs.Smb
return p24; return p24;
} }
/// <summary>Generate the Unicode MD4 hash for the password associated with these credentials. /// <summary>
/// Generate the Unicode MD4 hash for the password associated with these credentials.
/// </summary> /// </summary>
/// <remarks>Generate the Unicode MD4 hash for the password associated with these credentials. /// <remarks>
/// 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)
{ {
@ -152,8 +166,11 @@ 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, string user, string password, public static byte[] GetLMv2Response(string domain,
byte[] challenge, byte[] clientChallenge) string user,
string password,
byte[] challenge,
byte[] clientChallenge)
{ {
try try
{ {
@ -161,13 +178,10 @@ 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);
@ -185,8 +199,9 @@ namespace SharpCifs.Smb
} }
} }
public static byte[] GetNtlm2Response(byte[] nTowFv1, byte[] serverChallenge, byte public static byte[] GetNtlm2Response(byte[] nTowFv1,
[] clientChallenge) byte[] serverChallenge,
byte[] clientChallenge)
{ {
byte[] sessionHash = new byte[8]; byte[] sessionHash = new byte[8];
try try
@ -221,8 +236,7 @@ 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)
@ -236,11 +250,9 @@ 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();
} }
@ -250,8 +262,11 @@ namespace SharpCifs.Smb
} }
} }
internal static byte[] ComputeResponse(byte[] responseKey, byte[] serverChallenge internal static byte[] ComputeResponse(byte[] responseKey,
, byte[] clientData, int offset, int length) byte[] serverChallenge,
byte[] clientData,
int offset,
int length)
{ {
Hmact64 hmac = new Hmact64(responseKey); Hmact64 hmac = new Hmact64(responseKey);
hmac.Update(serverChallenge); hmac.Update(serverChallenge);
@ -263,17 +278,26 @@ namespace SharpCifs.Smb
return ret; return ret;
} }
public static byte[] GetLMv2Response(byte[] responseKeyLm, byte[] serverChallenge public static byte[] GetLMv2Response(byte[] responseKeyLm,
, byte[] clientChallenge) byte[] serverChallenge,
byte[] clientChallenge)
{ {
return ComputeResponse(responseKeyLm, serverChallenge return ComputeResponse(responseKeyLm,
, clientChallenge, 0, clientChallenge.Length); serverChallenge,
clientChallenge,
0,
clientChallenge.Length);
} }
public static byte[] GetNtlMv2Response(byte[] responseKeyNt, byte[] serverChallenge public static byte[] GetNtlMv2Response(byte[] responseKeyNt,
, byte[] clientChallenge, long nanos1601, byte[] targetInfo) byte[] serverChallenge,
byte[] clientChallenge,
long nanos1601,
byte[] targetInfo)
{ {
int targetInfoLength = targetInfo != null ? targetInfo.Length : 0; int targetInfoLength = targetInfo != null
? 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
@ -289,18 +313,21 @@ 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, serverChallenge return ComputeResponse(responseKeyNt,
, temp, 0, temp.Length); serverChallenge,
temp,
0,
temp.Length);
} }
internal static readonly NtlmPasswordAuthentication Null = new NtlmPasswordAuthentication internal static readonly NtlmPasswordAuthentication Null
(string.Empty, string.Empty, string.Empty); = new NtlmPasswordAuthentication(string.Empty, string.Empty, string.Empty);
internal static readonly NtlmPasswordAuthentication Guest = new NtlmPasswordAuthentication internal static readonly NtlmPasswordAuthentication Guest
("?", "GUEST", string.Empty); = new NtlmPasswordAuthentication("?", "GUEST", string.Empty);
internal static readonly NtlmPasswordAuthentication Default = new NtlmPasswordAuthentication internal static readonly NtlmPasswordAuthentication Default
(null); = new NtlmPasswordAuthentication(null);
internal string Domain; internal string Domain;
@ -389,8 +416,7 @@ 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)
@ -438,10 +464,16 @@ 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, string username, byte[] challenge public NtlmPasswordAuthentication(string domain,
, byte[] ansiHash, byte[] unicodeHash) string username,
byte[] challenge,
byte[] ansiHash,
byte[] unicodeHash)
{ {
if (domain == null || username == null || ansiHash == null || unicodeHash == null) if (domain == null
|| username == null
|| ansiHash == null
|| unicodeHash == null)
{ {
throw new ArgumentException("External credentials cannot be null"); throw new ArgumentException("External credentials cannot be null");
} }
@ -497,12 +529,16 @@ 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 ? Domain + "\\" + Username : Username; return d
? Domain + "\\" + Username
: Username;
} }
/// <summary>Computes the 24 byte ANSI password hash given the 8 byte server challenge. /// <summary>
/// Computes the 24 byte ANSI password hash given the 8 byte server challenge.
/// </summary> /// </summary>
/// <remarks>Computes the 24 byte ANSI password hash given the 8 byte server challenge. /// <remarks>
/// 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)
{ {
@ -532,7 +568,11 @@ namespace SharpCifs.Smb
ClientChallenge = new byte[8]; ClientChallenge = new byte[8];
Random.NextBytes(ClientChallenge); Random.NextBytes(ClientChallenge);
} }
return GetLMv2Response(Domain, Username, Password, challenge, ClientChallenge); return GetLMv2Response(Domain,
Username,
Password,
challenge,
ClientChallenge);
} }
default: default:
@ -542,9 +582,11 @@ namespace SharpCifs.Smb
} }
} }
/// <summary>Computes the 24 byte Unicode password hash given the 8 byte server challenge. /// <summary>
/// Computes the 24 byte Unicode password hash given the 8 byte server challenge.
/// </summary> /// </summary>
/// <remarks>Computes the 24 byte Unicode password hash given the 8 byte server challenge. /// <remarks>
/// 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)
{ {
@ -594,8 +636,10 @@ namespace SharpCifs.Smb
case 4: case 4:
case 5: case 5:
{ {
throw new SmbException("NTLMv2 requires extended security (jcifs.smb.client.useExtendedSecurity must be true if jcifs.smb.lmCompatibility >= 3)" throw new SmbException(
); "NTLMv2 requires extended security "
+ "(jcifs.smb.client.useExtendedSecurity must be true "
+ "if jcifs.smb.lmCompatibility >= 3)");
} }
} }
return null; return null;
@ -650,8 +694,7 @@ 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:
@ -673,10 +716,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(), SmbConstants.UniEncoding hmac.Update(Runtime.GetBytesForString(Username.ToUpper(),
)); SmbConstants.UniEncoding));
hmac.Update(Runtime.GetBytesForString(Domain.ToUpper(), SmbConstants.UniEncoding hmac.Update(Runtime.GetBytesForString(Domain.ToUpper(),
)); SmbConstants.UniEncoding));
byte[] ntlmv2Hash = hmac.Digest(); byte[] ntlmv2Hash = hmac.Digest();
hmac = new Hmact64(ntlmv2Hash); hmac = new Hmact64(ntlmv2Hash);
hmac.Update(challenge); hmac.Update(challenge);
@ -714,16 +757,15 @@ namespace SharpCifs.Smb
{ {
if (obj is NtlmPasswordAuthentication) if (obj is NtlmPasswordAuthentication)
{ {
NtlmPasswordAuthentication ntlm = (NtlmPasswordAuthentication NtlmPasswordAuthentication ntlm = (NtlmPasswordAuthentication)obj;
)obj; if (ntlm.Domain.ToUpper().Equals(Domain.ToUpper())
if (ntlm.Domain.ToUpper().Equals(Domain.ToUpper()) && ntlm.Username.ToUpper().Equals && ntlm.Username.ToUpper().Equals(Username.ToUpper()))
(Username.ToUpper()))
{ {
if (HashesExternal && ntlm.HashesExternal) if (HashesExternal && ntlm.HashesExternal)
{ {
return Arrays.Equals(AnsiHash, ntlm.AnsiHash) && Arrays.Equals(UnicodeHash, ntlm. return Arrays.Equals(AnsiHash, ntlm.AnsiHash)
UnicodeHash); && Arrays.Equals(UnicodeHash, ntlm.UnicodeHash);
} }
if (!HashesExternal && Password.Equals(ntlm.Password)) if (!HashesExternal && Password.Equals(ntlm.Password))
{ {
@ -792,8 +834,12 @@ namespace SharpCifs.Smb
case 1: case 1:
{ {
b[0] = unchecked((byte)(Convert.ToInt32(Runtime.Substring(str, i, b[0] = unchecked(
i + 2), 16) & unchecked(0xFF))); (byte)(
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,8 +67,11 @@ namespace SharpCifs.Smb
public const int SidTypeUnknown = Lsarpc.SidNameUnknown; public const int SidTypeUnknown = Lsarpc.SidNameUnknown;
internal static readonly string[] SidTypeNames = { "0", "User", "Domain group" internal static readonly string[] SidTypeNames =
, "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);
@ -94,8 +97,9 @@ 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, LsaPolicyHandle policyHandle internal static void ResolveSids(DcerpcHandle handle,
, Sid[] sids) LsaPolicyHandle policyHandle,
Sid[] sids)
{ {
MsrpcLookupSids rpc = new MsrpcLookupSids(policyHandle, sids); MsrpcLookupSids rpc = new MsrpcLookupSids(policyHandle, sids);
handle.Sendrecv(rpc); handle.Sendrecv(rpc);
@ -132,16 +136,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, NtlmPasswordAuthentication internal static void ResolveSids0(string authorityServerName,
auth, Sid[] sids) NtlmPasswordAuthentication auth,
Sid[] sids)
{ {
DcerpcHandle handle = null; DcerpcHandle handle = null;
LsaPolicyHandle policyHandle = null; LsaPolicyHandle policyHandle = null;
@ -149,8 +153,8 @@ namespace SharpCifs.Smb
{ {
try try
{ {
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\lsarpc]" handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName
, auth); + "[\\PIPE\\lsarpc]", 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)
@ -175,10 +179,13 @@ namespace SharpCifs.Smb
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication public static void ResolveSids(string authorityServerName,
auth, Sid[] sids, int offset, int length) NtlmPasswordAuthentication auth,
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;
lock (SidCache) lock (SidCache)
{ {
@ -212,23 +219,27 @@ 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">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 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.
/// </param> /// </param>
/// <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. /// <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.
/// </param> /// </param>
/// <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. /// <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.
/// </param> /// </param>
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication public static void ResolveSids(string authorityServerName,
auth, Sid[] sids) NtlmPasswordAuthentication auth,
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;
lock (SidCache) lock (SidCache)
{ {
@ -249,7 +260,7 @@ namespace SharpCifs.Smb
if (list.Count > 0) if (list.Count > 0)
{ {
//sids = (Jcifs.Smb.SID[])Sharpen.Collections.ToArray(list, new Jcifs.Smb.SID[0]); //sids = (Jcifs.Smb.SID[])Sharpen.Collections.ToArray(list, new Jcifs.Smb.SID[0]);
sids = (Sid[]) list.ToArray(); sids = (Sid[])list.ToArray();
ResolveSids0(authorityServerName, auth, sids); ResolveSids0(authorityServerName, auth, sids);
for (si = 0; si < sids.Length; si++) for (si = 0; si < sids.Length; si++)
{ {
@ -260,8 +271,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public static Sid GetServerSid(string server, NtlmPasswordAuthentication public static Sid GetServerSid(string server,
auth) NtlmPasswordAuthentication auth)
{ {
DcerpcHandle handle = null; DcerpcHandle handle = null;
LsaPolicyHandle policyHandle = null; LsaPolicyHandle policyHandle = null;
@ -274,15 +285,19 @@ 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, Lsarpc.PolicyInfoAccountDomain rpc = new MsrpcQueryInformationPolicy(policyHandle,
, info); Lsarpc.PolicyInfoAccountDomain,
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, SidTypeDomain, (new UnicodeString return new Sid(info.Sid,
(info.Name, false)).ToString(), null, false); SidTypeDomain,
(new UnicodeString(info.Name, false)).ToString(),
null,
false);
} }
finally finally
{ {
@ -413,8 +428,11 @@ namespace SharpCifs.Smb
SubAuthority[i] = rid; SubAuthority[i] = rid;
} }
public Sid(Rpc.SidT sid, int type, string domainName, string acctName, bool decrementAuthority public Sid(Rpc.SidT sid,
) int type,
string domainName,
string acctName,
bool decrementAuthority)
{ {
Revision = sid.Revision; Revision = sid.Revision;
SubAuthorityCount = sid.SubAuthorityCount; SubAuthorityCount = sid.SubAuthorityCount;
@ -436,8 +454,11 @@ namespace SharpCifs.Smb
public virtual Sid GetDomainSid() public virtual Sid GetDomainSid()
{ {
return new Sid(this, SidTypeDomain, DomainName, null, GetType() return new Sid(this,
!= SidTypeDomain); SidTypeDomain,
DomainName,
null,
GetType() != SidTypeDomain);
} }
public virtual int GetRid() public virtual int GetRid()
@ -512,8 +533,7 @@ namespace SharpCifs.Smb
if (Type == SidTypeUnknown) if (Type == SidTypeUnknown)
{ {
string full = ToString(); string full = ToString();
return Runtime.Substring(full, 0, full.Length - GetAccountName().Length - return Runtime.Substring(full, 0, full.Length - GetAccountName().Length - 1);
1);
} }
return DomainName; return DomainName;
} }
@ -597,8 +617,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) || IdentifierAuthority[1] != unchecked( if (IdentifierAuthority[0] != unchecked(0)
0)) || IdentifierAuthority[1] != unchecked(0))
{ {
ret += "0x"; ret += "0x";
ret += Hexdump.ToHexString(IdentifierAuthority, 0, 6); ret += Hexdump.ToHexString(IdentifierAuthority, 0, 6);
@ -689,8 +709,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, NtlmPasswordAuthentication public virtual void Resolve(string authorityServerName,
auth) NtlmPasswordAuthentication auth)
{ {
Sid[] sids = new Sid[1]; Sid[] sids = new Sid[1];
sids[0] = this; sids[0] = this;
@ -717,8 +737,11 @@ namespace SharpCifs.Smb
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
internal static Sid[] GetGroupMemberSids0(DcerpcHandle handle, SamrDomainHandle internal static Sid[] GetGroupMemberSids0(DcerpcHandle handle,
domainHandle, Sid domsid, int rid, int flags) SamrDomainHandle domainHandle,
Sid domsid,
int rid,
int flags)
{ {
SamrAliasHandle aliasHandle = null; SamrAliasHandle aliasHandle = null;
Lsarpc.LsarSidArray sidarray = new Lsarpc.LsarSidArray(); Lsarpc.LsarSidArray sidarray = new Lsarpc.LsarSidArray();
@ -734,8 +757,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)handle.GetPrincipal NtlmPasswordAuthentication originAuth
(); = (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);
@ -758,8 +781,9 @@ namespace SharpCifs.Smb
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public virtual Sid[] GetGroupMemberSids(string authorityServerName, NtlmPasswordAuthentication public virtual Sid[] GetGroupMemberSids(string authorityServerName,
auth, int flags) NtlmPasswordAuthentication auth,
int flags)
{ {
if (Type != SidTypeDomGrp && Type != SidTypeAlias) if (Type != SidTypeDomGrp && Type != SidTypeAlias)
{ {
@ -773,11 +797,19 @@ namespace SharpCifs.Smb
{ {
try try
{ {
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]" handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName
, auth); + "[\\PIPE\\samr]", auth);
policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x00000030)); policyHandle = new SamrPolicyHandle(handle,
domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x00000200), domsid); authorityServerName,
return GetGroupMemberSids0(handle, domainHandle, domsid, GetRid(), unchecked(0x00000030));
domainHandle = new SamrDomainHandle(handle,
policyHandle,
unchecked(0x00000200),
domsid);
return GetGroupMemberSids0(handle,
domainHandle,
domsid,
GetRid(),
flags); flags);
} }
finally finally
@ -842,12 +874,18 @@ namespace SharpCifs.Smb
{ {
try try
{ {
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]" handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName
, auth); + "[\\PIPE\\samr]", auth);
policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x02000000)); policyHandle = new SamrPolicyHandle(handle,
domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x02000000), domsid); authorityServerName,
rpc = new MsrpcEnumerateAliasesInDomain(domainHandle, unchecked(0xFFFF), sam unchecked(0x02000000));
); 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)
{ {
@ -857,8 +895,11 @@ 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, domainHandle, domsid Sid[] mems = GetGroupMemberSids0(handle,
, entry.Idx, flags); domainHandle,
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

@ -21,15 +21,20 @@ using SharpCifs.Util.Transport;
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
public abstract class ServerMessageBlock: Response public abstract class ServerMessageBlock : Response
{ {
internal static LogStream Log = LogStream.GetInstance(); internal static LogStream Log = LogStream.GetInstance();
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 = { 0xFF, (byte)('S'), (byte)('M'), internal static readonly byte[] Header =
(byte)('B'), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 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
};
internal static void WriteInt2(long val, byte[] dst, int dstIndex) internal static void WriteInt2(long val, byte[] dst, int dstIndex)
{ {
@ -47,19 +52,22 @@ namespace SharpCifs.Smb
internal static int ReadInt2(byte[] src, int srcIndex) internal static int ReadInt2(byte[] src, int srcIndex)
{ {
return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8); return unchecked(src[srcIndex] & 0xFF)
+ ((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) + ((src[srcIndex + 1] & 0xFF) << 8) + ((src[srcIndex + 2] return unchecked(src[srcIndex] & 0xFF)
& 0xFF) << 16) + ((src[srcIndex + 3] & 0xFF) << 24); + ((src[srcIndex + 1] & 0xFF) << 8)
+ ((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)) + unchecked((long)(ReadInt4 return unchecked(ReadInt4(src, srcIndex) & unchecked(0xFFFFFFFFL))
(src, srcIndex + 4)) << 32); + unchecked((long)(ReadInt4(src, srcIndex + 4)) << 32);
} }
internal static void WriteInt8(long val, byte[] dst, int dstIndex) internal static void WriteInt8(long val, byte[] dst, int dstIndex)
@ -206,16 +214,20 @@ namespace SharpCifs.Smb
public ServerMessageBlock() public ServerMessageBlock()
{ {
Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized Flags = unchecked(
)); (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((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized Flags = unchecked(
)); (byte)(SmbConstants.FlagsPathNamesCaseless
| SmbConstants.FlagsPathNamesCanonicalized)
);
Flags2 = 0; Flags2 = 0;
ErrorCode = 0; ErrorCode = 0;
Received = false; Received = false;
@ -227,8 +239,7 @@ 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
@ -240,8 +251,8 @@ namespace SharpCifs.Smb
{ {
dst[dstIndex++] = (byte)('\0'); dst[dstIndex++] = (byte)('\0');
} }
Array.Copy(Runtime.GetBytesForString(str, SmbConstants.UniEncoding), 0, dst, dstIndex Array.Copy(Runtime.GetBytesForString(str, SmbConstants.UniEncoding),
, str.Length * 2); 0, dst, dstIndex, 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');
@ -269,8 +280,7 @@ 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;
@ -291,8 +301,12 @@ namespace SharpCifs.Smb
{ {
if (Log.Level > 0) if (Log.Level > 0)
{ {
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 : Hexdump.ToHexdump(Console.Error,
128); src,
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
} }
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
@ -308,8 +322,12 @@ namespace SharpCifs.Smb
{ {
if (Log.Level > 0) if (Log.Level > 0)
{ {
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 : Hexdump.ToHexdump(Console.Error,
128); src,
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
} }
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
@ -327,8 +345,11 @@ namespace SharpCifs.Smb
return str; return str;
} }
internal virtual string ReadString(byte[] src, int srcIndex, int srcEnd, int maxLen internal virtual string ReadString(byte[] src,
, bool useUnicode) int srcIndex,
int srcEnd,
int maxLen,
bool useUnicode)
{ {
int len = 0; int len = 0;
string str = null; string str = null;
@ -343,8 +364,7 @@ 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 if (src[srcIndex + len] == 0x00 && src[srcIndex + len + 1] == 0x00)
+ len + 1] == 0x00)
{ {
break; break;
} }
@ -352,8 +372,12 @@ namespace SharpCifs.Smb
{ {
if (Log.Level > 0) if (Log.Level > 0)
{ {
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 : Hexdump.ToHexdump(Console.Error,
128); src,
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
} }
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
@ -372,8 +396,12 @@ namespace SharpCifs.Smb
{ {
if (Log.Level > 0) if (Log.Level > 0)
{ {
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 : Hexdump.ToHexdump(Console.Error,
128); src,
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
} }
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
@ -447,8 +475,8 @@ namespace SharpCifs.Smb
{ {
if (Log.Level >= 5) if (Log.Level >= 5)
{ {
Log.WriteLine("wordCount * 2=" + (WordCount * 2) + " but readParameterWordsWireFormat returned " Log.WriteLine("wordCount * 2=" + (WordCount * 2)
+ n); + " but readParameterWordsWireFormat returned " + n);
} }
} }
bufferIndex += WordCount * 2; bufferIndex += WordCount * 2;
@ -462,8 +490,8 @@ namespace SharpCifs.Smb
{ {
if (Log.Level >= 5) if (Log.Level >= 5)
{ {
Log.WriteLine("byteCount=" + ByteCount + " but readBytesWireFormat returned " + n Log.WriteLine("byteCount=" + ByteCount
); + " 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.
@ -510,8 +538,7 @@ 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);
@ -522,8 +549,7 @@ namespace SharpCifs.Smb
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
return obj is ServerMessageBlock && ((ServerMessageBlock)obj) return obj is ServerMessageBlock && ((ServerMessageBlock)obj).Mid == Mid;
.Mid == Mid;
} }
public override string ToString() public override string ToString()
@ -681,12 +707,21 @@ namespace SharpCifs.Smb
break; break;
} }
} }
string str = ErrorCode == 0 ? "0" : SmbException.GetMessageByCode(ErrorCode); string str = ErrorCode == 0
return "command=" + c + ",received=" + Received + ",errorCode=" + str ? "0"
+ ",flags=0x" + Hexdump.ToHexString(Flags & 0xFF, 4) + ",flags2=0x" : SmbException.GetMessageByCode(ErrorCode);
+ Hexdump.ToHexString(Flags2, 4) + ",signSeq=" + SignSeq + ",tid=" + Tid + ",pid=" return "command=" + c
+ Pid + ",uid=" + Uid + ",mid=" + Mid + ",wordCount=" + WordCount + ",byteCount=" + ",received=" + Received
+ ByteCount; + ",errorCode=" + str
+ ",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,9 +85,14 @@ namespace SharpCifs.Smb
case 2: case 2:
{ {
_macSigningKey = new byte[40]; _macSigningKey = new byte[40];
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0); auth.GetUserSessionKey(transport.Server.EncryptionKey,
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey _macSigningKey,
, 16, 24); 0);
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey),
0,
_macSigningKey,
16,
24);
break; break;
} }
@ -104,8 +109,11 @@ 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), 0, _macSigningKey Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey),
, 16, 24); 0,
_macSigningKey,
16,
24);
break; break;
} }
} }
@ -161,8 +169,11 @@ 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, int offset, int length, ServerMessageBlock internal virtual void Sign(byte[] data,
request, ServerMessageBlock response) int offset,
int length,
ServerMessageBlock request,
ServerMessageBlock response)
{ {
request.SignSeq = _signSequence; request.SignSeq = _signSequence;
if (response != null) if (response != null)
@ -184,7 +195,10 @@ namespace SharpCifs.Smb
if (_bypass) if (_bypass)
{ {
_bypass = false; _bypass = false;
Array.Copy(Runtime.GetBytesForString("BSRSPYL "), 0, data, index, Array.Copy(Runtime.GetBytesForString("BSRSPYL "),
0,
data,
index,
8); 8);
} }
} }
@ -209,8 +223,7 @@ 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;
@ -250,8 +263,10 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "LM_COMPATIBILITY=" + SmbConstants.LmCompatibility + " MacSigningKey=" + Hexdump.ToHexString return "LM_COMPATIBILITY=" + SmbConstants.LmCompatibility
(_macSigningKey, 0, _macSigningKey.Length); + " MacSigningKey=" + Hexdump.ToHexString(_macSigningKey,
0,
_macSigningKey.Length);
} }
} }
} }

View File

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

View File

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

View File

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

View File

@ -37,8 +37,7 @@ 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;
} }
@ -50,8 +49,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComDeleteDirectory[" + base.ToString() + ",directoryName=" return "SmbComDeleteDirectory["
+ Path + "]"; + base.ToString()
+ ",directoryName=" + Path + "]";
} }
} }
} }

View File

@ -37,8 +37,7 @@ 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;
} }
@ -50,7 +49,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComFindClose2[" + base.ToString() + ",sid=" + _sid + "]"; return "SmbComFindClose2["
+ base.ToString()
+ ",sid=" + _sid + "]";
} }
} }
} }

View File

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

View File

@ -65,8 +65,7 @@ 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++];
@ -103,13 +102,20 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComNTCreateAndXResponse[" + base.ToString() + ",oplockLevel=" return "SmbComNTCreateAndXResponse["
+ OplockLevel + ",fid=" + Fid + ",createAction=0x" + Hexdump.ToHexString(CreateAction + base.ToString()
, 4) + ",creationTime=" + Extensions.CreateDate(CreationTime) + ",lastAccessTime=" + ",oplockLevel=" + OplockLevel
+ Extensions.CreateDate(LastAccessTime) + ",lastWriteTime=" + Extensions.CreateDate + ",fid=" + Fid
(LastWriteTime) + ",changeTime=" + Extensions.CreateDate(ChangeTime) + ",extFileAttributes=0x" + ",createAction=0x" + Hexdump.ToHexString(CreateAction, 4)
+ Hexdump.ToHexString(ExtFileAttributes, 4) + ",allocationSize=" + AllocationSize + ",creationTime=" + Extensions.CreateDate(CreationTime)
+ ",endOfFile=" + EndOfFile + ",fileType=" + FileType + ",deviceState=" + DeviceState + ",lastAccessTime=" + Extensions.CreateDate(LastAccessTime)
+ ",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,8 +50,7 @@ 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;
} }
@ -63,7 +62,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComNegotiate[" + base.ToString() + ",wordCount=" + WordCount return "SmbComNegotiate["
+ base.ToString()
+ ",wordCount=" + WordCount
+ ",dialects=NT LM 0.12]"; + ",dialects=NT LM 0.12]";
} }
} }

View File

@ -41,8 +41,7 @@ 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);
@ -53,12 +52,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.SecurityMode & unchecked(0x02)) == unchecked( Server.EncryptedPasswords
0x02); = (Server.SecurityMode & unchecked(0x02)) == unchecked(0x02);
Server.SignaturesEnabled = (Server.SecurityMode & unchecked(0x04)) == unchecked( Server.SignaturesEnabled
0x04); = (Server.SecurityMode & unchecked(0x04)) == unchecked(0x04);
Server.SignaturesRequired = (Server.SecurityMode & unchecked(0x08)) == unchecked( Server.SignaturesRequired
0x08); = (Server.SecurityMode & unchecked(0x08)) == unchecked(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);
@ -85,8 +84,11 @@ 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, bufferIndex, Server.EncryptionKey, 0, Server.EncryptionKeyLength Array.Copy(buffer,
); bufferIndex,
Server.EncryptionKey,
0,
Server.EncryptionKeyLength);
bufferIndex += Server.EncryptionKeyLength; bufferIndex += Server.EncryptionKeyLength;
if (ByteCount > Server.EncryptionKeyLength) if (ByteCount > Server.EncryptionKeyLength)
{ {
@ -96,8 +98,8 @@ namespace SharpCifs.Smb
{ {
if ((Flags2 & SmbConstants.Flags2Unicode) == SmbConstants.Flags2Unicode) if ((Flags2 & SmbConstants.Flags2Unicode) == SmbConstants.Flags2Unicode)
{ {
while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)) || buffer while (buffer[bufferIndex + len] != unchecked(unchecked(0x00))
[bufferIndex + len + 1] != unchecked(unchecked(0x00))) || buffer[bufferIndex + len + 1] != unchecked(unchecked(0x00)))
{ {
len += 2; len += 2;
if (len > 256) if (len > 256)
@ -105,8 +107,10 @@ namespace SharpCifs.Smb
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
} }
Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len Server.OemDomainName = Runtime.GetStringForBytes(buffer,
, SmbConstants.UniEncoding); bufferIndex,
len,
SmbConstants.UniEncoding);
} }
else else
{ {
@ -118,8 +122,10 @@ namespace SharpCifs.Smb
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
} }
Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len Server.OemDomainName = Runtime.GetStringForBytes(buffer,
, SmbConstants.OemEncoding); bufferIndex,
len,
SmbConstants.OemEncoding);
} }
} }
catch (UnsupportedEncodingException uee) catch (UnsupportedEncodingException uee)
@ -148,17 +154,26 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComNegotiateResponse[" + base.ToString() + ",wordCount=" + return "SmbComNegotiateResponse["
WordCount + ",dialectIndex=" + DialectIndex + ",securityMode=0x" + Hexdump.ToHexString + base.ToString()
(Server.SecurityMode, 1) + ",security=" + (Server.Security == SmbConstants.SecurityShare ? "share" + ",wordCount=" + WordCount
: "user") + ",encryptedPasswords=" + Server.EncryptedPasswords + ",maxMpxCount=" + ",dialectIndex=" + DialectIndex
+ Server.MaxMpxCount + ",maxNumberVcs=" + Server.MaxNumberVcs + ",maxBufferSize=" + ",securityMode=0x" + Hexdump.ToHexString(Server.SecurityMode, 1)
+ Server.MaxBufferSize + ",maxRawSize=" + Server.MaxRawSize + ",sessionKey=0x" + ",security=" + (Server.Security == SmbConstants.SecurityShare
+ Hexdump.ToHexString(Server.SessionKey, 8) + ",capabilities=0x" + Hexdump.ToHexString ? "share"
(Server.Capabilities, 8) + ",serverTime=" + Extensions.CreateDate(Server : "user")
.ServerTime) + ",serverTimeZone=" + Server.ServerTimeZone + ",encryptionKeyLength=" + ",encryptedPasswords=" + Server.EncryptedPasswords
+ Server.EncryptionKeyLength + ",byteCount=" + ByteCount + ",oemDomainName=" + + ",maxMpxCount=" + Server.MaxMpxCount
Server.OemDomainName + "]"; + ",maxNumberVcs=" + Server.MaxNumberVcs
+ ",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,8 +18,7 @@ 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 = Config.GetInt("jcifs.smb.client.OpenAndX.ReadAndX" private static readonly int BatchLimit
, 1); = Config.GetInt("jcifs.smb.client.OpenAndX.ReadAndX", 1);
internal int flags; internal int flags;
@ -66,8 +66,10 @@ namespace SharpCifs.Smb
internal int AllocationSize; internal int AllocationSize;
internal SmbComOpenAndX(string fileName, int access, int flags, ServerMessageBlock internal SmbComOpenAndX(string fileName,
andx) : base(andx) int access,
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
@ -85,7 +87,9 @@ 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 | SmbConstants.AttrHidden | SmbConstants.AttrSystem; SearchAttributes = SmbConstants.AttrDirectory
| SmbConstants.AttrHidden
| SmbConstants.AttrSystem;
// fileAttributes // fileAttributes
FileAttributes = 0; FileAttributes = 0;
// openFunction // openFunction
@ -166,8 +170,7 @@ 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;
} }
@ -179,12 +182,16 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComOpenAndX[" + base.ToString() + ",flags=0x" + Hexdump.ToHexString return "SmbComOpenAndX["
(flags, 2) + ",desiredAccess=0x" + Hexdump.ToHexString(DesiredAccess, 4) + ",searchAttributes=0x" + base.ToString()
+ Hexdump.ToHexString(SearchAttributes, 4) + ",fileAttributes=0x" + Hexdump.ToHexString + ",flags=0x" + Hexdump.ToHexString(flags, 2)
(FileAttributes, 4) + ",creationTime=" + Extensions.CreateDate(CreationTime + ",desiredAccess=0x" + Hexdump.ToHexString(DesiredAccess, 4)
) + ",openFunction=0x" + Hexdump.ToHexString(OpenFunction, 2) + ",allocationSize=" + ",searchAttributes=0x" + Hexdump.ToHexString(SearchAttributes, 4)
+ AllocationSize + ",fileName=" + Path + "]"; + ",fileAttributes=0x" + Hexdump.ToHexString(FileAttributes, 4)
+ ",creationTime=" + Extensions.CreateDate(CreationTime)
+ ",openFunction=0x" + Hexdump.ToHexString(OpenFunction, 2)
+ ",allocationSize=" + AllocationSize
+ ",fileName=" + Path + "]";
} }
} }
} }

View File

@ -46,8 +46,7 @@ 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);
@ -78,10 +77,17 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComOpenAndXResponse[" + base.ToString() + ",fid=" + Fid + ",fileAttributes=" return "SmbComOpenAndXResponse["
+ FileAttributes + ",lastWriteTime=" + LastWriteTime + ",dataSize=" + DataSize + base.ToString()
+ ",grantedAccess=" + GrantedAccess + ",fileType=" + FileType + ",deviceState=" + ",fid=" + Fid
+ DeviceState + ",action=" + Action + ",serverFid=" + ServerFid + "]"; + ",fileAttributes=" + FileAttributes
+ ",lastWriteTime=" + LastWriteTime
+ ",dataSize=" + DataSize
+ ",grantedAccess=" + GrantedAccess
+ ",fileType=" + FileType
+ ",deviceState=" + DeviceState
+ ",action=" + Action
+ ",serverFid=" + ServerFid + "]";
} }
} }
} }

View File

@ -37,8 +37,7 @@ 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;
} }
@ -50,8 +49,9 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComQueryInformation[" + base.ToString() + ",filename=" + Path return "SmbComQueryInformation["
+ "]"; + base.ToString()
+ ",filename=" + Path + "]";
} }
} }
} }

View File

@ -65,8 +65,7 @@ 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)
{ {
@ -87,9 +86,11 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComQueryInformationResponse[" + base.ToString() + ",fileAttributes=0x" return "SmbComQueryInformationResponse["
+ Hexdump.ToHexString(_fileAttributes, 4) + ",lastWriteTime=" + Extensions.CreateDate + base.ToString()
(_lastWriteTime) + ",fileSize=" + _fileSize + "]"; + ",fileAttributes=0x" + Hexdump.ToHexString(_fileAttributes, 4)
+ ",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 = Config.GetInt("jcifs.smb.client.ReadAndX.Close" private static readonly int BatchLimit
, 1); = Config.GetInt("jcifs.smb.client.ReadAndX.Close", 1);
private long _offset; private long _offset;
@ -39,8 +39,10 @@ namespace SharpCifs.Smb
_openTimeout = unchecked((int)(0xFFFFFFFF)); _openTimeout = unchecked((int)(0xFFFFFFFF));
} }
internal SmbComReadAndX(int fid, long offset, int maxCount, ServerMessageBlock andx internal SmbComReadAndX(int fid,
) : base(andx) long offset,
int maxCount,
ServerMessageBlock andx) : base(andx)
{ {
this._fid = fid; this._fid = fid;
this._offset = offset; this._offset = offset;
@ -86,8 +88,7 @@ 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;
} }
@ -99,9 +100,15 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComReadAndX[" + base.ToString() + ",fid=" + _fid + ",offset=" return "SmbComReadAndX["
+ _offset + ",maxCount=" + MaxCount + ",minCount=" + MinCount + ",openTimeout=" + base.ToString()
+ _openTimeout + ",remaining=" + Remaining + ",offset=" + _offset + "]"; + ",fid=" + _fid
+ ",offset=" + _offset
+ ",maxCount=" + MaxCount
+ ",minCount=" + MinCount
+ ",openTimeout=" + _openTimeout
+ ",remaining=" + Remaining
+ ",offset=" + _offset + "]";
} }
} }
} }

View File

@ -54,8 +54,7 @@ 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;
@ -79,9 +78,11 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComReadAndXResponse[" + base.ToString() + ",dataCompactionMode=" return "SmbComReadAndXResponse["
+ DataCompactionMode + ",dataLength=" + DataLength + ",dataOffset=" + DataOffset + base.ToString()
+ "]"; + ",dataCompactionMode=" + DataCompactionMode
+ ",dataLength=" + DataLength
+ ",dataOffset=" + DataOffset + "]";
} }
} }
} }

View File

@ -31,7 +31,9 @@ namespace SharpCifs.Smb
Command = SmbComRename; Command = SmbComRename;
this._oldFileName = oldFileName; this._oldFileName = oldFileName;
this._newFileName = newFileName; this._newFileName = newFileName;
_searchAttributes = SmbConstants.AttrHidden | SmbConstants.AttrSystem | SmbConstants.AttrDirectory; _searchAttributes = SmbConstants.AttrHidden
| SmbConstants.AttrSystem
| SmbConstants.AttrDirectory;
} }
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
@ -54,8 +56,7 @@ 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;
} }
@ -67,9 +68,11 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComRename[" + base.ToString() + ",searchAttributes=0x" + Hexdump return "SmbComRename["
.ToHexString(_searchAttributes, 4) + ",oldFileName=" + _oldFileName + ",newFileName=" + base.ToString()
+ _newFileName + "]"; + ",searchAttributes=0x" + Hexdump.ToHexString(_searchAttributes, 4)
+ ",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 = Config.GetInt("jcifs.smb.client.SessionSetupAndX.TreeConnectAndX" private static readonly int BatchLimit
, 1); = Config.GetInt("jcifs.smb.client.SessionSetupAndX.TreeConnectAndX", 1);
private static readonly bool DisablePlainTextPasswords = Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords" private static readonly bool DisablePlainTextPasswords
, true); = Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords", true);
private byte[] _lmHash; private byte[] _lmHash;
@ -47,8 +47,9 @@ 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, ServerMessageBlock andx, object internal SmbComSessionSetupAndX(SmbSession session,
cred) : base(andx) ServerMessageBlock andx,
object cred) : base(andx)
{ {
Command = SmbComSessionSetupAndx; Command = SmbComSessionSetupAndx;
this.Session = session; this.Session = session;
@ -208,8 +209,7 @@ 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,12 +221,22 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
string result = "SmbComSessionSetupAndX[" + base.ToString() + ",snd_buf_size=" string result = "SmbComSessionSetupAndX["
+ Session.transport.SndBufSize + ",maxMpxCount=" + Session.transport.MaxMpxCount + base.ToString()
+ ",VC_NUMBER=" + SmbConstants.VcNumber + ",sessionKey=" + _sessionKey + ",lmHash.length=" + ",snd_buf_size=" + Session.transport.SndBufSize
+ (_lmHash == null ? 0 : _lmHash.Length) + ",ntHash.length=" + (_ntHash == null ? + ",maxMpxCount=" + Session.transport.MaxMpxCount
0 : _ntHash.Length) + ",capabilities=" + _capabilities + ",accountName=" + _accountName + ",VC_NUMBER=" + SmbConstants.VcNumber
+ ",primaryDomain=" + _primaryDomain + ",NATIVE_OS=" + SmbConstants.NativeOs + ",sessionKey=" + _sessionKey
+ ",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,11 +44,12 @@ 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 ? true : false; IsLoggedInAsGuest = (buffer[bufferIndex] & 0x01) == 0x01
? true
: false;
bufferIndex += 2; bufferIndex += 2;
if (ExtendedSecurity) if (ExtendedSecurity)
{ {
@ -69,13 +70,11 @@ 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;
@ -83,9 +82,12 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
string result = "SmbComSessionSetupAndXResponse[" + base.ToString() + string result = "SmbComSessionSetupAndXResponse["
",isLoggedInAsGuest=" + IsLoggedInAsGuest + ",nativeOs=" + _nativeOs + ",nativeLanMan=" + base.ToString()
+ _nativeLanMan + ",primaryDomain=" + _primaryDomain + "]"; + ",isLoggedInAsGuest=" + IsLoggedInAsGuest
+ ",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 = Config.GetInt("jcifs.smb.client.transaction_buf_size" private static readonly int DefaultMaxDataCount
, TransactionBufSize) - 512; = Config.GetInt("jcifs.smb.client.transaction_buf_size", TransactionBufSize) - 512;
private const int PrimarySetupOffset = 61; private const int PrimarySetupOffset = 61;
@ -70,14 +70,11 @@ 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));
@ -211,8 +208,8 @@ namespace SharpCifs.Smb
available -= _pad1; available -= _pad1;
DataCount = Math.Min(TotalDataCount - DataDisplacement, available); DataCount = Math.Min(TotalDataCount - DataDisplacement, available);
} }
if ((ParameterDisplacement + ParameterCount) >= TotalParameterCount && (DataDisplacement if ((ParameterDisplacement + ParameterCount) >= TotalParameterCount
+ DataCount) >= TotalDataCount) && (DataDisplacement + DataCount) >= TotalDataCount)
{ {
_hasMore = false; _hasMore = false;
} }
@ -306,8 +303,7 @@ 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;
} }
@ -323,24 +319,31 @@ 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 internal abstract int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len);
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() + ",totalParameterCount=" + TotalParameterCount return base.ToString()
+ ",totalDataCount=" + TotalDataCount + ",maxParameterCount=" + MaxParameterCount + ",totalParameterCount=" + TotalParameterCount
+ ",maxDataCount=" + MaxDataCount + ",maxSetupCount=" + (int)MaxSetupCount + ",flags=0x" + ",totalDataCount=" + TotalDataCount
+ Hexdump.ToHexString(_flags, 2) + ",timeout=" + Timeout + ",parameterCount=" + + ",maxParameterCount=" + MaxParameterCount
ParameterCount + ",parameterOffset=" + ParameterOffset + ",parameterDisplacement=" + ",maxDataCount=" + MaxDataCount
+ ParameterDisplacement + ",dataCount=" + DataCount + ",dataOffset=" + DataOffset + ",maxSetupCount=" + (int)MaxSetupCount
+ ",dataDisplacement=" + DataDisplacement + ",setupCount=" + SetupCount + ",pad=" + ",flags=0x" + Hexdump.ToHexString(_flags, 2)
+ _pad + ",pad1=" + _pad1; + ",timeout=" + Timeout
+ ",parameterCount=" + ParameterCount
+ ",parameterOffset=" + ParameterOffset
+ ",parameterDisplacement=" + ParameterDisplacement
+ ",dataCount=" + DataCount
+ ",dataOffset=" + DataOffset
+ ",dataDisplacement=" + DataDisplacement
+ ",setupCount=" + SetupCount
+ ",pad=" + _pad
+ ",pad1=" + _pad1;
} }
} }
} }

View File

@ -108,8 +108,7 @@ 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);
@ -152,22 +151,30 @@ namespace SharpCifs.Smb
if (ParameterCount > 0) if (ParameterCount > 0)
{ {
bufferIndex += _pad = ParameterOffset - (bufferIndex - HeaderStart); bufferIndex += _pad = ParameterOffset - (bufferIndex - HeaderStart);
Array.Copy(buffer, bufferIndex, TxnBuf, BufParameterStart + ParameterDisplacement Array.Copy(buffer,
, ParameterCount); bufferIndex,
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, bufferIndex, TxnBuf, BufDataStart + DataDisplacement, Array.Copy(buffer,
bufferIndex,
TxnBuf,
BufDataStart + DataDisplacement,
DataCount); DataCount);
bufferIndex += DataCount; bufferIndex += DataCount;
} }
if (!_parametersDone && (ParameterDisplacement + ParameterCount) == TotalParameterCount) if (!_parametersDone
&& (ParameterDisplacement + ParameterCount) == TotalParameterCount)
{ {
_parametersDone = true; _parametersDone = true;
} }
if (!_dataDone && (DataDisplacement + DataCount) == TotalDataCount) if (!_dataDone
&& (DataDisplacement + DataCount) == TotalDataCount)
{ {
_dataDone = true; _dataDone = true;
} }
@ -186,21 +193,26 @@ 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 internal abstract int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len);
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() + ",totalParameterCount=" + TotalParameterCount return base.ToString()
+ ",totalDataCount=" + TotalDataCount + ",parameterCount=" + ParameterCount + ",parameterOffset=" + ",totalParameterCount=" + TotalParameterCount
+ ParameterOffset + ",parameterDisplacement=" + ParameterDisplacement + ",dataCount=" + ",totalDataCount=" + TotalDataCount
+ DataCount + ",dataOffset=" + DataOffset + ",dataDisplacement=" + DataDisplacement + ",parameterCount=" + ParameterCount
+ ",setupCount=" + SetupCount + ",pad=" + _pad + ",pad1=" + _pad1; + ",parameterOffset=" + ParameterOffset
+ ",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 = Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords" private static readonly bool DisablePlainTextPasswords
, true); = Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords", true);
private SmbSession _session; private SmbSession _session;
@ -42,13 +42,11 @@ namespace SharpCifs.Smb
static SmbComTreeConnectAndX() static SmbComTreeConnectAndX()
{ {
string s; string s;
if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CheckDirectory")) != if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CheckDirectory")) != null)
null)
{ {
_batchLimits[0] = byte.Parse(s); _batchLimits[0] = byte.Parse(s);
} }
if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CreateDirectory")) if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.CreateDirectory")) != null)
!= null)
{ {
_batchLimits[2] = byte.Parse(s); _batchLimits[2] = byte.Parse(s);
} }
@ -56,8 +54,7 @@ namespace SharpCifs.Smb
{ {
_batchLimits[3] = byte.Parse(s); _batchLimits[3] = byte.Parse(s);
} }
if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.DeleteDirectory")) if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.DeleteDirectory")) != null)
!= null)
{ {
_batchLimits[4] = byte.Parse(s); _batchLimits[4] = byte.Parse(s);
} }
@ -73,15 +70,16 @@ namespace SharpCifs.Smb
{ {
_batchLimits[7] = byte.Parse(s); _batchLimits[7] = byte.Parse(s);
} }
if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.QueryInformation")) if ((s = Config.GetProperty("jcifs.smb.client.TreeConnectAndX.QueryInformation")) != null)
!= null)
{ {
_batchLimits[8] = byte.Parse(s); _batchLimits[8] = byte.Parse(s);
} }
} }
internal SmbComTreeConnectAndX(SmbSession session, string path, string service, ServerMessageBlock internal SmbComTreeConnectAndX(SmbSession session,
andx) : base(andx) string path,
string service,
ServerMessageBlock andx) : base(andx)
{ {
this._session = session; this._session = session;
this.path = path; this.path = path;
@ -140,8 +138,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 && (_session.Auth.HashesExternal if (_session.transport.Server.Security == SmbConstants.SecurityShare
|| _session.Auth.Password.Length > 0)) && (_session.Auth.HashesExternal || _session.Auth.Password.Length > 0))
{ {
if (_session.transport.Server.EncryptedPasswords) if (_session.transport.Server.EncryptedPasswords)
{ {
@ -165,8 +163,9 @@ namespace SharpCifs.Smb
// no password in tree connect // no password in tree connect
_passwordLength = 1; _passwordLength = 1;
} }
dst[dstIndex++] = _disconnectTid ? unchecked((byte)unchecked(0x01)) : unchecked( dst[dstIndex++] = _disconnectTid
(byte)unchecked(0x00)); ? unchecked((byte)unchecked(0x01))
: 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;
@ -175,10 +174,14 @@ 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 && (_session.Auth.HashesExternal if (_session.transport.Server.Security == SmbConstants.SecurityShare
|| _session.Auth.Password.Length > 0)) && (_session.Auth.HashesExternal || _session.Auth.Password.Length > 0))
{ {
Array.Copy(_password, 0, dst, dstIndex, _passwordLength); Array.Copy(_password,
0,
dst,
dstIndex,
_passwordLength);
dstIndex += _passwordLength; dstIndex += _passwordLength;
} }
else else
@ -189,10 +192,13 @@ namespace SharpCifs.Smb
dstIndex += WriteString(path, dst, dstIndex); dstIndex += WriteString(path, dst, dstIndex);
try try
{ {
// 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"), 0, dst, dstIndex Array.Copy(Runtime.GetBytesForString(_service, "UTF-8"),
, _service.Length); 0,
dst,
dstIndex,
_service.Length);
} }
catch (UnsupportedEncodingException) catch (UnsupportedEncodingException)
{ {
@ -203,8 +209,7 @@ 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;
} }
@ -216,10 +221,13 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
string result = "SmbComTreeConnectAndX[" + base.ToString() + ",disconnectTid=" string result = "SmbComTreeConnectAndX["
+ _disconnectTid + ",passwordLength=" + _passwordLength + ",password=" + Hexdump. + base.ToString()
ToHexString(_password, _passwordLength, 0) + ",path=" + path + ",service=" + _service + ",disconnectTid=" + _disconnectTid
+ "]"; + ",passwordLength=" + _passwordLength
+ ",password=" + Hexdump.ToHexString(_password, _passwordLength, 0)
+ ",path=" + path
+ ",service=" + _service + "]";
return result; return result;
} }
} }

View File

@ -47,8 +47,7 @@ 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;
@ -75,9 +74,12 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
string result = "SmbComTreeConnectAndXResponse[" + base.ToString() + ",supportSearchBits=" string result = "SmbComTreeConnectAndXResponse["
+ SupportSearchBits + ",shareIsInDfs=" + ShareIsInDfs + ",service=" + Service + + base.ToString()
",nativeFileSystem=" + NativeFileSystem + "]"; + ",supportSearchBits=" + SupportSearchBits
+ ",shareIsInDfs=" + ShareIsInDfs
+ ",service=" + Service
+ ",nativeFileSystem=" + NativeFileSystem + "]";
return result; return result;
} }
} }

View File

@ -33,8 +33,7 @@ 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,8 +37,7 @@ 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;
@ -49,8 +48,12 @@ namespace SharpCifs.Smb
Command = SmbComWrite; Command = SmbComWrite;
} }
internal virtual void SetParam(int fid, long offset, int remaining, byte[] b, int internal virtual void SetParam(int fid,
off, int len) long offset,
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));
@ -86,8 +89,7 @@ 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;
} }
@ -99,8 +101,12 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComWrite[" + base.ToString() + ",fid=" + _fid + ",count=" + return "SmbComWrite["
_count + ",offset=" + _offset + ",remaining=" + _remaining + "]"; + base.ToString()
+ ",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 = Config.GetInt("jcifs.smb.client.WriteAndX.ReadAndX" private static readonly int ReadAndxBatchLimit
, 1); = Config.GetInt("jcifs.smb.client.WriteAndX.ReadAndX", 1);
private static readonly int CloseBatchLimit = Config.GetInt("jcifs.smb.client.WriteAndX.Close" private static readonly int CloseBatchLimit
, 1); = Config.GetInt("jcifs.smb.client.WriteAndX.Close", 1);
private int _fid; private int _fid;
@ -49,8 +49,13 @@ namespace SharpCifs.Smb
Command = SmbComWriteAndx; Command = SmbComWriteAndx;
} }
internal SmbComWriteAndX(int fid, long offset, int remaining, byte[] b, int off, internal SmbComWriteAndX(int fid,
int len, ServerMessageBlock andx) : base(andx) long offset,
int remaining,
byte[] b,
int off,
int len,
ServerMessageBlock andx) : base(andx)
{ {
this._fid = fid; this._fid = fid;
this._offset = offset; this._offset = offset;
@ -61,8 +66,12 @@ namespace SharpCifs.Smb
Command = SmbComWriteAndx; Command = SmbComWriteAndx;
} }
internal virtual void SetParam(int fid, long offset, int remaining, byte[] b, int internal virtual void SetParam(int fid,
off, int len) long offset,
int remaining,
byte[] b,
int off,
int len)
{ {
this._fid = fid; this._fid = fid;
this._offset = offset; this._offset = offset;
@ -107,7 +116,7 @@ namespace SharpCifs.Smb
WriteInt2(_remaining, dst, dstIndex); WriteInt2(_remaining, dst, dstIndex);
dstIndex += 2; dstIndex += 2;
dst[dstIndex++] = 0x00; dst[dstIndex++] = 0x00;
dst[dstIndex++] =0x00; dst[dstIndex++] = 0x00;
WriteInt2(_dataLength, dst, dstIndex); WriteInt2(_dataLength, dst, dstIndex);
dstIndex += 2; dstIndex += 2;
WriteInt2(_dataOffset, dst, dstIndex); WriteInt2(_dataOffset, dst, dstIndex);
@ -129,8 +138,7 @@ 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;
} }
@ -142,9 +150,14 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbComWriteAndX[" + base.ToString() + ",fid=" + _fid + ",offset=" return "SmbComWriteAndX["
+ _offset + ",writeMode=" + WriteMode + ",remaining=" + _remaining + ",dataLength=" + base.ToString()
+ _dataLength + ",dataOffset=" + _dataOffset + "]"; + ",fid=" + _fid
+ ",offset=" + _offset
+ ",writeMode=" + WriteMode
+ ",remaining=" + _remaining
+ ",dataLength=" + _dataLength
+ ",dataOffset=" + _dataOffset + "]";
} }
} }
} }

View File

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

View File

@ -24,6 +24,7 @@ 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
{ {
@ -227,6 +228,14 @@ 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;
@ -374,10 +383,10 @@ namespace SharpCifs.Smb
Sharpen.Runtime.PrintStackTrace(cnfe); Sharpen.Runtime.PrintStackTrace(cnfe);
}*/ }*/
AttrExpirationPeriod = Config.GetLong("jcifs.smb.client.attrExpirationPeriod", DefaultAttrExpirationPeriod AttrExpirationPeriod
); = Config.GetLong("jcifs.smb.client.attrExpirationPeriod", DefaultAttrExpirationPeriod);
IgnoreCopyToException = Config.GetBoolean("jcifs.smb.client.ignoreCopyToException" IgnoreCopyToException
, true); = Config.GetBoolean("jcifs.smb.client.ignoreCopyToException", true);
Dfs = new Dfs(); Dfs = new Dfs();
} }
@ -522,11 +531,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(context.Url.AbsoluteUri + name), ? new Uri("smb://" + 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())
@ -565,7 +574,6 @@ 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))
{ {
} }
@ -582,10 +590,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) public SmbFile(string url, NtlmPasswordAuthentication auth)
: this(new Uri(url, UriKind.RelativeOrAbsolute), : this(new Uri(url, UriKind.RelativeOrAbsolute), auth)
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>
@ -604,8 +610,7 @@ 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 : this(new Uri(url), auth)
(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
@ -614,8 +619,7 @@ 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)) != if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) != 0)
0)
{ {
throw new RuntimeException("Illegal shareAccess parameter"); throw new RuntimeException("Illegal shareAccess parameter");
} }
@ -640,11 +644,8 @@ 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 : this(new Uri(context + name), auth)
(new Uri(context + name)
, auth)
{ {
} }
@ -672,12 +673,13 @@ 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, string name, NtlmPasswordAuthentication auth, int public SmbFile(string context,
shareAccess) string name,
NtlmPasswordAuthentication auth,
int shareAccess)
: this(new Uri(context + name), auth) : this(new Uri(context + name), auth)
{ {
if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) != if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) != 0)
0)
{ {
throw new RuntimeException("Illegal shareAccess parameter"); throw new RuntimeException("Illegal shareAccess parameter");
} }
@ -709,11 +711,12 @@ 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() ? new Uri("smb://" + name) : new Uri( : this(context.IsWorkgroup0()
context.Url.AbsoluteUri + name), context.Auth) ? new Uri("smb://" + name)
: new Uri(context.Url.AbsoluteUri + name),
context.Auth)
{ {
if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) != if ((shareAccess & ~(FileShareRead | FileShareWrite | FileShareDelete)) != 0)
0)
{ {
throw new RuntimeException("Illegal shareAccess parameter"); throw new RuntimeException("Illegal shareAccess parameter");
} }
@ -743,8 +746,7 @@ 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()))
()))
{ {
} }
@ -769,16 +771,18 @@ namespace SharpCifs.Smb
/// <exception cref="System.UriFormatException"></exception> /// <exception cref="System.UriFormatException"></exception>
/// <exception cref="UnknownHostException"></exception> /// <exception cref="UnknownHostException"></exception>
/*internal SmbFile(Jcifs.Smb.SmbFile context, string name, int type, int attributes internal SmbFile(SmbFile context,
, long createTime, long lastModified, long size) string name,
: this(context.IsWorkgroup0() ? int type,
new Uri(null, "smb://" + name + "/") : new Uri(context.url, int attributes,
name + ((attributes & ATTR_DIRECTORY) > 0 ? "/" : string.Empty)))*/ long createTime,
internal SmbFile(SmbFile context, string name, int type, int attributes long lastModified,
, long createTime, long lastModified, long size) long size)
: this(context.IsWorkgroup0() ? : this(context.IsWorkgroup0()
new Uri("smb://" + name + "/") : new Uri(context.Url.AbsoluteUri + ? new Uri("smb://" + name + "/")
name + ((attributes & AttrDirectory) > 0 ? "/" : string.Empty))) : new Uri(context.Url.AbsoluteUri + name + ((attributes & AttrDirectory) > 0
? "/"
: string.Empty)))
{ {
Auth = context.Auth; Auth = context.Auth;
if (context._share != null) if (context._share != null)
@ -846,8 +850,7 @@ namespace SharpCifs.Smb
return; return;
} }
Connect0(); Connect0();
DfsReferral dr = Dfs.Resolve(Tree.Session.transport.TconHostName, Tree.Share, Unc DfsReferral dr = Dfs.Resolve(Tree.Session.transport.TconHostName, Tree.Share, Unc, Auth);
, Auth);
if (dr != null) if (dr != null)
{ {
string service = null; string service = null;
@ -946,8 +949,10 @@ namespace SharpCifs.Smb
dunc = "\\" + dr.Path + dunc; dunc = "\\" + dr.Path + dunc;
} }
Unc = dunc; Unc = dunc;
if (request != null && request.Path != null && request.Path.EndsWith("\\") && dunc if (request != null
.EndsWith("\\") == false) && request.Path != null
&& request.Path.EndsWith("\\")
&& dunc.EndsWith("\\") == false)
{ {
dunc += "\\"; dunc += "\\";
} }
@ -959,8 +964,10 @@ namespace SharpCifs.Smb
} }
else else
{ {
if (Tree.InDomainDfs && !(request is NtTransQuerySecurityDesc) && !(request is SmbComClose if (Tree.InDomainDfs
) && !(request is SmbComFindClose2)) && !(request is NtTransQuerySecurityDesc)
&& !(request is SmbComClose)
&& !(request is SmbComFindClose2))
{ {
throw new SmbException(NtStatus.NtStatusNotFound, false); throw new SmbException(NtStatus.NtStatusNotFound, false);
} }
@ -972,10 +979,9 @@ 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 (;;)
{ {
ResolveDfs(request); ResolveDfs(request);
try try
@ -1099,8 +1105,8 @@ namespace SharpCifs.Smb
{ {
throw; throw;
} }
Addresses = UniAddress.GetAllByName(NtlmPasswordAuthentication.DefaultDomain, true Addresses = UniAddress.GetAllByName(NtlmPasswordAuthentication.DefaultDomain,
); true);
} }
} }
else else
@ -1201,8 +1207,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);
@ -1243,7 +1249,7 @@ namespace SharpCifs.Smb
} }
GetUncPath0(); GetUncPath0();
GetFirstAddress(); GetFirstAddress();
for (; ; ) for (;;)
{ {
try try
{ {
@ -1291,8 +1297,13 @@ 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, flags, access, _shareAccess SmbComNtCreateAndX request = new SmbComNtCreateAndX(Unc,
, attrs, options, null); flags,
access,
_shareAccess,
attrs,
options,
null);
if (this is SmbNamedPipe) if (this is SmbNamedPipe)
{ {
request.Flags0 |= 0x16; request.Flags0 |= 0x16;
@ -1510,8 +1521,10 @@ namespace SharpCifs.Smb
i++; i++;
break; break;
} }
if ((i + 1) < length && instr[i] == '.' && instr[i + 1] == '.' && ((i + 2) >= length if ((i + 1) < length
|| instr[i + 2] == '/')) && instr[i] == '.'
&& instr[i + 1] == '.'
&& ((i + 2) >= length || instr[i + 2] == '/'))
{ {
i += 2; i += 2;
if (o == 1) if (o == 1)
@ -1768,15 +1781,17 @@ namespace SharpCifs.Smb
} }
if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs)) if (Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs))
{ {
Trans2QueryPathInformationResponse response = new Trans2QueryPathInformationResponse Trans2QueryPathInformationResponse response
(infoLevel); = new Trans2QueryPathInformationResponse(infoLevel);
Send(new Trans2QueryPathInformation(path, infoLevel), response); Send(new Trans2QueryPathInformation(path, infoLevel), response);
return response.Info; return response.Info;
} }
else else
{ {
SmbComQueryInformationResponse response = new SmbComQueryInformationResponse(Tree SmbComQueryInformationResponse response
.Session.transport.Server.ServerTimeZone * 1000 * 60L); = new SmbComQueryInformationResponse(Tree.Session.transport.Server.ServerTimeZone
* 1000
* 60L);
Send(new SmbComQueryInformation(path), response); Send(new SmbComQueryInformation(path), response);
return response; return response;
} }
@ -1835,8 +1850,8 @@ namespace SharpCifs.Smb
else else
{ {
// treeConnect is good enough // treeConnect is good enough
IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO IInfo info = QueryPath(GetUncPath0(),
); Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO);
_attributes = info.GetAttributes(); _attributes = info.GetAttributes();
_createTime = info.GetCreateTime(); _createTime = info.GetCreateTime();
_lastModified = info.GetLastWriteTime(); _lastModified = info.GetLastWriteTime();
@ -2174,8 +2189,10 @@ 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, AttrDirectory | AttrHidden | AttrSystem, null, null return ListFiles(wildcard,
); AttrDirectory | AttrHidden | AttrSystem,
null,
null);
} }
/// <summary>List the contents of this SMB resource.</summary> /// <summary>List the contents of this SMB resource.</summary>
@ -2208,8 +2225,10 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual string[] List(string wildcard, int searchAttributes, ISmbFilenameFilter internal virtual string[] List(string wildcard,
fnf, ISmbFileFilter ff) int searchAttributes,
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);
@ -2218,8 +2237,10 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual SmbFile[] ListFiles(string wildcard, int searchAttributes internal virtual SmbFile[] ListFiles(string wildcard,
, ISmbFilenameFilter fnf, ISmbFileFilter ff) int searchAttributes,
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);
@ -2228,8 +2249,12 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual void DoEnum(List<object> list, bool files, string wildcard, int searchAttributes internal virtual void DoEnum(List<object> list,
, ISmbFilenameFilter fnf, ISmbFileFilter ff) bool files,
string wildcard,
int searchAttributes,
ISmbFilenameFilter fnf,
ISmbFileFilter ff)
{ {
if (ff != null && ff is DosFileFilter) if (ff != null && ff is DosFileFilter)
{ {
@ -2242,7 +2267,9 @@ namespace SharpCifs.Smb
} }
try try
{ {
int hostlen = Url.GetHost() != null ? Url.GetHost().Length : 0; int hostlen = Url.GetHost() != null
? 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);
@ -2285,8 +2312,12 @@ 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, bool files, string wildcard, int internal virtual void DoShareEnum(List<object> list,
searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff) bool files,
string wildcard,
int searchAttributes,
ISmbFilenameFilter fnf,
ISmbFileFilter ff)
{ {
string p = Url.AbsolutePath; string p = Url.AbsolutePath;
IOException last = null; IOException last = null;
@ -2397,8 +2428,13 @@ 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, name, e.GetType(), AttrReadonly SmbFile f = new SmbFile(this,
| AttrDirectory, 0L, 0L, 0L); name,
e.GetType(),
AttrReadonly | AttrDirectory,
0L,
0L,
0L);
if (ff != null && ff.Accept(f) == false) if (ff != null && ff.Accept(f) == false)
{ {
continue; continue;
@ -2421,8 +2457,10 @@ namespace SharpCifs.Smb
MsrpcDfsRootEnum rpc; MsrpcDfsRootEnum rpc;
DcerpcHandle handle = null; DcerpcHandle handle = null;
IFileEntry[] entries; IFileEntry[] entries;
handle = DcerpcHandle.GetHandle("ncacn_np:" + GetAddress().GetHostAddress() + "[\\PIPE\\netdfs]" handle = DcerpcHandle.GetHandle("ncacn_np:"
, Auth); + GetAddress().GetHostAddress()
+ "[\\PIPE\\netdfs]",
Auth);
try try
{ {
rpc = new MsrpcDfsRootEnum(GetServer()); rpc = new MsrpcDfsRootEnum(GetServer());
@ -2455,8 +2493,10 @@ 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:" + GetAddress().GetHostAddress() + "[\\PIPE\\srvsvc]" handle = DcerpcHandle.GetHandle("ncacn_np:"
, Auth); + GetAddress().GetHostAddress()
+ "[\\PIPE\\srvsvc]",
Auth);
try try
{ {
handle.Sendrecv(rpc); handle.Sendrecv(rpc);
@ -2498,17 +2538,23 @@ 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, bool files, string wildcard internal virtual void DoNetServerEnum(List<object> list,
, int searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff) bool files,
string wildcard,
int searchAttributes,
ISmbFilenameFilter fnf,
ISmbFileFilter ff)
{ {
int listType = Url.GetHost().Length == 0 ? 0 : GetType(); int listType = Url.GetHost().Length == 0
? 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, NetServerEnum2 req = new NetServerEnum2(Tree.Session.transport.Server.OemDomainName,
.SvTypeDomainEnum); NetServerEnum2.SvTypeDomainEnum);
resp = new NetServerEnum2Response(); resp = new NetServerEnum2Response();
} }
else else
@ -2545,8 +2591,13 @@ 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, name, e.GetType(), AttrReadonly SmbFile f = new SmbFile(this,
| AttrDirectory, 0L, 0L, 0L); name,
e.GetType(),
AttrReadonly | AttrDirectory,
0L,
0L,
0L);
if (ff != null && ff.Accept(f) == false) if (ff != null && ff.Accept(f) == false)
{ {
continue; continue;
@ -2575,8 +2626,12 @@ 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, bool files, string wildcard internal virtual void DoFindFirstNext(List<object> list,
, int searchAttributes, ISmbFilenameFilter fnf, ISmbFileFilter ff) bool files,
string wildcard,
int searchAttributes,
ISmbFilenameFilter fnf,
ISmbFileFilter ff)
{ {
SmbComTransaction req; SmbComTransaction req;
Trans2FindFirst2Response resp; Trans2FindFirst2Response resp;
@ -2597,7 +2652,7 @@ namespace SharpCifs.Smb
sid = resp.Sid; sid = resp.Sid;
req = new Trans2FindNext2(sid, resp.ResumeKey, resp.LastName); req = new Trans2FindNext2(sid, resp.ResumeKey, resp.LastName);
resp.SubCommand = SmbComTransaction.Trans2FindNext2; resp.SubCommand = SmbComTransaction.Trans2FindNext2;
for (; ; ) for (;;)
{ {
for (int i = 0; i < resp.NumEntries; i++) for (int i = 0; i < resp.NumEntries; i++)
{ {
@ -2620,8 +2675,13 @@ namespace SharpCifs.Smb
} }
if (name.Length > 0) if (name.Length > 0)
{ {
SmbFile f = new SmbFile(this, name, TypeFilesystem, e.GetAttributes SmbFile f = new SmbFile(this,
(), e.CreateTime(), e.LastModified(), e.Length()); name,
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;
@ -2722,7 +2782,10 @@ namespace SharpCifs.Smb
: base("JCIFS-WriterThread") : base("JCIFS-WriterThread")
{ {
this._enclosing = enclosing; this._enclosing = enclosing;
UseNtSmbs = this._enclosing.Tree.Session.transport.HasCapability(SmbConstants.CapNtSmbs); UseNtSmbs = this._enclosing.Tree
.Session
.transport
.HasCapability(SmbConstants.CapNtSmbs);
if (UseNtSmbs) if (UseNtSmbs)
{ {
Reqx = new SmbComWriteAndX(); Reqx = new SmbComWriteAndX();
@ -2755,7 +2818,7 @@ namespace SharpCifs.Smb
{ {
try try
{ {
for (; ; ) for (;;)
{ {
Runtime.Notify(this); Runtime.Notify(this);
Ready = true; Ready = true;
@ -2795,8 +2858,12 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual void CopyTo0(SmbFile dest, byte[][] b, int bsize, WriterThread internal virtual void CopyTo0(SmbFile dest,
w, SmbComReadAndX req, SmbComReadAndXResponse resp) byte[][] b,
int bsize,
WriterThread w,
SmbComReadAndX req,
SmbComReadAndXResponse resp)
{ {
int i; int i;
if (_attrExpiration < Runtime.CurrentTimeMillis()) if (_attrExpiration < Runtime.CurrentTimeMillis())
@ -2805,8 +2872,8 @@ namespace SharpCifs.Smb
_createTime = 0L; _createTime = 0L;
_lastModified = 0L; _lastModified = 0L;
_isExists = false; _isExists = false;
IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO IInfo info = QueryPath(GetUncPath0(),
); Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO);
_attributes = info.GetAttributes(); _attributes = info.GetAttributes();
_createTime = info.GetCreateTime(); _createTime = info.GetCreateTime();
_lastModified = info.GetLastWriteTime(); _lastModified = info.GetLastWriteTime();
@ -2827,8 +2894,8 @@ namespace SharpCifs.Smb
} }
catch (SmbException se) catch (SmbException se)
{ {
if (se.GetNtStatus() != NtStatus.NtStatusAccessDenied && se.GetNtStatus() != NtStatus if (se.GetNtStatus() != NtStatus.NtStatusAccessDenied
.NtStatusObjectNameCollision) && se.GetNtStatus() != NtStatus.NtStatusObjectNameCollision)
{ {
throw; throw;
} }
@ -2839,8 +2906,13 @@ namespace SharpCifs.Smb
{ {
for (i = 0; i < files.Length; i++) for (i = 0; i < files.Length; i++)
{ {
ndest = new SmbFile(dest, files[i].GetName(), files[i].Type, files[i]._attributes, ndest = new SmbFile(dest,
files[i]._createTime, files[i]._lastModified, files[i]._size); files[i].GetName(),
files[i].Type,
files[i]._attributes,
files[i]._createTime,
files[i]._lastModified,
files[i]._size);
files[i].CopyTo0(ndest, b, bsize, w, req, resp); files[i].CopyTo0(ndest, b, bsize, w, req, resp);
} }
} }
@ -2861,16 +2933,20 @@ namespace SharpCifs.Smb
Open(ORdonly, 0, AttrNormal, 0); Open(ORdonly, 0, AttrNormal, 0);
try try
{ {
dest.Open(OCreat | OWronly | OTrunc, SmbConstants.FileWriteData | dest.Open(OCreat | OWronly | OTrunc,
SmbConstants.FileWriteAttributes, _attributes, 0); SmbConstants.FileWriteData | SmbConstants.FileWriteAttributes,
_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, SmbConstants.FileWriteData | dest.Open(OCreat | OWronly | OTrunc,
SmbConstants.FileWriteAttributes, _attributes, 0); SmbConstants.FileWriteData | SmbConstants.FileWriteAttributes,
_attributes,
0);
} }
else else
{ {
@ -2879,7 +2955,7 @@ namespace SharpCifs.Smb
} }
i = 0; i = 0;
off = 0L; off = 0L;
for (; ; ) for (;;)
{ {
req.SetParam(Fid, off, bsize); req.SetParam(Fid, off, bsize);
resp.SetParam(b[i], 0); resp.SetParam(b[i], 0);
@ -2914,16 +2990,19 @@ 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, _attributes, _createTime, _lastModified dest.Send(new Trans2SetFileInformation(dest.Fid,
), new Trans2SetFileInformationResponse()); _attributes,
_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 [" + ToString() + "] to [" throw new SmbException("Failed to copy file from "
+ dest + "]", se); + "[" + ToString() + "] to [" + dest + "]", se);
} }
if (Log.Level > 1) if (Log.Level > 1)
{ {
@ -2976,8 +3055,8 @@ namespace SharpCifs.Smb
ResolveDfs(null); ResolveDfs(null);
try try
{ {
if (GetAddress().Equals(dest.GetAddress()) && _canon.RegionMatches(true, 0, dest._canon if (GetAddress().Equals(dest.GetAddress())
, 0, Math.Min(_canon.Length, dest._canon.Length))) && _canon.RegionMatches(true, 0, dest._canon, 0, Math.Min(_canon.Length, dest._canon.Length)))
{ {
throw new SmbException("Source and destination paths overlap."); throw new SmbException("Source and destination paths overlap.");
} }
@ -2987,7 +3066,8 @@ namespace SharpCifs.Smb
} }
w = new WriterThread(this); w = new WriterThread(this);
w.SetDaemon(true); w.SetDaemon(true);
w.Start(); w.Start(true);
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)
@ -3043,8 +3123,8 @@ namespace SharpCifs.Smb
_createTime = 0L; _createTime = 0L;
_lastModified = 0L; _lastModified = 0L;
_isExists = false; _isExists = false;
IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO IInfo info = QueryPath(GetUncPath0(),
); Trans2QueryPathInformationResponse.SMB_QUERY_FILE_BASIC_INFO);
_attributes = info.GetAttributes(); _attributes = info.GetAttributes();
_createTime = info.GetCreateTime(); _createTime = info.GetCreateTime();
_lastModified = info.GetLastWriteTime(); _lastModified = info.GetLastWriteTime();
@ -3063,8 +3143,7 @@ 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();
@ -3117,8 +3196,8 @@ namespace SharpCifs.Smb
{ {
if (GetUncPath0().Length > 1 && Type != TypeNamedPipe) if (GetUncPath0().Length > 1 && Type != TypeNamedPipe)
{ {
IInfo info = QueryPath(GetUncPath0(), Trans2QueryPathInformationResponse.SMB_QUERY_FILE_STANDARD_INFO IInfo info = QueryPath(GetUncPath0(),
); Trans2QueryPathInformationResponse.SMB_QUERY_FILE_STANDARD_INFO);
_size = info.GetSize(); _size = info.GetSize();
} }
else else
@ -3272,10 +3351,14 @@ namespace SharpCifs.Smb
int dir; int dir;
Exists(); Exists();
dir = _attributes & AttrDirectory; dir = _attributes & AttrDirectory;
f = Open0(ORdonly, SmbConstants.FileWriteAttributes, dir, dir != 0 ? 0x0001 f = Open0(ORdonly,
SmbConstants.FileWriteAttributes,
dir,
dir != 0
? 0x0001
: 0x0040); : 0x0040);
Send(new Trans2SetFileInformation(f, attrs | dir, ctime, mtime), new Trans2SetFileInformationResponse Send(new Trans2SetFileInformation(f, attrs | dir, ctime, mtime),
()); new Trans2SetFileInformationResponse());
Close(f, 0L); Close(f, 0L);
_attrExpiration = 0; _attrExpiration = 0;
} }
@ -3430,8 +3513,7 @@ 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;
@ -3646,8 +3728,7 @@ 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, file.Tree.Session _readSize = Math.Min(file.Tree.Session.transport.RcvBufSize - 70,
.transport.Server.MaxBufferSize - 70); file.Tree.Session.transport.Server.MaxBufferSize - 70);
} }
protected internal virtual IOException SeToIoe(SmbException se) protected internal virtual IOException SeToIoe(SmbException se)
@ -194,7 +194,9 @@ namespace SharpCifs.Smb
int n; int n;
do do
{ {
r = len > _readSize ? _readSize : len; r = len > _readSize
? _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);
@ -207,12 +209,13 @@ 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 && se.GetNtStatus() == NtStatus.NtStatusPipeBroken) if (File.Type == SmbFile.TypeNamedPipe
&& se.GetNtStatus() == NtStatus.NtStatusPipeBroken)
{ {
return -1; return -1;
} }
@ -230,7 +233,6 @@ namespace SharpCifs.Smb
} }
while (len > 0 && n == r); while (len > 0 && n == r);
return (int)(_fp - start); return (int)(_fp - start);
} }
@ -255,13 +257,12 @@ namespace SharpCifs.Smb
try try
{ {
pipe = (SmbNamedPipe)File; pipe = (SmbNamedPipe)File;
File.Open(SmbFile.OExcl, pipe.PipeType & 0xFF0000, SmbFile.AttrNormal File.Open(SmbFile.OExcl, pipe.PipeType & 0xFF0000, SmbFile.AttrNormal, 0);
, 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 || resp.status if (resp.status == TransPeekNamedPipeResponse.StatusDisconnected
== TransPeekNamedPipeResponse.StatusServerEndClosed) || resp.status == TransPeekNamedPipeResponse.StatusServerEndClosed)
{ {
File.Opened = false; File.Opened = false;
return 0; return 0;
@ -300,7 +301,8 @@ 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,8 +100,7 @@ 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)
)
{ {
} }
@ -120,9 +119,12 @@ 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) : this(file, append, append public SmbFileOutputStream(SmbFile file, bool append)
? SmbFile.OCreat | SmbFile.OWronly | SmbFile.OAppend : SmbFile.OCreat | SmbFile : this(file,
.OWronly | SmbFile.OTrunc) append,
append
? SmbFile.OCreat | SmbFile.OWronly | SmbFile.OAppend
: SmbFile.OCreat | SmbFile.OWronly | SmbFile.OTrunc)
{ {
} }
@ -150,8 +152,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) : this(new SmbFile(url, string.Empty public SmbFileOutputStream(string url, int shareAccess)
, null, shareAccess), false) : this(new SmbFile(url, string.Empty, null, shareAccess), false)
{ {
} }
@ -182,15 +184,16 @@ 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), new TransWaitNamedPipeResponse file.Send(new TransWaitNamedPipe("\\pipe" + file.Unc),
()); new TransWaitNamedPipeResponse());
} }
file.Open(openFlags, _access | SmbConstants.FileWriteData, SmbFile.AttrNormal, file.Open(openFlags,
_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();
@ -252,7 +255,9 @@ namespace SharpCifs.Smb
// ensure file is open // ensure file is open
if (_file.IsOpen() == false) if (_file.IsOpen() == false)
{ {
_file.Open(_openFlags, _access | SmbConstants.FileWriteData, SmbFile.AttrNormal, _file.Open(_openFlags,
_access | SmbConstants.FileWriteData,
SmbFile.AttrNormal,
0); 0);
if (_append) if (_append)
{ {
@ -275,8 +280,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), new TransWaitNamedPipeResponse _file.Send(new TransWaitNamedPipe("\\pipe" + _file.Unc),
()); new TransWaitNamedPipeResponse());
} }
WriteDirect(b, off, len, 0); WriteDirect(b, off, len, 0);
} }
@ -295,10 +300,12 @@ 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) : base public SmbNamedPipe(Uri url, int pipeType, NtlmPasswordAuthentication auth)
(url, auth) : base(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 || (PipeType & PipeTypeTransact if ((PipeType & PipeTypeCall) == PipeTypeCall
) == PipeTypeTransact) || (PipeType & PipeTypeTransact) == PipeTypeTransact)
{ {
PipeIn = new TransactNamedPipeInputStream(this); PipeIn = new TransactNamedPipeInputStream(this);
} }
else else
{ {
PipeIn = new SmbFileInputStream(this, (PipeType & unchecked((int)(0xFFFF00FF))) | PipeIn = new SmbFileInputStream(this,
OExcl); (PipeType & unchecked((int)(0xFFFF00FF))) | OExcl);
} }
} }
return PipeIn; return PipeIn;
@ -193,15 +193,16 @@ namespace SharpCifs.Smb
{ {
if (PipeOut == null) if (PipeOut == null)
{ {
if ((PipeType & PipeTypeCall) == PipeTypeCall || (PipeType & PipeTypeTransact if ((PipeType & PipeTypeCall) == PipeTypeCall
) == PipeTypeTransact) || (PipeType & PipeTypeTransact) == PipeTypeTransact)
{ {
PipeOut = new TransactNamedPipeOutputStream(this); PipeOut = new TransactNamedPipeOutputStream(this);
} }
else else
{ {
PipeOut = new SmbFileOutputStream(this, false, (PipeType & unchecked((int)(0xFFFF00FF PipeOut = new SmbFileOutputStream(this,
))) | OExcl); false,
(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) : this(new SmbFile public SmbRandomAccessFile(string url, string mode, int shareAccess)
(url, string.Empty, null, shareAccess), mode) : this(new SmbFile(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), _writeAndxResp _file.Send(new SmbComWriteAndX(_file.Fid, _fp, len - w, b, off, w, null),
); _writeAndxResp);
_fp += _writeAndxResp.Count; _fp += _writeAndxResp.Count;
len -= (int)_writeAndxResp.Count; len -= (int)_writeAndxResp.Count;
off += (int)_writeAndxResp.Count; off += (int)_writeAndxResp.Count;
@ -232,7 +232,13 @@ 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, (int)(newLength & unchecked(0xFFFFFFFFL)), 0, _tmp, 0, 0), rsp); _file.Send(new SmbComWrite(_file.Fid,
(int)(newLength & unchecked(0xFFFFFFFFL)),
0,
_tmp,
0,
0),
rsp);
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
@ -462,8 +468,10 @@ 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;
@ -476,7 +484,8 @@ 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)
@ -488,7 +497,11 @@ 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) ? (ch > unchecked(0x7FF) ? 3 : 2) : 1; size += ch > unchecked(0x07F)
? (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 = Config.GetProperty("jcifs.smb.client.logonShare" private static readonly string LogonShare
, null); = Config.GetProperty("jcifs.smb.client.logonShare", null);
private static readonly int LookupRespLimit = Config.GetInt("jcifs.netbios.lookupRespLimit" private static readonly int LookupRespLimit
, 3); = Config.GetInt("jcifs.netbios.lookupRespLimit", 3);
private static readonly string Domain = Config.GetProperty("jcifs.smb.client.domain" private static readonly string Domain
, null); = Config.GetProperty("jcifs.smb.client.domain", null);
private static readonly string Username = Config.GetProperty("jcifs.smb.client.username" private static readonly string Username
, null); = Config.GetProperty("jcifs.smb.client.username", null);
private static readonly int CachePolicy = Config.GetInt("jcifs.netbios.cachePolicy" private static readonly int CachePolicy
, 60 * 10) * 60; = Config.GetInt("jcifs.netbios.cachePolicy", 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("Default credentials (jcifs.smb.client.username/password)" SmbTransport.LogStatic.WriteLine(
+ " not specified. SMB signing may not work propertly." + " Skipping DC interrogation." "Default credentials (jcifs.smb.client.username/password)"
); + " 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,8 +86,7 @@ namespace SharpCifs.Smb
{ {
if (DcListExpiration < now) if (DcListExpiration < now)
{ {
NbtAddress[] list = NbtAddress.GetAllByName(Domain, 0x1C, null, NbtAddress[] list = NbtAddress.GetAllByName(Domain, 0x1C, null, null);
null);
DcListExpiration = now + CachePolicy * 1000L; DcListExpiration = now + CachePolicy * 1000L;
if (list != null && list.Length > 0) if (list != null && list.Length > 0)
{ {
@ -131,8 +130,8 @@ namespace SharpCifs.Smb
while (retry-- > 0); while (retry-- > 0);
DcListExpiration = now + 1000 * 60 * 15; DcListExpiration = now + 1000 * 60 * 15;
} }
throw new UnknownHostException("Failed to negotiate with a suitable domain controller for " throw new UnknownHostException(
+ Domain); "Failed to negotiate with a suitable domain controller for " + Domain);
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
@ -174,11 +173,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).GetSmbSession(auth).GetSmbTree SmbTree tree = SmbTransport.GetSmbTransport(dc, port)
(LogonShare, null); .GetSmbSession(auth)
.GetSmbTree(LogonShare, null);
if (LogonShare == null) if (LogonShare == null)
{ {
tree.TreeConnect(null, null); tree.TreeConnect(null, null);
@ -191,6 +190,19 @@ 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;
@ -213,8 +225,11 @@ namespace SharpCifs.Smb
internal string NetbiosName; internal string NetbiosName;
internal SmbSession(UniAddress address, int port, IPAddress localAddr, int localPort internal SmbSession(UniAddress address,
, NtlmPasswordAuthentication auth) int port,
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;
@ -235,14 +250,16 @@ 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;
@ -269,8 +286,11 @@ namespace SharpCifs.Smb
{ {
if (transport == null) if (transport == null)
{ {
transport = SmbTransport.GetSmbTransport(_address, _port, _localAddr, _localPort, null transport = SmbTransport.GetSmbTransport(_address,
); _port,
_localAddr,
_localPort,
null);
} }
return transport; return transport;
} }
@ -318,8 +338,7 @@ 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())
{ {
@ -352,8 +371,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 + ",primaryDomain=" transport.Log.WriteLine("sessionSetup: accountName=" + Auth.Username
+ Auth.Domain); + ",primaryDomain=" + Auth.Domain);
} }
Uid = 0; Uid = 0;
do do
@ -362,8 +381,8 @@ namespace SharpCifs.Smb
{ {
case 10: case 10:
{ {
if (Auth != NtlmPasswordAuthentication.Anonymous && transport.HasCapability(SmbConstants if (Auth != NtlmPasswordAuthentication.Anonymous
.CapExtendedSecurity)) && transport.HasCapability(SmbConstants.CapExtendedSecurity))
{ {
state = 20; state = 20;
break; break;
@ -372,15 +391,18 @@ namespace SharpCifs.Smb
response = new SmbComSessionSetupAndXResponse(andxResponse); response = new SmbComSessionSetupAndXResponse(andxResponse);
if (transport.IsSignatureSetupRequired(Auth)) if (transport.IsSignatureSetupRequired(Auth))
{ {
if (Auth.HashesExternal && NtlmPasswordAuthentication.DefaultPassword != NtlmPasswordAuthentication if (Auth.HashesExternal
.Blank) && NtlmPasswordAuthentication.DefaultPassword
!= NtlmPasswordAuthentication.Blank)
{ {
transport.GetSmbSession(NtlmPasswordAuthentication.Default).GetSmbTree(LogonShare transport.GetSmbSession(NtlmPasswordAuthentication.Default)
, null).TreeConnect(null, null); .GetSmbTree(LogonShare, null)
.TreeConnect(null, null);
} }
else else
{ {
byte[] signingKey = Auth.GetSigningKey(transport.Server.EncryptionKey); byte[] signingKey
= Auth.GetSigningKey(transport.Server.EncryptionKey);
request.Digest = new SigningDigest(signingKey, false); request.Digest = new SigningDigest(signingKey, false);
} }
} }
@ -397,9 +419,10 @@ namespace SharpCifs.Smb
{ {
ex = se; ex = se;
} }
if (response.IsLoggedInAsGuest && Runtime.EqualsIgnoreCase("GUEST", Auth. if (response.IsLoggedInAsGuest
Username) == false && transport.Server.Security != SmbConstants.SecurityShare && && Runtime.EqualsIgnoreCase("GUEST", Auth.Username) == false
Auth != NtlmPasswordAuthentication.Anonymous) && transport.Server.Security != SmbConstants.SecurityShare
&& Auth != NtlmPasswordAuthentication.Anonymous)
{ {
throw new SmbAuthException(NtStatus.NtStatusLogonFailure); throw new SmbAuthException(NtStatus.NtStatusLogonFailure);
} }
@ -421,8 +444,9 @@ namespace SharpCifs.Smb
{ {
if (nctx == null) if (nctx == null)
{ {
bool doSigning = (transport.Flags2 & SmbConstants.Flags2SecuritySignatures bool doSigning
) != 0; = (transport.Flags2
& SmbConstants.Flags2SecuritySignatures) != 0;
nctx = new NtlmContext(Auth, doSigning); nctx = new NtlmContext(Auth, doSigning);
} }
if (SmbTransport.LogStatic.Level >= 4) if (SmbTransport.LogStatic.Level >= 4)
@ -485,8 +509,9 @@ namespace SharpCifs.Smb
{ {
} }
} }
if (response.IsLoggedInAsGuest && Runtime.EqualsIgnoreCase("GUEST", Auth. if (response.IsLoggedInAsGuest
Username) == false) && Runtime.EqualsIgnoreCase("GUEST", Auth.Username)
== false)
{ {
throw new SmbAuthException(NtStatus.NtStatusLogonFailure); throw new SmbAuthException(NtStatus.NtStatusLogonFailure);
} }
@ -563,8 +588,10 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbSession[accountName=" + Auth.Username + ",primaryDomain=" + Auth.Domain return "SmbSession[accountName=" + Auth.Username
+ ",uid=" + Uid + ",connectionState=" + ConnectionState + "]"; + ",primaryDomain=" + Auth.Domain
+ ",uid=" + Uid
+ ",connectionState=" + ConnectionState + "]";
} }
} }
} }

View File

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

View File

@ -31,25 +31,30 @@ 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, port, SmbConstants.Laddr, SmbConstants.Lport, null); return GetSmbTransport(address,
port,
SmbConstants.Laddr,
SmbConstants.Lport,
null);
} }
} }
internal static SmbTransport GetSmbTransport(UniAddress address, int port internal static SmbTransport GetSmbTransport(UniAddress address,
, IPAddress localAddr, int localPort, string hostName) int port,
IPAddress localAddr,
int localPort,
string hostName)
{ {
lock (typeof(SmbTransport)) lock (typeof(SmbTransport))
{ {
@ -59,18 +64,19 @@ namespace SharpCifs.Smb
{ {
if (SmbConstants.SsnLimit != 1) if (SmbConstants.SsnLimit != 1)
{ {
conn = conn = SmbConstants.Connections
SmbConstants.Connections.FirstOrDefault( .FirstOrDefault(c => c.Matches(address,
c => port,
c.Matches(address, port, localAddr, localPort, hostName) && localAddr,
(SmbConstants.SsnLimit == localPort,
0 || c.Sessions.Count < SmbConstants.SsnLimit)); hostName)
&& (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);
@ -80,6 +86,26 @@ 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;
@ -174,8 +200,10 @@ namespace SharpCifs.Smb
internal string TconHostName; internal string TconHostName;
internal SmbTransport(UniAddress address, int port, IPAddress localAddr, int localPort internal SmbTransport(UniAddress address,
) int port,
IPAddress localAddr,
int localPort)
{ {
Server = new ServerData(this); Server = new ServerData(this);
this.Address = address; this.Address = address;
@ -206,7 +234,8 @@ namespace SharpCifs.Smb
return ssn; return ssn;
} }
if (SmbConstants.SoTimeout > 0 && SessionExpiration < (now = Runtime.CurrentTimeMillis())) if (SmbConstants.SoTimeout > 0
&& SessionExpiration < (now = Runtime.CurrentTimeMillis()))
{ {
SessionExpiration = now + SmbConstants.SoTimeout; SessionExpiration = now + SmbConstants.SoTimeout;
@ -222,16 +251,25 @@ namespace SharpCifs.Smb
} }
} }
internal virtual bool Matches(UniAddress address, int port, IPAddress localAddr, internal virtual bool Matches(UniAddress address,
int localPort, string hostName) int port,
IPAddress localAddr,
int localPort,
string hostName)
{ {
if (hostName == null) if (hostName == null)
{ {
hostName = address.GetHostName(); hostName = address.GetHostName();
} }
return (TconHostName == null || Runtime.EqualsIgnoreCase(hostName, TconHostName)) && address.Equals(this.Address) && (port == -1 || port == this.Port return (TconHostName == null
|| (port == 445 && this.Port == 139)) && (localAddr == this.LocalAddr || (localAddr || Runtime.EqualsIgnoreCase(hostName, TconHostName))
!= null && localAddr.Equals(this.LocalAddr))) && localPort == this.LocalPort; && address.Equals(this.Address)
&& (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>
@ -250,31 +288,36 @@ namespace SharpCifs.Smb
internal virtual bool IsSignatureSetupRequired(NtlmPasswordAuthentication auth) internal virtual bool IsSignatureSetupRequired(NtlmPasswordAuthentication auth)
{ {
return (Flags2 & SmbConstants.Flags2SecuritySignatures) != 0 && Digest == return (Flags2 & SmbConstants.Flags2SecuritySignatures) != 0
null && auth != NtlmPasswordAuthentication.Null && NtlmPasswordAuthentication.Null && Digest == null
.Equals(auth) == false; && auth != NtlmPasswordAuthentication.Null
&& 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, SocketType.Stream, ProtocolType.Tcp); Socket = new SocketEx(AddressFamily.InterNetwork,
if (LocalAddr != null) SocketType.Stream,
{ 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, NbtAddress.GetLocalName SessionServicePacket ssp = new SessionRequestPacket(calledName,
()); 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)
{ {
@ -317,7 +360,8 @@ namespace SharpCifs.Smb
default: default:
{ {
Disconnect(true); Disconnect(true);
throw new NbtException(NbtException.ErrSsnSrvc, errorCode); throw new NbtException(NbtException.ErrSsnSrvc,
errorCode);
} }
} }
break; break;
@ -326,8 +370,8 @@ namespace SharpCifs.Smb
case -1: case -1:
{ {
Disconnect(true); Disconnect(true);
throw new NbtException(NbtException.ErrSsnSrvc, NbtException.ConnectionRefused throw new NbtException(NbtException.ErrSsnSrvc,
); NbtException.ConnectionRefused);
} }
default: default:
@ -357,13 +401,18 @@ namespace SharpCifs.Smb
port = SmbConstants.DefaultPort; port = SmbConstants.DefaultPort;
} }
// 445 // 445
Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Socket = new SocketEx(AddressFamily.InterNetwork,
if (LocalAddr != null) SocketType.Stream,
{ 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();
@ -430,21 +479,28 @@ namespace SharpCifs.Smb
} }
catch (ConnectException) catch (ConnectException)
{ {
Port = (Port == -1 || Port == SmbConstants.DefaultPort) ? 139 : SmbConstants.DefaultPort; Port = (Port == -1 || Port == 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 ((Server.Capabilities & SmbConstants.CapExtendedSecurity) != SmbConstants.CapExtendedSecurity && Server if (
.EncryptionKeyLength != 8 && SmbConstants.LmCompatibility == 0) (Server.Capabilities & SmbConstants.CapExtendedSecurity)
!= SmbConstants.CapExtendedSecurity
&& Server.EncryptionKeyLength != 8
&& SmbConstants.LmCompatibility == 0
)
{ {
throw new SmbException("Unexpected encryption key length: " + Server.EncryptionKeyLength throw new SmbException("Unexpected encryption key length: "
); + Server.EncryptionKeyLength);
} }
TconHostName = Address.GetHostName(); TconHostName = Address.GetHostName();
if (Server.SignaturesRequired || (Server.SignaturesEnabled && SmbConstants.Signpref)) if (Server.SignaturesRequired
|| (Server.SignaturesEnabled && SmbConstants.Signpref))
{ {
Flags2 |= SmbConstants.Flags2SecuritySignatures; Flags2 |= SmbConstants.Flags2SecuritySignatures;
} }
@ -459,7 +515,8 @@ 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) == SmbConstants.CapExtendedSecurity) if ((Server.Capabilities & SmbConstants.CapExtendedSecurity)
== SmbConstants.CapExtendedSecurity)
{ {
Capabilities |= SmbConstants.CapExtendedSecurity; Capabilities |= SmbConstants.CapExtendedSecurity;
} }
@ -494,6 +551,7 @@ 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
@ -536,7 +594,7 @@ namespace SharpCifs.Smb
Log.WriteLine("New data read: " + this); Log.WriteLine("New data read: " + this);
Hexdump.ToHexdump(Log, Sbuf, 4, 32); Hexdump.ToHexdump(Log, Sbuf, 4, 32);
} }
for (; ; ) for (;;)
{ {
if (Sbuf[0] == 0x00 && Sbuf[1] == 0x00 && if (Sbuf[0] == 0x00 && Sbuf[1] == 0x00 &&
Sbuf[4] == 0xFF && Sbuf[4] == 0xFF &&
@ -575,8 +633,8 @@ namespace SharpCifs.Smb
{ {
Log.WriteLine(smb); Log.WriteLine(smb);
} }
while (smb is AndXServerMessageBlock && (smb = ((AndXServerMessageBlock)smb).Andx while (smb is AndXServerMessageBlock
) != null); && (smb = ((AndXServerMessageBlock)smb).Andx) != null);
if (Log.Level >= 6) if (Log.Level >= 6)
{ {
Hexdump.ToHexdump(Log, Buf, 4, n); Hexdump.ToHexdump(Log, Buf, 4, n);
@ -616,7 +674,9 @@ namespace SharpCifs.Smb
{ {
ServerMessageBlock resp = (ServerMessageBlock)response; ServerMessageBlock resp = (ServerMessageBlock)response;
resp.UseUnicode = UseUnicode; resp.UseUnicode = UseUnicode;
resp.ExtendedSecurity = (Capabilities & SmbConstants.CapExtendedSecurity) == SmbConstants.CapExtendedSecurity; resp.ExtendedSecurity
= (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);
@ -626,8 +686,10 @@ 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 && (errorCode == 0 || errorCode if (resp.Command == ServerMessageBlock.SmbComReadAndx
== unchecked((int)(0x80000005)))) && (errorCode == 0
|| errorCode == unchecked((int)(0x80000005)))
)
{ {
// overflow indicator normal for pipe // overflow indicator normal for pipe
SmbComReadAndXResponse r = (SmbComReadAndXResponse)resp; SmbComReadAndXResponse r = (SmbComReadAndXResponse)resp;
@ -684,8 +746,7 @@ 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)
@ -746,8 +807,7 @@ 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;
@ -809,7 +869,8 @@ namespace SharpCifs.Smb
timeout = resp.Expiration - Runtime.CurrentTimeMillis(); timeout = resp.Expiration - Runtime.CurrentTimeMillis();
if (timeout <= 0) if (timeout <= 0)
{ {
throw new TransportException(this + " timedout waiting for response to " + req); throw new TransportException(
this + " timedout waiting for response to " + req);
} }
} }
if (response.ErrorCode != 0) if (response.ErrorCode != 0)
@ -891,8 +952,9 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual DfsReferral GetDfsReferrals(NtlmPasswordAuthentication auth, string internal virtual DfsReferral GetDfsReferrals(NtlmPasswordAuthentication auth,
path, int rn) string path,
int rn)
{ {
SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null); SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null);
Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse(); Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();
@ -909,7 +971,7 @@ namespace SharpCifs.Smb
string[] arr = new string[4]; string[] arr = new string[4];
long expiration = Runtime.CurrentTimeMillis() + Dfs.Ttl * 1000; long expiration = Runtime.CurrentTimeMillis() + Dfs.Ttl * 1000;
int di = 0; int di = 0;
for (; ; ) for (;;)
{ {
dr.ResolveHashes = auth.HashesExternal; dr.ResolveHashes = auth.HashesExternal;
dr.Ttl = resp.Referrals[di].Ttl; dr.Ttl = resp.Referrals[di].Ttl;
@ -939,7 +1001,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 path, int rn) string path,
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,9 +56,10 @@ 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) && (service == null || return Runtime.EqualsIgnoreCase(this.Share, share)
service.StartsWith("??") || Runtime.EqualsIgnoreCase(this.Service, service && (service == null
)); || service.StartsWith("??")
|| Runtime.EqualsIgnoreCase(this.Service, service));
} }
public override bool Equals(object obj) public override bool Equals(object obj)
@ -72,8 +73,7 @@ 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,7 +103,8 @@ namespace SharpCifs.Smb
case ServerMessageBlock.SmbComTransaction: case ServerMessageBlock.SmbComTransaction:
case ServerMessageBlock.SmbComTransaction2: case ServerMessageBlock.SmbComTransaction2:
{ {
switch (((SmbComTransaction)request).SubCommand & unchecked(0xFF)) switch (((SmbComTransaction)request).SubCommand
& unchecked(0xFF))
{ {
case SmbComTransaction.NetShareEnum: case SmbComTransaction.NetShareEnum:
case SmbComTransaction.NetServerEnum2: case SmbComTransaction.NetServerEnum2:
@ -119,7 +120,8 @@ namespace SharpCifs.Smb
default: default:
{ {
throw new SmbException("Invalid operation for " + Service + " service"); throw new SmbException(
"Invalid operation for " + Service + " service");
} }
} }
break; break;
@ -127,15 +129,19 @@ namespace SharpCifs.Smb
default: default:
{ {
throw new SmbException("Invalid operation for " + Service + " service" + request); throw new SmbException(
"Invalid operation for " + Service + " service" + request);
} }
} }
} }
request.Tid = Tid; request.Tid = Tid;
if (InDfs && !Service.Equals("IPC") && !string.IsNullOrEmpty(request.Path)) if (InDfs
&& !Service.Equals("IPC")
&& !string.IsNullOrEmpty(request.Path))
{ {
request.Flags2 = SmbConstants.Flags2ResolvePathsInDfs; request.Flags2 = SmbConstants.Flags2ResolvePathsInDfs;
request.Path = '\\' + Session.Transport().TconHostName + '\\' + Share + request.Path; request.Path = '\\' + Session.Transport().TconHostName
+ '\\' + Share + request.Path;
} }
try try
{ {
@ -153,8 +159,8 @@ namespace SharpCifs.Smb
} }
/// <exception cref="SharpCifs.Smb.SmbException"></exception> /// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual void TreeConnect(ServerMessageBlock andx, ServerMessageBlock andxResponse internal virtual void TreeConnect(ServerMessageBlock andx,
) ServerMessageBlock andxResponse)
{ {
lock (Session.Transport()) lock (Session.Transport())
{ {
@ -184,13 +190,14 @@ namespace SharpCifs.Smb
Service = Service0; Service = Service0;
if (Session.transport.Log.Level >= 4) if (Session.transport.Log.Level >= 4)
{ {
Session.transport.Log.WriteLine("treeConnect: unc=" + unc + ",service=" + Service Session.transport.Log.WriteLine(
); "treeConnect: unc=" + unc
+ ",service=" + Service);
} }
SmbComTreeConnectAndXResponse response = new SmbComTreeConnectAndXResponse(andxResponse SmbComTreeConnectAndXResponse response
); = new SmbComTreeConnectAndXResponse(andxResponse);
SmbComTreeConnectAndX request = new SmbComTreeConnectAndX(Session, unc, Service, SmbComTreeConnectAndX request
andx); = new SmbComTreeConnectAndX(Session, unc, Service, andx);
Session.Send(request, response); Session.Send(request, response);
Tid = response.Tid; Tid = response.Tid;
Service = response.Service; Service = response.Service;
@ -242,9 +249,12 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "SmbTree[share=" + Share + ",service=" + Service + ",tid=" + Tid + ",inDfs=" return "SmbTree[share=" + Share
+ InDfs + ",inDomainDfs=" + InDomainDfs + ",connectionState=" + ConnectionState + ",service=" + Service
+ "]"; + ",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 = Config.GetInt("jcifs.smb.client.listSize" internal static readonly int ListSize
, DefaultListSize); = Config.GetInt("jcifs.smb.client.listSize", DefaultListSize);
internal static readonly int ListCount = Config.GetInt("jcifs.smb.client.listCount" internal static readonly int ListCount
, DefaultListCount); = Config.GetInt("jcifs.smb.client.listCount", 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, int bufferIndex, int internal override int ReadParametersWireFormat(byte[] buffer,
len) int bufferIndex,
int len)
{ {
return 0; return 0;
} }
@ -136,11 +136,14 @@ namespace SharpCifs.Smb
public override string ToString() public override string ToString()
{ {
return "Trans2FindFirst2[" + base.ToString() + ",searchAttributes=0x" return "Trans2FindFirst2["
+ Hexdump.ToHexString(_searchAttributes, 2) + ",searchCount=" + ListCount + ",flags=0x" + base.ToString()
+ Hexdump.ToHexString(_flags, 2) + ",informationLevel=0x" + Hexdump.ToHexString( + ",searchAttributes=0x" + Hexdump.ToHexString(_searchAttributes, 2)
_informationLevel, 3) + ",searchStorageType=" + _searchStorageType + ",filename=" + ",searchCount=" + ListCount
+ Path + "]"; + ",flags=0x" + Hexdump.ToHexString(_flags, 2)
+ ",informationLevel=0x" + Hexdump.ToHexString(_informationLevel, 3)
+ ",searchStorageType=" + _searchStorageType
+ ",filename=" + Path + "]";
} }
} }
} }

View File

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

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