update sharpcifs

pull/1154/head
Luke Pulverenti 7 years ago
parent 2b20163775
commit 23691e181b

@ -21,14 +21,17 @@ namespace SharpCifs.Dcerpc
{
public class DcerpcBind : DcerpcMessage
{
internal static readonly string[] ResultMessage = { "0", "DCERPC_BIND_ERR_ABSTRACT_SYNTAX_NOT_SUPPORTED"
, "DCERPC_BIND_ERR_PROPOSED_TRANSFER_SYNTAXES_NOT_SUPPORTED", "DCERPC_BIND_ERR_LOCAL_LIMIT_EXCEEDED"
internal static readonly string[] ResultMessage =
{
"0",
"DCERPC_BIND_ERR_ABSTRACT_SYNTAX_NOT_SUPPORTED",
"DCERPC_BIND_ERR_PROPOSED_TRANSFER_SYNTAXES_NOT_SUPPORTED",
"DCERPC_BIND_ERR_LOCAL_LIMIT_EXCEEDED"
};
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()

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

@ -18,8 +18,7 @@ namespace SharpCifs.Dcerpc
{
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);

@ -36,13 +36,29 @@ namespace SharpCifs.Dcerpc
public static int DcerpcFaultProtoError = unchecked(0x1c01000b);
public static int[] DcerpcFaultCodes = { DcerpcFaultOther, DcerpcFaultAccessDenied
, DcerpcFaultCantPerform, DcerpcFaultNdr, DcerpcFaultInvalidTag, DcerpcFaultContextMismatch
, DcerpcFaultOpRngError, DcerpcFaultUnkIf, DcerpcFaultProtoError };
public static string[] DcerpcFaultMessages = { "DCERPC_FAULT_OTHER"
, "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" };
public static int[] DcerpcFaultCodes = {
DcerpcFaultOther,
DcerpcFaultAccessDenied,
DcerpcFaultCantPerform,
DcerpcFaultNdr,
DcerpcFaultInvalidTag,
DcerpcFaultContextMismatch,
DcerpcFaultOpRngError,
DcerpcFaultUnkIf,
DcerpcFaultProtoError
};
public static string[] DcerpcFaultMessages =
{
"DCERPC_FAULT_OTHER",
"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"
};
}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -23,8 +23,7 @@ namespace SharpCifs.Netbios
{
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();

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

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

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

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

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

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

@ -94,14 +94,26 @@ namespace SharpCifs.Netbios
n = Runtime.GetStringForBytes(src, srcIndex, j - srcIndex + 1, Name.OemEncoding
);
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;
isBeingDeleted = ((src[srcIndex + 16] & unchecked(0x10)) == unchecked(0x10)) ? true : false;
isInConflict = ((src[srcIndex + 16] & unchecked(0x08)) == unchecked(0x08)) ? true : 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)))
isBeingDeleted = ((src[srcIndex + 16] & unchecked(0x10)) == unchecked(0x10))
? true
: false;
isInConflict = ((src[srcIndex + 16] & unchecked(0x08)) == unchecked(0x08))
? true
: 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)
{
@ -120,8 +132,14 @@ namespace SharpCifs.Netbios
}
else
{
AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope), _queryAddress.Address
, groupName, ownerNodeType, isBeingDeleted, isInConflict, isActive, isPermanent,
AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope),
_queryAddress.Address,
groupName,
ownerNodeType,
isBeingDeleted,
isInConflict,
isActive,
isPermanent,
_macAddress);
}
}

@ -47,8 +47,7 @@ namespace SharpCifs.Netbios
}
/// <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;
if (@in.Read(buffer, bufferIndex, Length) != Length)

@ -37,8 +37,7 @@ namespace SharpCifs.Netbios
}
/// <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)
{

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

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

@ -24,10 +24,17 @@ namespace SharpCifs.Ntlmssp
{
/// <summary>The NTLMSSP "preamble".</summary>
/// <remarks>The NTLMSSP "preamble".</remarks>
protected internal static readonly byte[] NtlmsspSignature = { unchecked(
(byte)('N')), unchecked((byte)('T')), unchecked((byte)('L')),
unchecked((byte)('M')), unchecked((byte)('S')), unchecked((byte
)('S')), unchecked((byte)('P')), unchecked(0) };
protected internal static readonly byte[] NtlmsspSignature =
{
unchecked((byte)('N')),
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;
@ -75,14 +82,17 @@ namespace SharpCifs.Ntlmssp
/// </param>
public virtual void SetFlag(int flag, bool value)
{
SetFlags(value ? (GetFlags() | flag) : (GetFlags() & (unchecked((int)(0xffffffff)
) ^ flag)));
SetFlags(value
? (GetFlags() | flag)
: (GetFlags() & (unchecked((int)(0xffffffff)) ^ flag)));
}
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
+ 3] & unchecked(0xff)) << 24);
return (src[index] & unchecked(0xff))
| ((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)
@ -113,10 +123,14 @@ namespace SharpCifs.Ntlmssp
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)
{
int length = (src != null) ? src.Length : 0;
int length = (src != null)
? src.Length
: 0;
if (length == 0)
{
return;

@ -38,8 +38,9 @@ namespace SharpCifs.Ntlmssp
static Type1Message()
{
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode", true)
? NtlmsspNegotiateUnicode
: NtlmsspNegotiateOem);
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
string defaultWorkstation = null;
try
@ -60,8 +61,9 @@ namespace SharpCifs.Ntlmssp
/// Creates a Type-1 message using default values from the current
/// environment.
/// </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>
/// <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>
/// <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>
public Type1Message(byte[] material)
{
@ -136,8 +139,8 @@ namespace SharpCifs.Ntlmssp
{
hostInfo = true;
flags |= NtlmsspNegotiateOemDomainSupplied;
domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(), GetOemEncoding
());
domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(),
GetOemEncoding());
}
else
{
@ -148,16 +151,16 @@ namespace SharpCifs.Ntlmssp
{
hostInfo = true;
flags |= NtlmsspNegotiateOemWorkstationSupplied;
workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(), GetOemEncoding
());
workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(),
GetOemEncoding());
}
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);
WriteULong(type1, 8, 1);
WriteULong(type1, 12, flags);
@ -178,9 +181,9 @@ namespace SharpCifs.Ntlmssp
{
string suppliedDomain = GetSuppliedDomain();
string suppliedWorkstation = GetSuppliedWorkstation();
return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null"
) + ",suppliedWorkstation=" + (suppliedWorkstation ?? "null"
) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null")
+ ",suppliedWorkstation=" + (suppliedWorkstation ?? "null")
+ ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
}
/// <summary>
@ -238,8 +241,7 @@ namespace SharpCifs.Ntlmssp
if ((flags & NtlmsspNegotiateOemWorkstationSupplied) != 0)
{
byte[] workstation = ReadSecurityBuffer(material, 24);
suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding
());
suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding());
}
SetFlags(flags);
SetSuppliedDomain(suppliedDomain);

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

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

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

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

@ -18,8 +18,7 @@ namespace SharpCifs.Smb
{
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];
@ -48,8 +47,7 @@ namespace SharpCifs.Smb
}
}
internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse
rsp)
internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse rsp)
{
lock (Cache)
{

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

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

@ -18,47 +18,92 @@ namespace SharpCifs.Smb
{
public static class DosError
{
public static int[][] DosErrorCodes = { new[] { unchecked(0x00000000), unchecked(0x00000000) }, new[] { unchecked(0x00010001), unchecked((int)(0xc0000002)) }, new[] { unchecked(0x00010002), unchecked(
(int)(0xc0000002)) }, new[] { unchecked(0x00020001), unchecked((int)(
0xc000000f)) }, new[] { unchecked(0x00020002), unchecked((int)(0xc000006a
)) }, new[] { unchecked(0x00030001), unchecked((int)(0xc000003a)) },
new[] { unchecked(0x00030002), unchecked((int)(0xc00000cb)) }, new[] { unchecked(0x00040002), unchecked((int)(0xc00000ca)) }, new[] { unchecked(
0x00050001), unchecked((int)(0xc0000022)) }, new[] { unchecked(0x00050002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x00060001), unchecked((int)(0xc0000008)) }, new[] { unchecked(0x00060002), unchecked(
(int)(0xc00000cc)) }, new[] { unchecked(0x00080001), unchecked((int)(
0xc000009a)) }, new[] { unchecked(0x00130003), unchecked((int)(0xc00000a2
)) }, new[] { unchecked(0x00150003), unchecked((int)(0xc0000013)) },
new[] { unchecked(0x001f0001), unchecked((int)(0xc0000001)) }, new[] { unchecked(0x001f0003), unchecked((int)(0xc0000001)) }, new[] { unchecked(
0x00200001), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00200003), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00210003), unchecked((int)(0xc0000054)) }, 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 int[][] DosErrorCodes =
{
new[] { unchecked(0x00000000), unchecked(0x00000000) },
new[] { unchecked(0x00010001), unchecked((int)(0xc0000002)) },
new[] { unchecked(0x00010002), unchecked((int)(0xc0000002)) },
new[] { unchecked(0x00020001), unchecked((int)(0xc000000f)) },
new[] { unchecked(0x00020002), unchecked((int)(0xc000006a)) },
new[] { unchecked(0x00030001), unchecked((int)(0xc000003a)) },
new[] { unchecked(0x00030002), unchecked((int)(0xc00000cb)) },
new[] { unchecked(0x00040002), unchecked((int)(0xc00000ca)) },
new[] { unchecked(0x00050001), unchecked((int)(0xc0000022)) },
new[] { unchecked(0x00050002), unchecked((int)(0xc000000d)) },
new[] { unchecked(0x00060001), unchecked((int)(0xc0000008)) },
new[] { unchecked(0x00060002), unchecked((int)(0xc00000cc)) },
new[] { unchecked(0x00080001), unchecked((int)(0xc000009a)) },
new[] { unchecked(0x00130003), unchecked((int)(0xc00000a2)) },
new[] { unchecked(0x00150003), unchecked((int)(0xc0000013)) },
new[] { unchecked(0x001f0001), unchecked((int)(0xc0000001)) },
new[] { unchecked(0x001f0003), unchecked((int)(0xc0000001)) },
new[] { unchecked(0x00200001), unchecked((int)(0xc0000043)) },
new[] { unchecked(0x00200003), unchecked((int)(0xc0000043)) },
new[] { unchecked(0x00210003), unchecked((int)(0xc0000054)) },
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."
, "Incorrect function.", "Incorrect function.", "The system cannot find the file specified."
, "Bad password.", "The system cannot find the path specified.", "reserved", "The client does not have the necessary access rights to perform the requested function."
, "Access is denied.", "The TID specified was invalid.", "The handle is invalid."
, "The network name cannot be found.", "Not enough storage is available to process this command."
, "The media is write protected.", "The device is not ready.", "A device attached to the system is not functioning."
, "A device attached to the system is not functioning.", "The process cannot access the file because it is being used by another process."
, "The process cannot access the file because it is being used by another process."
, "The process cannot access the file because another process has locked a portion of the file."
, "The disk is full.", "A duplicate name exists on the network.", "The network name cannot be found."
, "ERRnomoreconn.", "The file exists.", "The parameter is incorrect.", "Too many Uids active on this session."
, "The 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."
public static string[] DosErrorMessages =
{
"The operation completed successfully.",
"Incorrect function.",
"Incorrect function.",
"The system cannot find the file specified.",
"Bad password.",
"The system cannot find the path specified.",
"reserved",
"The client does not have the necessary access rights to perform the requested function.",
"Access is denied.",
"The TID specified was invalid.",
"The handle is invalid.",
"The network name cannot be found.",
"Not enough storage is available to process this command.",
"The media is write protected.",
"The device is not ready.",
"A device attached to the system is not functioning.",
"A device attached to the system is not functioning.",
"The process cannot access the file because it is being used by another process.",
"The process cannot access the file because it is being used by another process.",
"The process cannot access the file because another process has locked a portion of the file.",
"The disk is full.",
"A duplicate name exists on the network.",
"The network name cannot be found.",
"ERRnomoreconn.",
"The file exists.",
"The parameter is incorrect.",
"Too many Uids active on this session.",
"The 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."
};
}
}

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

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

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

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

@ -36,8 +36,7 @@ namespace SharpCifs.Smb
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));
@ -131,8 +130,7 @@ namespace SharpCifs.Smb
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));
@ -142,61 +140,138 @@ namespace SharpCifs.Smb
public const int NtStatusPathNotCovered = unchecked((int)(0xC0000257));
public const int NtStatusIoReparseTagNotHandled = unchecked((int)(0xC0000279
));
public static int[] NtStatusCodes = { NtStatusOk, NtStatusUnsuccessful
, NtStatusNotImplemented, NtStatusInvalidInfoClass, NtStatusAccessViolation
, NtStatusInvalidHandle, NtStatusInvalidParameter, NtStatusNoSuchDevice
, NtStatusNoSuchFile, NtStatusMoreProcessingRequired, NtStatusAccessDenied
, NtStatusBufferTooSmall, NtStatusObjectNameInvalid, NtStatusObjectNameNotFound
, NtStatusObjectNameCollision, NtStatusPortDisconnected, NtStatusObjectPathInvalid
, NtStatusObjectPathNotFound, 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."
, "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 parameter is incorrect.", "The system cannot find the file specified.", "The system cannot find the file specified."
, "More data is available.", "Access is denied.", "The data area passed to a system call is too small."
, "The filename, directory name, or volume label syntax is incorrect.", "The system cannot find the file specified."
, "Cannot create a file when that file already exists.", "The handle is invalid."
, "The specified path is invalid.", "The system cannot find the path specified."
, "The specified path is invalid.", "The process cannot access the file because it is being used by another process."
, "Access is denied.", "There are currently no logon servers available to service the logon request."
, "The specified user already exists.", "The specified user does not exist.", "The specified network password is not correct."
, "Logon failure: unknown user name or bad password.", "Logon failure: user account restriction."
, "Logon failure: account logon time restriction violation.", "Logon failure: user not allowed to log on to this computer."
, "Logon failure: the specified account password has expired.", "Logon failure: account currently disabled."
, "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"
public const int NtStatusIoReparseTagNotHandled = unchecked((int)(0xC0000279));
public static int[] NtStatusCodes =
{
NtStatusOk,
NtStatusUnsuccessful,
NtStatusNotImplemented,
NtStatusInvalidInfoClass,
NtStatusAccessViolation,
NtStatusInvalidHandle,
NtStatusInvalidParameter,
NtStatusNoSuchDevice,
NtStatusNoSuchFile,
NtStatusMoreProcessingRequired,
NtStatusAccessDenied,
NtStatusBufferTooSmall,
NtStatusObjectNameInvalid,
NtStatusObjectNameNotFound,
NtStatusObjectNameCollision,
NtStatusPortDisconnected,
NtStatusObjectPathInvalid,
NtStatusObjectPathNotFound,
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.",
"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 parameter is incorrect.",
"The system cannot find the file specified.",
"The system cannot find the file specified.",
"More data is available.",
"Access is denied.",
"The data area passed to a system call is too small.",
"The filename, directory name, or volume label syntax is incorrect.",
"The system cannot find the file specified.",
"Cannot create a file when that file already exists.",
"The handle is invalid.",
"The specified path is invalid.",
"The system cannot find the path specified.",
"The specified path is invalid.",
"The process cannot access the file because it is being used by another process.",
"Access is denied.",
"There are currently no logon servers available to service the logon request.",
"The specified user already exists.",
"The specified user does not exist.",
"The specified network password is not correct.",
"Logon failure: unknown user name or bad password.",
"Logon failure: user account restriction.",
"Logon failure: account logon time restriction violation.",
"Logon failure: user not allowed to log on to this computer.",
"Logon failure: the specified account password has expired.",
"Logon failure: account currently disabled.",
"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"
};
}
}

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

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

@ -16,9 +16,11 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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>
/// <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>
public abstract class NtlmAuthenticator
{
@ -35,7 +37,8 @@ namespace SharpCifs.Smb
}
/// <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>
public static void SetDefault(NtlmAuthenticator a)
{
@ -59,12 +62,14 @@ namespace SharpCifs.Smb
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>
/// <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>
public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string
url, SmbAuthException sae)
public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string url,
SmbAuthException sae)
{
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.
/// 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>
protected internal virtual NtlmPasswordAuthentication GetNtlmPasswordAuthentication
()
protected internal virtual NtlmPasswordAuthentication GetNtlmPasswordAuthentication()
{
return null;
}

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

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

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

@ -67,8 +67,11 @@ namespace SharpCifs.Smb
public const int SidTypeUnknown = Lsarpc.SidNameUnknown;
internal static readonly string[] SidTypeNames = { "0", "User", "Domain group"
, "Domain", "Local group", "Builtin group", "Deleted", "Invalid", "Unknown" };
internal static readonly string[] SidTypeNames =
{
"0", "User", "Domain group", "Domain", "Local group",
"Builtin group", "Deleted", "Invalid", "Unknown"
};
public const int SidFlagResolveSids = unchecked(0x0001);
@ -94,8 +97,9 @@ namespace SharpCifs.Smb
internal static Hashtable SidCache = new Hashtable();
/// <exception cref="System.IO.IOException"></exception>
internal static void ResolveSids(DcerpcHandle handle, LsaPolicyHandle policyHandle
, Sid[] sids)
internal static void ResolveSids(DcerpcHandle handle,
LsaPolicyHandle policyHandle,
Sid[] sids)
{
MsrpcLookupSids rpc = new MsrpcLookupSids(policyHandle, sids);
handle.Sendrecv(rpc);
@ -132,16 +136,16 @@ namespace SharpCifs.Smb
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].OriginAuth = null;
}
}
/// <exception cref="System.IO.IOException"></exception>
internal static void ResolveSids0(string authorityServerName, NtlmPasswordAuthentication
auth, Sid[] sids)
internal static void ResolveSids0(string authorityServerName,
NtlmPasswordAuthentication auth,
Sid[] sids)
{
DcerpcHandle handle = null;
LsaPolicyHandle policyHandle = null;
@ -149,8 +153,8 @@ namespace SharpCifs.Smb
{
try
{
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\lsarpc]"
, auth);
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName
+ "[\\PIPE\\lsarpc]", auth);
string server = authorityServerName;
int dot = server.IndexOf('.');
if (dot > 0 && char.IsDigit(server[0]) == false)
@ -175,10 +179,13 @@ namespace SharpCifs.Smb
}
/// <exception cref="System.IO.IOException"></exception>
public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication
auth, Sid[] sids, int offset, int length)
public static void ResolveSids(string authorityServerName,
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;
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>
/// <remarks>
/// Resolve an array of SIDs using a cache and at most one MSRPC request.
/// <p>
///
/// This method will attempt
/// 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
/// expired because under normal circumstances SID information never changes.
/// </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 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 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>
/// <exception cref="System.IO.IOException"></exception>
public static void ResolveSids(string authorityServerName, NtlmPasswordAuthentication
auth, Sid[] sids)
public static void ResolveSids(string authorityServerName,
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;
lock (SidCache)
{
@ -249,7 +260,7 @@ namespace SharpCifs.Smb
if (list.Count > 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);
for (si = 0; si < sids.Length; si++)
{
@ -260,8 +271,8 @@ namespace SharpCifs.Smb
}
/// <exception cref="System.IO.IOException"></exception>
public static Sid GetServerSid(string server, NtlmPasswordAuthentication
auth)
public static Sid GetServerSid(string server,
NtlmPasswordAuthentication auth)
{
DcerpcHandle handle = null;
LsaPolicyHandle policyHandle = null;
@ -274,15 +285,19 @@ namespace SharpCifs.Smb
handle = DcerpcHandle.GetHandle("ncacn_np:" + server + "[\\PIPE\\lsarpc]", auth);
// NetApp doesn't like the 'generic' access mask values
policyHandle = new LsaPolicyHandle(handle, null, unchecked(0x00000001));
rpc = new MsrpcQueryInformationPolicy(policyHandle, Lsarpc.PolicyInfoAccountDomain
, info);
rpc = new MsrpcQueryInformationPolicy(policyHandle,
Lsarpc.PolicyInfoAccountDomain,
info);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
return new Sid(info.Sid, SidTypeDomain, (new UnicodeString
(info.Name, false)).ToString(), null, false);
return new Sid(info.Sid,
SidTypeDomain,
(new UnicodeString(info.Name, false)).ToString(),
null,
false);
}
finally
{
@ -413,8 +428,11 @@ namespace SharpCifs.Smb
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;
SubAuthorityCount = sid.SubAuthorityCount;
@ -436,8 +454,11 @@ namespace SharpCifs.Smb
public virtual Sid GetDomainSid()
{
return new Sid(this, SidTypeDomain, DomainName, null, GetType()
!= SidTypeDomain);
return new Sid(this,
SidTypeDomain,
DomainName,
null,
GetType() != SidTypeDomain);
}
public virtual int GetRid()
@ -512,8 +533,7 @@ namespace SharpCifs.Smb
if (Type == SidTypeUnknown)
{
string full = ToString();
return Runtime.Substring(full, 0, full.Length - GetAccountName().Length -
1);
return Runtime.Substring(full, 0, full.Length - GetAccountName().Length - 1);
}
return DomainName;
}
@ -597,8 +617,8 @@ namespace SharpCifs.Smb
public override string ToString()
{
string ret = "S-" + (Revision & unchecked(0xFF)) + "-";
if (IdentifierAuthority[0] != unchecked(0) || IdentifierAuthority[1] != unchecked(
0))
if (IdentifierAuthority[0] != unchecked(0)
|| IdentifierAuthority[1] != unchecked(0))
{
ret += "0x";
ret += Hexdump.ToHexString(IdentifierAuthority, 0, 6);
@ -689,8 +709,8 @@ namespace SharpCifs.Smb
/// </param>
/// <param name="auth">Credentials suitable for accessing the SID's information.</param>
/// <exception cref="System.IO.IOException"></exception>
public virtual void Resolve(string authorityServerName, NtlmPasswordAuthentication
auth)
public virtual void Resolve(string authorityServerName,
NtlmPasswordAuthentication auth)
{
Sid[] sids = new Sid[1];
sids[0] = this;
@ -717,8 +737,11 @@ namespace SharpCifs.Smb
}
/// <exception cref="System.IO.IOException"></exception>
internal static Sid[] GetGroupMemberSids0(DcerpcHandle handle, SamrDomainHandle
domainHandle, Sid domsid, int rid, int flags)
internal static Sid[] GetGroupMemberSids0(DcerpcHandle handle,
SamrDomainHandle domainHandle,
Sid domsid,
int rid,
int flags)
{
SamrAliasHandle aliasHandle = null;
Lsarpc.LsarSidArray sidarray = new Lsarpc.LsarSidArray();
@ -734,8 +757,8 @@ namespace SharpCifs.Smb
}
Sid[] sids = new Sid[rpc.Sids.NumSids];
string originServer = handle.GetServer();
NtlmPasswordAuthentication originAuth = (NtlmPasswordAuthentication)handle.GetPrincipal
();
NtlmPasswordAuthentication originAuth
= (NtlmPasswordAuthentication)handle.GetPrincipal();
for (int i = 0; i < sids.Length; i++)
{
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>
public virtual Sid[] GetGroupMemberSids(string authorityServerName, NtlmPasswordAuthentication
auth, int flags)
public virtual Sid[] GetGroupMemberSids(string authorityServerName,
NtlmPasswordAuthentication auth,
int flags)
{
if (Type != SidTypeDomGrp && Type != SidTypeAlias)
{
@ -773,11 +797,19 @@ namespace SharpCifs.Smb
{
try
{
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]"
, auth);
policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x00000030));
domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x00000200), domsid);
return GetGroupMemberSids0(handle, domainHandle, domsid, GetRid(),
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName
+ "[\\PIPE\\samr]", auth);
policyHandle = new SamrPolicyHandle(handle,
authorityServerName,
unchecked(0x00000030));
domainHandle = new SamrDomainHandle(handle,
policyHandle,
unchecked(0x00000200),
domsid);
return GetGroupMemberSids0(handle,
domainHandle,
domsid,
GetRid(),
flags);
}
finally
@ -842,12 +874,18 @@ namespace SharpCifs.Smb
{
try
{
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName + "[\\PIPE\\samr]"
, auth);
policyHandle = new SamrPolicyHandle(handle, authorityServerName, unchecked(0x02000000));
domainHandle = new SamrDomainHandle(handle, policyHandle, unchecked(0x02000000), domsid);
rpc = new MsrpcEnumerateAliasesInDomain(domainHandle, unchecked(0xFFFF), sam
);
handle = DcerpcHandle.GetHandle("ncacn_np:" + authorityServerName
+ "[\\PIPE\\samr]", auth);
policyHandle = new SamrPolicyHandle(handle,
authorityServerName,
unchecked(0x02000000));
domainHandle = new SamrDomainHandle(handle,
policyHandle,
unchecked(0x02000000),
domsid);
rpc = new MsrpcEnumerateAliasesInDomain(domainHandle,
unchecked(0xFFFF),
sam);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
@ -857,8 +895,11 @@ namespace SharpCifs.Smb
for (int ei = 0; ei < rpc.Sam.Count; ei++)
{
Samr.SamrSamEntry entry = rpc.Sam.Entries[ei];
Sid[] mems = GetGroupMemberSids0(handle, domainHandle, domsid
, entry.Idx, flags);
Sid[] mems = GetGroupMemberSids0(handle,
domainHandle,
domsid,
entry.Idx,
flags);
Sid groupSid = new Sid(domsid, entry.Idx);
groupSid.Type = SidTypeAlias;
groupSid.DomainName = domsid.GetDomainName();

@ -21,15 +21,20 @@ using SharpCifs.Util.Transport;
namespace SharpCifs.Smb
{
public abstract class ServerMessageBlock: Response
public abstract class ServerMessageBlock : Response
{
internal static LogStream Log = LogStream.GetInstance();
internal static long Ticks1601 = new DateTime(1601, 1, 1).Ticks;
internal static readonly byte[] Header = { 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 readonly byte[] Header =
{
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)
{
@ -47,19 +52,22 @@ namespace SharpCifs.Smb
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)
{
return unchecked(src[srcIndex] & 0xFF) + ((src[srcIndex + 1] & 0xFF) << 8) + ((src[srcIndex + 2]
& 0xFF) << 16) + ((src[srcIndex + 3] & 0xFF) << 24);
return unchecked(src[srcIndex] & 0xFF)
+ ((src[srcIndex + 1] & 0xFF) << 8)
+ ((src[srcIndex + 2] & 0xFF) << 16)
+ ((src[srcIndex + 3] & 0xFF) << 24);
}
internal static long ReadInt8(byte[] src, int srcIndex)
{
return unchecked(ReadInt4(src, srcIndex) & unchecked(0xFFFFFFFFL)) + unchecked((long)(ReadInt4
(src, srcIndex + 4)) << 32);
return unchecked(ReadInt4(src, srcIndex) & unchecked(0xFFFFFFFFL))
+ unchecked((long)(ReadInt4(src, srcIndex + 4)) << 32);
}
internal static void WriteInt8(long val, byte[] dst, int dstIndex)
@ -206,16 +214,20 @@ namespace SharpCifs.Smb
public ServerMessageBlock()
{
Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized
));
Flags = unchecked(
(byte)(SmbConstants.FlagsPathNamesCaseless
| SmbConstants.FlagsPathNamesCanonicalized)
);
Pid = SmbConstants.Pid;
BatchLevel = 0;
}
internal virtual void Reset()
{
Flags = unchecked((byte)(SmbConstants.FlagsPathNamesCaseless | SmbConstants.FlagsPathNamesCanonicalized
));
Flags = unchecked(
(byte)(SmbConstants.FlagsPathNamesCaseless
| SmbConstants.FlagsPathNamesCanonicalized)
);
Flags2 = 0;
ErrorCode = 0;
Received = false;
@ -227,8 +239,7 @@ namespace SharpCifs.Smb
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;
try
@ -240,8 +251,8 @@ namespace SharpCifs.Smb
{
dst[dstIndex++] = (byte)('\0');
}
Array.Copy(Runtime.GetBytesForString(str, SmbConstants.UniEncoding), 0, dst, dstIndex
, str.Length * 2);
Array.Copy(Runtime.GetBytesForString(str, SmbConstants.UniEncoding),
0, dst, dstIndex, str.Length * 2);
dstIndex += str.Length * 2;
dst[dstIndex++] = (byte)('\0');
dst[dstIndex++] = (byte)('\0');
@ -269,8 +280,7 @@ namespace SharpCifs.Smb
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;
string str = null;
@ -291,8 +301,12 @@ namespace SharpCifs.Smb
{
if (Log.Level > 0)
{
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
128);
Hexdump.ToHexdump(Console.Error,
src,
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
}
throw new RuntimeException("zero termination not found");
}
@ -308,8 +322,12 @@ namespace SharpCifs.Smb
{
if (Log.Level > 0)
{
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
128);
Hexdump.ToHexdump(Console.Error,
src,
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
}
throw new RuntimeException("zero termination not found");
}
@ -327,8 +345,11 @@ namespace SharpCifs.Smb
return str;
}
internal virtual string ReadString(byte[] src, int srcIndex, int srcEnd, int maxLen
, bool useUnicode)
internal virtual string ReadString(byte[] src,
int srcIndex,
int srcEnd,
int maxLen,
bool useUnicode)
{
int len = 0;
string str = null;
@ -343,8 +364,7 @@ namespace SharpCifs.Smb
}
for (len = 0; (srcIndex + len + 1) < srcEnd; len += 2)
{
if (src[srcIndex + len] == 0x00 && src[srcIndex
+ len + 1] == 0x00)
if (src[srcIndex + len] == 0x00 && src[srcIndex + len + 1] == 0x00)
{
break;
}
@ -352,8 +372,12 @@ namespace SharpCifs.Smb
{
if (Log.Level > 0)
{
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
128);
Hexdump.ToHexdump(Console.Error,
src,
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
}
throw new RuntimeException("zero termination not found");
}
@ -372,8 +396,12 @@ namespace SharpCifs.Smb
{
if (Log.Level > 0)
{
Hexdump.ToHexdump(Console.Error, src, srcIndex, maxLen < 128 ? maxLen + 8 :
128);
Hexdump.ToHexdump(Console.Error,
src,
srcIndex,
maxLen < 128
? maxLen + 8
: 128);
}
throw new RuntimeException("zero termination not found");
}
@ -447,8 +475,8 @@ namespace SharpCifs.Smb
{
if (Log.Level >= 5)
{
Log.WriteLine("wordCount * 2=" + (WordCount * 2) + " but readParameterWordsWireFormat returned "
+ n);
Log.WriteLine("wordCount * 2=" + (WordCount * 2)
+ " but readParameterWordsWireFormat returned " + n);
}
}
bufferIndex += WordCount * 2;
@ -462,8 +490,8 @@ namespace SharpCifs.Smb
{
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.
@ -510,8 +538,7 @@ namespace SharpCifs.Smb
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);
@ -522,8 +549,7 @@ namespace SharpCifs.Smb
public override bool Equals(object obj)
{
return obj is ServerMessageBlock && ((ServerMessageBlock)obj)
.Mid == Mid;
return obj is ServerMessageBlock && ((ServerMessageBlock)obj).Mid == Mid;
}
public override string ToString()
@ -681,12 +707,21 @@ namespace SharpCifs.Smb
break;
}
}
string str = ErrorCode == 0 ? "0" : SmbException.GetMessageByCode(ErrorCode);
return "command=" + c + ",received=" + Received + ",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;
string str = ErrorCode == 0
? "0"
: SmbException.GetMessageByCode(ErrorCode);
return "command=" + c
+ ",received=" + Received
+ ",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;
}
}
}

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

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

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

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

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

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

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

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

@ -65,8 +65,7 @@ namespace SharpCifs.Smb
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
OplockLevel = buffer[bufferIndex++];
@ -103,13 +102,20 @@ namespace SharpCifs.Smb
public override string ToString()
{
return "SmbComNTCreateAndXResponse[" + base.ToString() + ",oplockLevel="
+ OplockLevel + ",fid=" + Fid + ",createAction=0x" + Hexdump.ToHexString(CreateAction
, 4) + ",creationTime=" + Extensions.CreateDate(CreationTime) + ",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
return "SmbComNTCreateAndXResponse["
+ base.ToString()
+ ",oplockLevel=" + OplockLevel
+ ",fid=" + Fid
+ ",createAction=0x" + Hexdump.ToHexString(CreateAction, 4)
+ ",creationTime=" + Extensions.CreateDate(CreationTime)
+ ",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 + "]";
}
}

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

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

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

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

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

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

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

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

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

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

@ -22,11 +22,11 @@ namespace SharpCifs.Smb
{
internal class SmbComSessionSetupAndX : AndXServerMessageBlock
{
private static readonly int BatchLimit = Config.GetInt("jcifs.smb.client.SessionSetupAndX.TreeConnectAndX"
, 1);
private static readonly int BatchLimit
= Config.GetInt("jcifs.smb.client.SessionSetupAndX.TreeConnectAndX", 1);
private static readonly bool DisablePlainTextPasswords = Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords"
, true);
private static readonly bool DisablePlainTextPasswords
= Config.GetBoolean("jcifs.smb.client.disablePlainTextPasswords", true);
private byte[] _lmHash;
@ -47,8 +47,9 @@ namespace SharpCifs.Smb
internal object Cred;
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal SmbComSessionSetupAndX(SmbSession session, ServerMessageBlock andx, object
cred) : base(andx)
internal SmbComSessionSetupAndX(SmbSession session,
ServerMessageBlock andx,
object cred) : base(andx)
{
Command = SmbComSessionSetupAndx;
this.Session = session;
@ -208,8 +209,7 @@ namespace SharpCifs.Smb
return dstIndex - start;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
@ -221,12 +221,22 @@ namespace SharpCifs.Smb
public override string ToString()
{
string result = "SmbComSessionSetupAndX[" + base.ToString() + ",snd_buf_size="
+ Session.transport.SndBufSize + ",maxMpxCount=" + Session.transport.MaxMpxCount
+ ",VC_NUMBER=" + SmbConstants.VcNumber + ",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
string result = "SmbComSessionSetupAndX["
+ base.ToString()
+ ",snd_buf_size=" + Session.transport.SndBufSize
+ ",maxMpxCount=" + Session.transport.MaxMpxCount
+ ",VC_NUMBER=" + SmbConstants.VcNumber
+ ",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 + "]";
return result;
}

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

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

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

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

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

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

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

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

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

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

@ -23,6 +23,61 @@ namespace SharpCifs.Smb
{
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 DefaultMaxMpxCount = 10;
@ -39,41 +94,44 @@ namespace SharpCifs.Smb
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",
true);
public static bool UseUnicode { get; internal set; }
= Config.GetBoolean("jcifs.smb.client.useUnicode", true);
public static readonly bool ForceUnicode = Config.GetBoolean("jcifs.smb.client.useUnicode"
, false);
public static bool ForceUnicode { get; internal set; }
= Config.GetBoolean("jcifs.smb.client.useUnicode", false);
public static readonly bool UseNtstatus = Config.GetBoolean("jcifs.smb.client.useNtStatus"
, true);
public static bool UseNtstatus { get; internal set; }
= Config.GetBoolean("jcifs.smb.client.useNtStatus", true);
public static readonly bool Signpref = Config.GetBoolean("jcifs.smb.client.signingPreferred"
, false);
public static bool Signpref { get; internal set; }
= 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"
, true);
public static bool UseExtsec { get; internal set; }
= Config.GetBoolean("jcifs.smb.client.useExtendedSecurity", true);
public static readonly string NetbiosHostname = Config.GetProperty("jcifs.netbios.hostname"
, null);
public static string NetbiosHostname { get; internal set; }
= 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);
@ -227,50 +285,70 @@ namespace SharpCifs.Smb
public static readonly TimeZoneInfo Tz = TimeZoneInfo.Local;
public static readonly bool UseBatching = Config.GetBoolean("jcifs.smb.client.useBatching"
, true);
public static readonly string OemEncoding = Config.GetProperty("jcifs.encoding", Config.DefaultOemEncoding
);
public static readonly string UniEncoding = "UTF-16LE";
public static readonly int DefaultFlags2 = Flags2LongFilenames | Flags2ExtendedAttributes
| (UseExtsec ? Flags2ExtendedSecurityNegotiation : 0) | (Signpref ? Flags2SecuritySignatures
: 0) | (UseNtstatus ? Flags2Status32 : 0) | (UseUnicode ? Flags2Unicode : 0
);
public static readonly int DefaultCapabilities = (UseNtsmbs ? CapNtSmbs : 0) | (UseNtstatus
? CapStatus32 : 0) | (UseUnicode ? CapUnicode : 0) | CapDfs;
public static readonly int Flags2 = Config.GetInt("jcifs.smb.client.flags2", DefaultFlags2
);
public static readonly int Capabilities = Config.GetInt("jcifs.smb.client.capabilities", DefaultCapabilities
);
public static readonly bool TcpNodelay = Config.GetBoolean("jcifs.smb.client.tcpNoDelay",
false);
public static readonly int ResponseTimeout = Config.GetInt("jcifs.smb.client.responseTimeout"
, DefaultResponseTimeout);
public static bool UseBatching { get; internal set; }
= Config.GetBoolean("jcifs.smb.client.useBatching", true);
public static string OemEncoding { get; internal set; }
= Config.GetProperty("jcifs.encoding", Config.DefaultOemEncoding);
public static string UniEncoding = "UTF-16LE";
public static int DefaultFlags2 { get; internal set; }
= Flags2LongFilenames
| Flags2ExtendedAttributes
| (UseExtsec
? Flags2ExtendedSecurityNegotiation
: 0)
| (Signpref
? Flags2SecuritySignatures
: 0)
| (UseNtstatus
? Flags2Status32
: 0)
| (UseUnicode
? Flags2Unicode
: 0);
public static int DefaultCapabilities { get; internal set; }
= (UseNtsmbs
? CapNtSmbs
: 0)
| (UseNtstatus
? CapStatus32
: 0)
| (UseUnicode
? CapUnicode
: 0)
| CapDfs;
public static int Flags2 { get; internal set; }
= Config.GetInt("jcifs.smb.client.flags2", DefaultFlags2);
public static int Capabilities { get; internal set; }
= Config.GetInt("jcifs.smb.client.capabilities", DefaultCapabilities);
public static bool TcpNodelay { get; internal set; }
= Config.GetBoolean("jcifs.smb.client.tcpNoDelay", false);
public static int ResponseTimeout { get; internal set; }
= Config.GetInt("jcifs.smb.client.responseTimeout", DefaultResponseTimeout);
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
.GetProperty("os.name"));
public static string NativeOs { get; internal set; }
= Config.GetProperty("jcifs.smb.client.nativeOs", Runtime.GetProperty("os.name"));
public static readonly string NativeLanman = Config.GetProperty("jcifs.smb.client.nativeLanMan"
, "jCIFS");
public static string NativeLanman { get; internal set; }
= Config.GetProperty("jcifs.smb.client.nativeLanMan", "jCIFS");
public static readonly int VcNumber = 1;

@ -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);
this._rootCause = rootCause;
@ -181,10 +181,14 @@ namespace SharpCifs.Smb
_status = NtStatus.NtStatusUnsuccessful;
}
public SmbException(int errcode, bool winerr) : base(winerr ? GetMessageByWinerrCode
(errcode) : GetMessageByCode(errcode))
{
_status = winerr ? errcode : GetStatusByCode(errcode);
public SmbException(int errcode, bool winerr)
: base(winerr
? GetMessageByWinerrCode(errcode)
: GetMessageByCode(errcode))
{
_status = winerr
? errcode
: GetStatusByCode(errcode);
}
public virtual int GetNtStatus()

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

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

@ -100,8 +100,7 @@ namespace SharpCifs.Smb
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
/// <exception cref="System.UriFormatException"></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="System.UriFormatException"></exception>
/// <exception cref="UnknownHostException"></exception>
public SmbFileOutputStream(SmbFile file, bool append) : this(file, append, append
? SmbFile.OCreat | SmbFile.OWronly | SmbFile.OAppend : SmbFile.OCreat | SmbFile
.OWronly | SmbFile.OTrunc)
public SmbFileOutputStream(SmbFile file, bool append)
: this(file,
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="System.UriFormatException"></exception>
/// <exception cref="UnknownHostException"></exception>
public SmbFileOutputStream(string url, int shareAccess) : this(new SmbFile(url, string.Empty
, null, shareAccess), false)
public SmbFileOutputStream(string url, int shareAccess)
: this(new SmbFile(url, string.Empty, null, shareAccess), false)
{
}
@ -182,15 +184,16 @@ namespace SharpCifs.Smb
if (file is SmbNamedPipe && file.Unc.StartsWith("\\pipe\\"))
{
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);
this._openFlags &= ~(SmbFile.OCreat | SmbFile.OTrunc);
_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)
{
_reqx = new SmbComWriteAndX();
@ -252,7 +255,9 @@ namespace SharpCifs.Smb
// ensure file is open
if (_file.IsOpen() == false)
{
_file.Open(_openFlags, _access | SmbConstants.FileWriteData, SmbFile.AttrNormal,
_file.Open(_openFlags,
_access | SmbConstants.FileWriteData,
SmbFile.AttrNormal,
0);
if (_append)
{
@ -275,8 +280,8 @@ namespace SharpCifs.Smb
{
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);
}
@ -295,10 +300,12 @@ namespace SharpCifs.Smb
throw new IOException("Bad file descriptor");
}
EnsureOpen();
/*if (file.log.level >= 4)
/*
if (file.log.level >= 4)
{
file.log.WriteLine("write: fid=" + file.fid + ",off=" + off + ",len=" + len);
}*/
}
*/
int w;
do
{

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

@ -49,8 +49,8 @@ namespace SharpCifs.Smb
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
/// <exception cref="System.UriFormatException"></exception>
/// <exception cref="UnknownHostException"></exception>
public SmbRandomAccessFile(string url, string mode, int shareAccess) : this(new SmbFile
(url, string.Empty, null, shareAccess), mode)
public SmbRandomAccessFile(string url, string mode, int shareAccess)
: this(new SmbFile(url, string.Empty, null, shareAccess), mode)
{
}
@ -196,8 +196,8 @@ namespace SharpCifs.Smb
do
{
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;
len -= (int)_writeAndxResp.Count;
off += (int)_writeAndxResp.Count;
@ -232,7 +232,13 @@ namespace SharpCifs.Smb
_file.Open(_openFlags, 0, SmbFile.AttrNormal, _options);
}
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>
@ -462,8 +468,10 @@ namespace SharpCifs.Smb
Write(b, 0, b.Length);
}
/*
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
/* public void WriteChars(string s)
public void WriteChars(string s)
{
int clen = s.Length;
int blen = 2 * clen;
@ -476,7 +484,8 @@ namespace SharpCifs.Smb
b[j++] = unchecked((byte)((char)(((uchar)c[i]) >> 0)));
}
Write(b, 0, blen);
}*/
}
*/
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public void WriteUtf(string str)
@ -488,7 +497,11 @@ namespace SharpCifs.Smb
for (int i = 0; i < len; 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];
WriteShort(size);

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

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

@ -31,25 +31,30 @@ namespace SharpCifs.Smb
{
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 Hashtable DfsRoots = null;
internal static SmbTransport GetSmbTransport(UniAddress address, int port
)
internal static SmbTransport GetSmbTransport(UniAddress address, int port)
{
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
, IPAddress localAddr, int localPort, string hostName)
internal static SmbTransport GetSmbTransport(UniAddress address,
int port,
IPAddress localAddr,
int localPort,
string hostName)
{
lock (typeof(SmbTransport))
{
@ -59,18 +64,19 @@ namespace SharpCifs.Smb
{
if (SmbConstants.SsnLimit != 1)
{
conn =
SmbConstants.Connections.FirstOrDefault(
c =>
c.Matches(address, port, localAddr, localPort, hostName) &&
(SmbConstants.SsnLimit ==
0 || c.Sessions.Count < SmbConstants.SsnLimit));
conn = SmbConstants.Connections
.FirstOrDefault(c => c.Matches(address,
port,
localAddr,
localPort,
hostName)
&& (SmbConstants.SsnLimit == 0
|| c.Sessions.Count < SmbConstants.SsnLimit));
if (conn != null)
{
return conn;
}
}
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 byte Flags;
@ -174,8 +200,10 @@ namespace SharpCifs.Smb
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);
this.Address = address;
@ -206,7 +234,8 @@ namespace SharpCifs.Smb
return ssn;
}
if (SmbConstants.SoTimeout > 0 && SessionExpiration < (now = Runtime.CurrentTimeMillis()))
if (SmbConstants.SoTimeout > 0
&& SessionExpiration < (now = Runtime.CurrentTimeMillis()))
{
SessionExpiration = now + SmbConstants.SoTimeout;
@ -222,16 +251,25 @@ namespace SharpCifs.Smb
}
}
internal virtual bool Matches(UniAddress address, int port, IPAddress localAddr,
int localPort, string hostName)
internal virtual bool Matches(UniAddress address,
int port,
IPAddress localAddr,
int localPort,
string hostName)
{
if (hostName == null)
{
hostName = address.GetHostName();
}
return (TconHostName == null || Runtime.EqualsIgnoreCase(hostName, TconHostName)) && 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;
return (TconHostName == null
|| Runtime.EqualsIgnoreCase(hostName, TconHostName))
&& 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>
@ -250,31 +288,36 @@ namespace SharpCifs.Smb
internal virtual bool IsSignatureSetupRequired(NtlmPasswordAuthentication auth)
{
return (Flags2 & SmbConstants.Flags2SecuritySignatures) != 0 && Digest ==
null && auth != NtlmPasswordAuthentication.Null && NtlmPasswordAuthentication.Null
.Equals(auth) == false;
return (Flags2 & SmbConstants.Flags2SecuritySignatures) != 0
&& Digest == null
&& auth != NtlmPasswordAuthentication.Null
&& NtlmPasswordAuthentication.Null.Equals(auth) == false;
}
/// <exception cref="System.IO.IOException"></exception>
internal virtual void Ssn139()
{
Name calledName = new Name(Address.FirstCalledName(), 0x20, null
);
Name calledName = new Name(Address.FirstCalledName(), 0x20, null);
do
{
Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (LocalAddr != null)
{
Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort));
}
Socket = new SocketEx(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
//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;
Out = Socket.GetOutputStream();
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));
if (Readn(In, Sbuf, 0, 4) < 4)
{
@ -317,7 +360,8 @@ namespace SharpCifs.Smb
default:
{
Disconnect(true);
throw new NbtException(NbtException.ErrSsnSrvc, errorCode);
throw new NbtException(NbtException.ErrSsnSrvc,
errorCode);
}
}
break;
@ -326,8 +370,8 @@ namespace SharpCifs.Smb
case -1:
{
Disconnect(true);
throw new NbtException(NbtException.ErrSsnSrvc, NbtException.ConnectionRefused
);
throw new NbtException(NbtException.ErrSsnSrvc,
NbtException.ConnectionRefused);
}
default:
@ -357,13 +401,18 @@ namespace SharpCifs.Smb
port = SmbConstants.DefaultPort;
}
// 445
Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (LocalAddr != null)
{
Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort));
}
Socket = new SocketEx(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
//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;
Out = Socket.GetOutputStream();
In = Socket.GetInputStream();
@ -430,21 +479,28 @@ namespace SharpCifs.Smb
}
catch (ConnectException)
{
Port = (Port == -1 || Port == SmbConstants.DefaultPort) ? 139 : SmbConstants.DefaultPort;
Port = (Port == -1 || Port == SmbConstants.DefaultPort)
? 139
: SmbConstants.DefaultPort;
Negotiate(Port, resp);
}
if (resp.DialectIndex > 10)
{
throw new SmbException("This client does not support the negotiated dialect.");
}
if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) != SmbConstants.CapExtendedSecurity && Server
.EncryptionKeyLength != 8 && SmbConstants.LmCompatibility == 0)
if (
(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();
if (Server.SignaturesRequired || (Server.SignaturesEnabled && SmbConstants.Signpref))
if (Server.SignaturesRequired
|| (Server.SignaturesEnabled && SmbConstants.Signpref))
{
Flags2 |= SmbConstants.Flags2SecuritySignatures;
}
@ -459,7 +515,8 @@ namespace SharpCifs.Smb
}
SndBufSize = Math.Min(SndBufSize, Server.MaxBufferSize);
Capabilities &= Server.Capabilities;
if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == SmbConstants.CapExtendedSecurity)
if ((Server.Capabilities & SmbConstants.CapExtendedSecurity)
== SmbConstants.CapExtendedSecurity)
{
Capabilities |= SmbConstants.CapExtendedSecurity;
}
@ -494,6 +551,7 @@ namespace SharpCifs.Smb
//Socket.`Close` method deleted
//Socket.Close();
Socket.Shutdown(SocketShutdown.Both);
Socket.Dispose();
}
finally
@ -536,7 +594,7 @@ namespace SharpCifs.Smb
Log.WriteLine("New data read: " + this);
Hexdump.ToHexdump(Log, Sbuf, 4, 32);
}
for (; ; )
for (;;)
{
if (Sbuf[0] == 0x00 && Sbuf[1] == 0x00 &&
Sbuf[4] == 0xFF &&
@ -575,8 +633,8 @@ namespace SharpCifs.Smb
{
Log.WriteLine(smb);
}
while (smb is AndXServerMessageBlock && (smb = ((AndXServerMessageBlock)smb).Andx
) != null);
while (smb is AndXServerMessageBlock
&& (smb = ((AndXServerMessageBlock)smb).Andx) != null);
if (Log.Level >= 6)
{
Hexdump.ToHexdump(Log, Buf, 4, n);
@ -616,7 +674,9 @@ namespace SharpCifs.Smb
{
ServerMessageBlock resp = (ServerMessageBlock)response;
resp.UseUnicode = UseUnicode;
resp.ExtendedSecurity = (Capabilities & SmbConstants.CapExtendedSecurity) == SmbConstants.CapExtendedSecurity;
resp.ExtendedSecurity
= (Capabilities & SmbConstants.CapExtendedSecurity)
== SmbConstants.CapExtendedSecurity;
lock (Buf)
{
Array.Copy(Sbuf, 0, Buf, 0, 4 + SmbConstants.HeaderLength);
@ -626,8 +686,10 @@ namespace SharpCifs.Smb
throw new IOException("Invalid payload size: " + size);
}
int errorCode = Encdec.Dec_uint32le(Buf, 9) & unchecked((int)(0xFFFFFFFF));
if (resp.Command == ServerMessageBlock.SmbComReadAndx && (errorCode == 0 || errorCode
== unchecked((int)(0x80000005))))
if (resp.Command == ServerMessageBlock.SmbComReadAndx
&& (errorCode == 0
|| errorCode == unchecked((int)(0x80000005)))
)
{
// overflow indicator normal for pipe
SmbComReadAndXResponse r = (SmbComReadAndXResponse)resp;
@ -684,8 +746,7 @@ namespace SharpCifs.Smb
}
/// <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);
switch (resp.ErrorCode)
@ -746,8 +807,7 @@ namespace SharpCifs.Smb
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response
)
internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response)
{
Connect();
request.Flags2 |= Flags2;
@ -809,7 +869,8 @@ namespace SharpCifs.Smb
timeout = resp.Expiration - Runtime.CurrentTimeMillis();
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)
@ -891,8 +952,9 @@ namespace SharpCifs.Smb
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual DfsReferral GetDfsReferrals(NtlmPasswordAuthentication auth, string
path, int rn)
internal virtual DfsReferral GetDfsReferrals(NtlmPasswordAuthentication auth,
string path,
int rn)
{
SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null);
Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();
@ -909,7 +971,7 @@ namespace SharpCifs.Smb
string[] arr = new string[4];
long expiration = Runtime.CurrentTimeMillis() + Dfs.Ttl * 1000;
int di = 0;
for (; ; )
for (;;)
{
dr.ResolveHashes = auth.HashesExternal;
dr.Ttl = resp.Referrals[di].Ttl;
@ -939,7 +1001,8 @@ namespace SharpCifs.Smb
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
internal virtual DfsReferral[] __getDfsReferrals(NtlmPasswordAuthentication auth,
string path, int rn)
string path,
int rn)
{
SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null);
Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();

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

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

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

@ -81,14 +81,14 @@ namespace SharpCifs.Smb
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
internal override int ReadParametersWireFormat(byte[] buffer,
int bufferIndex,
int len)
{
return 0;
}
@ -100,10 +100,14 @@ namespace SharpCifs.Smb
public override string ToString()
{
return "Trans2FindNext2[" + base.ToString() + ",sid=" + _sid + ",searchCount="
+ Smb.Trans2FindFirst2.ListSize + ",informationLevel=0x" + Hexdump.ToHexString(_informationLevel
, 3) + ",resumeKey=0x" + Hexdump.ToHexString(_resumeKey, 4) + ",flags=0x" + Hexdump
.ToHexString(_flags, 2) + ",filename=" + _filename + "]";
return "Trans2FindNext2["
+ base.ToString()
+ ",sid=" + _sid
+ ",searchCount=" + Smb.Trans2FindFirst2.ListSize
+ ",informationLevel=0x" + Hexdump.ToHexString(_informationLevel, 3)
+ ",resumeKey=0x" + Hexdump.ToHexString(_resumeKey, 4)
+ ",flags=0x" + Hexdump.ToHexString(_flags, 2)
+ ",filename=" + _filename + "]";
}
}
}

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

Loading…
Cancel
Save