update sharpcifs

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

View File

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

View File

@ -19,87 +19,84 @@ using SharpCifs.Util;
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"
};
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 string GetResultMessage(int result)
{
return result < 4 ? ResultMessage[result] : "0x" + Hexdump.ToHexString(result, 4);
}
internal static string GetResultMessage(int result)
{
return result < 4 ? ResultMessage[result] : "0x" + Hexdump.ToHexString(result, 4
);
}
public override DcerpcException GetResult()
{
if (Result != 0)
{
return new DcerpcException(GetResultMessage(Result));
}
return null;
}
public override DcerpcException GetResult()
{
if (Result != 0)
{
return new DcerpcException(GetResultMessage(Result));
}
return null;
}
internal DcerpcBinding Binding;
internal DcerpcBinding Binding;
internal int MaxXmit;
internal int MaxXmit;
internal int MaxRecv;
internal int MaxRecv;
public DcerpcBind()
{
}
public DcerpcBind()
{
}
internal DcerpcBind(DcerpcBinding binding, DcerpcHandle handle)
{
this.Binding = binding;
MaxXmit = handle.MaxXmit;
MaxRecv = handle.MaxRecv;
Ptype = 11;
internal DcerpcBind(DcerpcBinding binding, DcerpcHandle handle)
{
this.Binding = binding;
MaxXmit = handle.MaxXmit;
MaxRecv = handle.MaxRecv;
Ptype = 11;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
public override int GetOpnum()
{
return 0;
}
public override int GetOpnum()
{
return 0;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
dst.Enc_ndr_short(MaxXmit);
dst.Enc_ndr_short(MaxRecv);
dst.Enc_ndr_long(0);
dst.Enc_ndr_small(1);
dst.Enc_ndr_small(0);
dst.Enc_ndr_short(0);
dst.Enc_ndr_short(0);
dst.Enc_ndr_small(1);
dst.Enc_ndr_small(0);
Binding.Uuid.Encode(dst);
dst.Enc_ndr_short(Binding.Major);
dst.Enc_ndr_short(Binding.Minor);
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode_in(NdrBuffer dst)
{
dst.Enc_ndr_short(MaxXmit);
dst.Enc_ndr_short(MaxRecv);
dst.Enc_ndr_long(0);
dst.Enc_ndr_small(1);
dst.Enc_ndr_small(0);
dst.Enc_ndr_short(0);
dst.Enc_ndr_short(0);
dst.Enc_ndr_small(1);
dst.Enc_ndr_small(0);
Binding.Uuid.Encode(dst);
dst.Enc_ndr_short(Binding.Major);
dst.Enc_ndr_short(Binding.Minor);
DcerpcConstants.DcerpcUuidSyntaxNdr.Encode(dst);
dst.Enc_ndr_long(2);
}
dst.Enc_ndr_long(2);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
src.Dec_ndr_short();
src.Dec_ndr_short();
src.Dec_ndr_long();
int n = src.Dec_ndr_short();
src.Advance(n);
src.Align(4);
src.Dec_ndr_small();
src.Align(4);
Result = src.Dec_ndr_short();
src.Dec_ndr_short();
src.Advance(20);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode_out(NdrBuffer src)
{
src.Dec_ndr_short();
src.Dec_ndr_short();
src.Dec_ndr_long();
int n = src.Dec_ndr_short();
src.Advance(n);
src.Align(4);
src.Dec_ndr_small();
src.Align(4);
Result = src.Dec_ndr_short();
src.Dec_ndr_short();
src.Advance(20);
}
}
}

View File

@ -20,105 +20,103 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Dcerpc
{
public class DcerpcBinding
{
private static Hashtable _interfaces;
public class DcerpcBinding
{
private static Hashtable _interfaces;
static DcerpcBinding()
{
_interfaces = new Hashtable();
_interfaces.Put("srvsvc", Srvsvc.GetSyntax());
_interfaces.Put("lsarpc", Lsarpc.GetSyntax());
_interfaces.Put("samr", Samr.GetSyntax());
_interfaces.Put("netdfs", Netdfs.GetSyntax());
}
static DcerpcBinding()
{
_interfaces = new Hashtable();
_interfaces.Put("srvsvc", Srvsvc.GetSyntax());
_interfaces.Put("lsarpc", Lsarpc.GetSyntax());
_interfaces.Put("samr", Samr.GetSyntax());
_interfaces.Put("netdfs", Netdfs.GetSyntax());
}
public static void AddInterface(string name, string syntax)
{
_interfaces.Put(name, syntax);
}
public static void AddInterface(string name, string syntax)
{
_interfaces.Put(name, syntax);
}
internal string Proto;
internal string Proto;
internal string Server;
internal string Server;
internal string Endpoint;
internal string Endpoint;
internal Hashtable Options;
internal Hashtable Options;
internal Uuid Uuid;
internal Uuid Uuid;
internal int Major;
internal int Major;
internal int Minor;
internal int Minor;
internal DcerpcBinding(string proto, string server)
{
this.Proto = proto;
this.Server = server;
}
internal DcerpcBinding(string proto, string server)
{
this.Proto = proto;
this.Server = server;
}
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
internal virtual void SetOption(string key, object val)
{
if (key.Equals("endpoint"))
{
Endpoint = val.ToString().ToLower();
if (Endpoint.StartsWith("\\pipe\\"))
{
string iface = (string)_interfaces.Get(Runtime.Substring(Endpoint, 6));
if (iface != null)
{
int c;
int p;
c = iface.IndexOf(':');
p = iface.IndexOf('.', c + 1);
Uuid = new Uuid(Runtime.Substring(iface, 0, c));
Major = Convert.ToInt32(Runtime.Substring(iface, c + 1, p));
Minor = Convert.ToInt32(Runtime.Substring(iface, p + 1));
return;
}
}
throw new DcerpcException("Bad endpoint: " + Endpoint);
}
if (Options == null)
{
Options = new Hashtable();
}
Options.Put(key, val);
}
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
internal virtual void SetOption(string key, object val)
{
if (key.Equals("endpoint"))
{
Endpoint = val.ToString().ToLower();
if (Endpoint.StartsWith("\\pipe\\"))
{
string iface = (string)_interfaces.Get(Runtime.Substring(Endpoint, 6));
if (iface != null)
{
int c;
int p;
c = iface.IndexOf(':');
p = iface.IndexOf('.', c + 1);
Uuid = new Uuid(Runtime.Substring(iface, 0, c));
Major = Convert.ToInt32(Runtime.Substring(iface, c + 1, p));
Minor = Convert.ToInt32(Runtime.Substring(iface, p + 1));
return;
}
}
throw new DcerpcException("Bad endpoint: " + Endpoint);
}
if (Options == null)
{
Options = new Hashtable();
}
Options.Put(key, val);
}
internal virtual object GetOption(string key)
{
if (key.Equals("endpoint"))
{
return Endpoint;
}
if (Options != null)
{
return Options.Get(key);
}
internal virtual object GetOption(string key)
{
if (key.Equals("endpoint"))
{
return Endpoint;
}
if (Options != null)
{
return Options.Get(key);
}
return null;
}
public override string ToString()
{
/* string ret = proto + ":" + server + "[" + endpoint;
if (options != null)
{
Iterator iter = (Iterator) options.Keys.GetEnumerator();
while (iter.HasNext())
{
object key = iter.Next();
object val = options.Get(key);
ret += "," + key + "=" + val;
}
}
ret += "]";
return ret; */
return null;
}
public override string ToString()
{
/*
string ret = proto + ":" + server + "[" + endpoint;
if (options != null)
{
Iterator iter = (Iterator) options.Keys.GetEnumerator();
while (iter.HasNext())
{
object key = iter.Next();
object val = options.Get(key);
ret += "," + key + "=" + val;
}
}
ret += "]";
return ret;
*/
return null;
}
}
}
}
}

View File

@ -16,24 +16,25 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc
{
public static class DcerpcConstants
{
public static Uuid DcerpcUuidSyntaxNdr = new Uuid("8a885d04-1ceb-11c9-9fe8-08002b104860");
public static class DcerpcConstants
{
public static Uuid DcerpcUuidSyntaxNdr = new Uuid("8a885d04-1ceb-11c9-9fe8-08002b104860"
);
public static int DcerpcFirstFrag = unchecked(0x01);
public static int DcerpcFirstFrag = unchecked(0x01);
public static int DcerpcLastFrag = unchecked(0x02);
public static int DcerpcLastFrag = unchecked(0x02);
public static int DcerpcPendingCancel = unchecked(0x04);
public static int DcerpcPendingCancel = unchecked(0x04);
public static int DcerpcReserved1 = unchecked(0x08);
public static int DcerpcReserved1 = unchecked(0x08);
public static int DcerpcConcMpx = unchecked(0x10);
public static int DcerpcConcMpx = unchecked(0x10);
public static int DcerpcDidNotExecute = unchecked(0x20);
public static int DcerpcDidNotExecute = unchecked(0x20);
public static int DcerpcMaybe = unchecked(0x40);
public static int DcerpcMaybe = unchecked(0x40);
public static int DcerpcObjectUuid = unchecked(0x80);
}
public static int DcerpcObjectUuid = unchecked(0x80);
}
}

View File

@ -16,49 +16,33 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc
{
public static class DcerpcError
{
public static int DcerpcFaultOther = unchecked(0x00000001);
public static class DcerpcError
{
public static int DcerpcFaultOther = unchecked(0x00000001);
public static int DcerpcFaultAccessDenied = unchecked(0x00000005);
public static int DcerpcFaultAccessDenied = unchecked(0x00000005);
public static int DcerpcFaultCantPerform = unchecked(0x000006D8);
public static int DcerpcFaultCantPerform = unchecked(0x000006D8);
public static int DcerpcFaultNdr = unchecked(0x000006F7);
public static int DcerpcFaultNdr = unchecked(0x000006F7);
public static int DcerpcFaultInvalidTag = unchecked(0x1C000006);
public static int DcerpcFaultInvalidTag = unchecked(0x1C000006);
public static int DcerpcFaultContextMismatch = unchecked(0x1C00001A);
public static int DcerpcFaultContextMismatch = unchecked(0x1C00001A);
public static int DcerpcFaultOpRngError = unchecked(0x1C010002);
public static int DcerpcFaultOpRngError = unchecked(0x1C010002);
public static int DcerpcFaultUnkIf = unchecked(0x1C010003);
public static int DcerpcFaultUnkIf = unchecked(0x1C010003);
public static int DcerpcFaultProtoError = unchecked(0x1c01000b);
public static int DcerpcFaultProtoError = unchecked(0x1c01000b);
public static int[] DcerpcFaultCodes = {
DcerpcFaultOther,
DcerpcFaultAccessDenied,
DcerpcFaultCantPerform,
DcerpcFaultNdr,
DcerpcFaultInvalidTag,
DcerpcFaultContextMismatch,
DcerpcFaultOpRngError,
DcerpcFaultUnkIf,
DcerpcFaultProtoError
};
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 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" };
}
}

View File

@ -21,73 +21,73 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Dcerpc
{
public class DcerpcException : IOException
{
internal static string GetMessageByDcerpcError(int errcode)
{
int min = 0;
public class DcerpcException : IOException
{
internal static string GetMessageByDcerpcError(int errcode)
{
int min = 0;
int max = DcerpcError.DcerpcFaultCodes.Length;
while (max >= min)
{
int mid = (min + max) / 2;
while (max >= min)
{
int mid = (min + max) / 2;
if (errcode > DcerpcError.DcerpcFaultCodes[mid])
{
min = mid + 1;
}
else
{
{
min = mid + 1;
}
else
{
if (errcode < DcerpcError.DcerpcFaultCodes[mid])
{
max = mid - 1;
}
else
{
{
max = mid - 1;
}
else
{
return DcerpcError.DcerpcFaultMessages[mid];
}
}
}
return "0x" + Hexdump.ToHexString(errcode, 8);
}
}
}
}
return "0x" + Hexdump.ToHexString(errcode, 8);
}
private int _error;
private int _error;
private Exception _rootCause;
private Exception _rootCause;
internal DcerpcException(int error) : base(GetMessageByDcerpcError(error))
{
this._error = error;
}
internal DcerpcException(int error) : base(GetMessageByDcerpcError(error))
{
this._error = error;
}
public DcerpcException(string msg) : base(msg)
{
}
public DcerpcException(string msg) : base(msg)
{
}
public DcerpcException(string msg, Exception rootCause) : base(msg)
{
this._rootCause = rootCause;
}
public DcerpcException(string msg, Exception rootCause) : base(msg)
{
this._rootCause = rootCause;
}
public virtual int GetErrorCode()
{
return _error;
}
public virtual int GetErrorCode()
{
return _error;
}
public virtual Exception GetRootCause()
{
return _rootCause;
}
public virtual Exception GetRootCause()
{
return _rootCause;
}
public override string ToString()
{
if (_rootCause != null)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Runtime.PrintStackTrace(_rootCause, pw);
return base.ToString() + "\n" + sw;
}
return base.ToString();
}
}
public override string ToString()
{
if (_rootCause != null)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
Runtime.PrintStackTrace(_rootCause, pw);
return base.ToString() + "\n" + sw;
}
return base.ToString();
}
}
}

View File

@ -22,312 +22,311 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Dcerpc
{
public abstract class DcerpcHandle
{
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
protected internal static DcerpcBinding ParseBinding(string str)
{
int state;
int mark;
int si;
char[] arr = str.ToCharArray();
string proto = null;
string key = null;
DcerpcBinding binding = null;
state = mark = si = 0;
do
{
char ch = arr[si];
switch (state)
{
case 0:
{
if (ch == ':')
{
proto = Runtime.Substring(str, mark, si);
mark = si + 1;
state = 1;
}
break;
}
public abstract class DcerpcHandle
{
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
protected internal static DcerpcBinding ParseBinding(string str)
{
int state;
int mark;
int si;
char[] arr = str.ToCharArray();
string proto = null;
string key = null;
DcerpcBinding binding = null;
state = mark = si = 0;
do
{
char ch = arr[si];
switch (state)
{
case 0:
{
if (ch == ':')
{
proto = Runtime.Substring(str, mark, si);
mark = si + 1;
state = 1;
}
break;
}
case 1:
{
if (ch == '\\')
{
mark = si + 1;
break;
}
state = 2;
goto case 2;
}
case 1:
{
if (ch == '\\')
{
mark = si + 1;
break;
}
state = 2;
goto case 2;
}
case 2:
{
if (ch == '[')
{
string server = Runtime.Substring(str, mark, si).Trim();
if (server.Length == 0)
{
server = "127.0.0.1";
}
binding = new DcerpcBinding(proto, Runtime.Substring(str, mark, si));
mark = si + 1;
state = 5;
}
break;
}
case 2:
{
if (ch == '[')
{
string server = Runtime.Substring(str, mark, si).Trim();
if (server.Length == 0)
{
server = "127.0.0.1";
}
binding = new DcerpcBinding(proto, Runtime.Substring(str, mark, si));
mark = si + 1;
state = 5;
}
break;
}
case 5:
{
if (ch == '=')
{
key = Runtime.Substring(str, mark, si).Trim();
mark = si + 1;
}
else
{
if (ch == ',' || ch == ']')
{
string val = Runtime.Substring(str, mark, si).Trim();
if (key == null)
{
key = "endpoint";
}
binding.SetOption(key, val);
key = null;
}
}
break;
}
case 5:
{
if (ch == '=')
{
key = Runtime.Substring(str, mark, si).Trim();
mark = si + 1;
}
else
{
if (ch == ',' || ch == ']')
{
string val = Runtime.Substring(str, mark, si).Trim();
if (key == null)
{
key = "endpoint";
}
binding.SetOption(key, val);
key = null;
}
}
break;
}
default:
{
si = arr.Length;
break;
}
}
si++;
}
while (si < arr.Length);
if (binding == null || binding.Endpoint == null)
{
throw new DcerpcException("Invalid binding URL: " + str);
}
return binding;
}
default:
{
si = arr.Length;
break;
}
}
si++;
}
while (si < arr.Length);
if (binding == null || binding.Endpoint == null)
{
throw new DcerpcException("Invalid binding URL: " + str);
}
return binding;
}
protected internal DcerpcBinding Binding;
protected internal DcerpcBinding Binding;
protected internal int MaxXmit = 4280;
protected internal int MaxXmit = 4280;
protected internal int MaxRecv;
protected internal int MaxRecv;
protected internal int State;
protected internal int State;
protected internal IDcerpcSecurityProvider SecurityProvider;
protected internal IDcerpcSecurityProvider SecurityProvider;
private static int _callId = 1;
private static int _callId = 1;
/// <exception cref="UnknownHostException"></exception>
/// <exception cref="System.UriFormatException"></exception>
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
public static DcerpcHandle GetHandle(string url, NtlmPasswordAuthentication auth)
{
if (url.StartsWith("ncacn_np:"))
{
return new DcerpcPipeHandle(url, auth);
}
throw new DcerpcException("DCERPC transport not supported: " + url);
}
/// <exception cref="UnknownHostException"></exception>
/// <exception cref="System.UriFormatException"></exception>
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
public static DcerpcHandle GetHandle(string url, NtlmPasswordAuthentication auth)
{
if (url.StartsWith("ncacn_np:"))
{
return new DcerpcPipeHandle(url, auth);
}
throw new DcerpcException("DCERPC transport not supported: " + url);
}
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
/// <exception cref="System.IO.IOException"></exception>
public virtual void Bind()
{
lock (this)
{
try
{
State = 1;
DcerpcMessage bind = new DcerpcBind(Binding, this);
Sendrecv(bind);
}
catch (IOException ioe)
{
State = 0;
throw;
}
}
}
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
/// <exception cref="System.IO.IOException"></exception>
public virtual void Bind()
{
lock (this)
{
try
{
State = 1;
DcerpcMessage bind = new DcerpcBind(Binding, this);
Sendrecv(bind);
}
catch (IOException ioe)
{
State = 0;
throw;
}
}
}
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
/// <exception cref="System.IO.IOException"></exception>
public virtual void Sendrecv(DcerpcMessage msg)
{
byte[] stub;
byte[] frag;
NdrBuffer buf;
NdrBuffer fbuf;
bool isLast;
bool isDirect;
DcerpcException de;
if (State == 0)
{
Bind();
}
isDirect = true;
stub = BufferCache.GetBuffer();
try
{
int off;
int tot;
int n;
buf = new NdrBuffer(stub, 0);
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
/// <exception cref="System.IO.IOException"></exception>
public virtual void Sendrecv(DcerpcMessage msg)
{
byte[] stub;
byte[] frag;
NdrBuffer buf;
NdrBuffer fbuf;
bool isLast;
bool isDirect;
DcerpcException de;
if (State == 0)
{
Bind();
}
isDirect = true;
stub = BufferCache.GetBuffer();
try
{
int off;
int tot;
int n;
buf = new NdrBuffer(stub, 0);
msg.Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
msg.CallId = _callId++;
msg.Encode(buf);
if (SecurityProvider != null)
{
buf.SetIndex(0);
SecurityProvider.Wrap(buf);
}
tot = buf.GetLength() - 24;
off = 0;
while (off < tot)
{
n = tot - off;
if ((24 + n) > MaxXmit)
{
msg.CallId = _callId++;
msg.Encode(buf);
if (SecurityProvider != null)
{
buf.SetIndex(0);
SecurityProvider.Wrap(buf);
}
tot = buf.GetLength() - 24;
off = 0;
while (off < tot)
{
n = tot - off;
if ((24 + n) > MaxXmit)
{
msg.Flags &= ~DcerpcConstants.DcerpcLastFrag;
n = MaxXmit - 24;
}
else
{
n = MaxXmit - 24;
}
else
{
msg.Flags |= DcerpcConstants.DcerpcLastFrag;
isDirect = false;
msg.AllocHint = n;
}
msg.Length = 24 + n;
if (off > 0)
{
isDirect = false;
msg.AllocHint = n;
}
msg.Length = 24 + n;
if (off > 0)
{
msg.Flags &= ~DcerpcConstants.DcerpcFirstFrag;
}
if (
(msg.Flags & (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag))
!= (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag)
)
{
buf.Start = off;
buf.Reset();
msg.Encode_header(buf);
buf.Enc_ndr_long(msg.AllocHint);
buf.Enc_ndr_short(0);
buf.Enc_ndr_short(msg.GetOpnum());
}
DoSendFragment(stub, off, msg.Length, isDirect);
off += n;
}
DoReceiveFragment(stub, isDirect);
buf.Reset();
buf.SetIndex(8);
buf.SetLength(buf.Dec_ndr_short());
if (SecurityProvider != null)
{
SecurityProvider.Unwrap(buf);
}
buf.SetIndex(0);
msg.Decode_header(buf);
off = 24;
}
if ((msg.Flags & (DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag)) != (DcerpcConstants.DcerpcFirstFrag |
DcerpcConstants.DcerpcLastFrag))
{
buf.Start = off;
buf.Reset();
msg.Encode_header(buf);
buf.Enc_ndr_long(msg.AllocHint);
buf.Enc_ndr_short(0);
buf.Enc_ndr_short(msg.GetOpnum());
}
DoSendFragment(stub, off, msg.Length, isDirect);
off += n;
}
DoReceiveFragment(stub, isDirect);
buf.Reset();
buf.SetIndex(8);
buf.SetLength(buf.Dec_ndr_short());
if (SecurityProvider != null)
{
SecurityProvider.Unwrap(buf);
}
buf.SetIndex(0);
msg.Decode_header(buf);
off = 24;
if (msg.Ptype == 2 && msg.IsFlagSet(DcerpcConstants.DcerpcLastFrag) == false)
{
off = msg.Length;
}
frag = null;
fbuf = null;
{
off = msg.Length;
}
frag = null;
fbuf = null;
while (msg.IsFlagSet(DcerpcConstants.DcerpcLastFrag) == false)
{
int stubFragLen;
if (frag == null)
{
frag = new byte[MaxRecv];
fbuf = new NdrBuffer(frag, 0);
}
DoReceiveFragment(frag, isDirect);
fbuf.Reset();
fbuf.SetIndex(8);
fbuf.SetLength(fbuf.Dec_ndr_short());
if (SecurityProvider != null)
{
SecurityProvider.Unwrap(fbuf);
}
fbuf.Reset();
msg.Decode_header(fbuf);
stubFragLen = msg.Length - 24;
if ((off + stubFragLen) > stub.Length)
{
// shouldn't happen if alloc_hint is correct or greater
byte[] tmp = new byte[off + stubFragLen];
Array.Copy(stub, 0, tmp, 0, off);
stub = tmp;
}
Array.Copy(frag, 24, stub, off, stubFragLen);
off += stubFragLen;
}
buf = new NdrBuffer(stub, 0);
msg.Decode(buf);
}
finally
{
BufferCache.ReleaseBuffer(stub);
}
if ((de = msg.GetResult()) != null)
{
throw de;
}
}
{
int stubFragLen;
if (frag == null)
{
frag = new byte[MaxRecv];
fbuf = new NdrBuffer(frag, 0);
}
DoReceiveFragment(frag, isDirect);
fbuf.Reset();
fbuf.SetIndex(8);
fbuf.SetLength(fbuf.Dec_ndr_short());
if (SecurityProvider != null)
{
SecurityProvider.Unwrap(fbuf);
}
fbuf.Reset();
msg.Decode_header(fbuf);
stubFragLen = msg.Length - 24;
if ((off + stubFragLen) > stub.Length)
{
// shouldn't happen if alloc_hint is correct or greater
byte[] tmp = new byte[off + stubFragLen];
Array.Copy(stub, 0, tmp, 0, off);
stub = tmp;
}
Array.Copy(frag, 24, stub, off, stubFragLen);
off += stubFragLen;
}
buf = new NdrBuffer(stub, 0);
msg.Decode(buf);
}
finally
{
BufferCache.ReleaseBuffer(stub);
}
if ((de = msg.GetResult()) != null)
{
throw de;
}
}
public virtual void SetDcerpcSecurityProvider(IDcerpcSecurityProvider securityProvider
)
{
this.SecurityProvider = securityProvider;
}
public virtual void SetDcerpcSecurityProvider(IDcerpcSecurityProvider securityProvider
)
{
this.SecurityProvider = securityProvider;
}
public virtual string GetServer()
{
if (this is DcerpcPipeHandle)
{
return ((DcerpcPipeHandle)this).Pipe.GetServer();
}
return null;
}
public virtual string GetServer()
{
if (this is DcerpcPipeHandle)
{
return ((DcerpcPipeHandle)this).Pipe.GetServer();
}
return null;
}
public virtual Principal GetPrincipal()
{
if (this is DcerpcPipeHandle)
{
return ((DcerpcPipeHandle)this).Pipe.GetPrincipal();
}
return null;
}
public virtual Principal GetPrincipal()
{
if (this is DcerpcPipeHandle)
{
return ((DcerpcPipeHandle)this).Pipe.GetPrincipal();
}
return null;
}
public override string ToString()
{
return Binding.ToString();
}
public override string ToString()
{
return Binding.ToString();
}
/// <exception cref="System.IO.IOException"></exception>
protected internal abstract void DoSendFragment(byte[] buf, int off, int length, bool isDirect);
/// <exception cref="System.IO.IOException"></exception>
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);
/// <exception cref="System.IO.IOException"></exception>
protected internal abstract void DoReceiveFragment(byte[] buf, bool isDirect);
/// <exception cref="System.IO.IOException"></exception>
public abstract void Close();
/// <exception cref="System.IO.IOException"></exception>
public abstract void Close();
public DcerpcHandle()
{
MaxRecv = MaxXmit;
}
}
public DcerpcHandle()
{
MaxRecv = MaxXmit;
}
}
}

View File

@ -18,133 +18,133 @@ using SharpCifs.Dcerpc.Ndr;
namespace SharpCifs.Dcerpc
{
public abstract class DcerpcMessage : NdrObject
{
protected internal int Ptype = -1;
public abstract class DcerpcMessage : NdrObject
{
protected internal int Ptype = -1;
protected internal int Flags;
protected internal int Flags;
protected internal int Length;
protected internal int Length;
protected internal int CallId;
protected internal int CallId;
protected internal int AllocHint;
protected internal int AllocHint;
protected internal int Result;
protected internal int Result;
public virtual bool IsFlagSet(int flag)
{
return (Flags & flag) == flag;
}
public virtual bool IsFlagSet(int flag)
{
return (Flags & flag) == flag;
}
public virtual void UnsetFlag(int flag)
{
Flags &= ~flag;
}
public virtual void UnsetFlag(int flag)
{
Flags &= ~flag;
}
public virtual void SetFlag(int flag)
{
Flags |= flag;
}
public virtual void SetFlag(int flag)
{
Flags |= flag;
}
public virtual DcerpcException GetResult()
{
if (Result != 0)
{
return new DcerpcException(Result);
}
return null;
}
public virtual DcerpcException GetResult()
{
if (Result != 0)
{
return new DcerpcException(Result);
}
return null;
}
internal virtual void Encode_header(NdrBuffer buf)
{
buf.Enc_ndr_small(5);
buf.Enc_ndr_small(0);
buf.Enc_ndr_small(Ptype);
buf.Enc_ndr_small(Flags);
buf.Enc_ndr_long(unchecked(0x00000010));
buf.Enc_ndr_short(Length);
buf.Enc_ndr_short(0);
buf.Enc_ndr_long(CallId);
}
internal virtual void Encode_header(NdrBuffer buf)
{
buf.Enc_ndr_small(5);
buf.Enc_ndr_small(0);
buf.Enc_ndr_small(Ptype);
buf.Enc_ndr_small(Flags);
buf.Enc_ndr_long(unchecked(0x00000010));
buf.Enc_ndr_short(Length);
buf.Enc_ndr_short(0);
buf.Enc_ndr_long(CallId);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
internal virtual void Decode_header(NdrBuffer buf)
{
if (buf.Dec_ndr_small() != 5 || buf.Dec_ndr_small() != 0)
{
throw new NdrException("DCERPC version not supported");
}
Ptype = buf.Dec_ndr_small();
Flags = buf.Dec_ndr_small();
if (buf.Dec_ndr_long() != unchecked(0x00000010))
{
throw new NdrException("Data representation not supported");
}
Length = buf.Dec_ndr_short();
if (buf.Dec_ndr_short() != 0)
{
throw new NdrException("DCERPC authentication not supported");
}
CallId = buf.Dec_ndr_long();
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
internal virtual void Decode_header(NdrBuffer buf)
{
if (buf.Dec_ndr_small() != 5 || buf.Dec_ndr_small() != 0)
{
throw new NdrException("DCERPC version not supported");
}
Ptype = buf.Dec_ndr_small();
Flags = buf.Dec_ndr_small();
if (buf.Dec_ndr_long() != unchecked(0x00000010))
{
throw new NdrException("Data representation not supported");
}
Length = buf.Dec_ndr_short();
if (buf.Dec_ndr_short() != 0)
{
throw new NdrException("DCERPC authentication not supported");
}
CallId = buf.Dec_ndr_long();
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer buf)
{
int start = buf.GetIndex();
int allocHintIndex = 0;
buf.Advance(16);
if (Ptype == 0)
{
allocHintIndex = buf.GetIndex();
buf.Enc_ndr_long(0);
buf.Enc_ndr_short(0);
buf.Enc_ndr_short(GetOpnum());
}
Encode_in(buf);
Length = buf.GetIndex() - start;
if (Ptype == 0)
{
buf.SetIndex(allocHintIndex);
AllocHint = Length - allocHintIndex;
buf.Enc_ndr_long(AllocHint);
}
buf.SetIndex(start);
Encode_header(buf);
buf.SetIndex(start + Length);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer buf)
{
int start = buf.GetIndex();
int allocHintIndex = 0;
buf.Advance(16);
if (Ptype == 0)
{
allocHintIndex = buf.GetIndex();
buf.Enc_ndr_long(0);
buf.Enc_ndr_short(0);
buf.Enc_ndr_short(GetOpnum());
}
Encode_in(buf);
Length = buf.GetIndex() - start;
if (Ptype == 0)
{
buf.SetIndex(allocHintIndex);
AllocHint = Length - allocHintIndex;
buf.Enc_ndr_long(AllocHint);
}
buf.SetIndex(start);
Encode_header(buf);
buf.SetIndex(start + Length);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer buf)
{
Decode_header(buf);
if (Ptype != 12 && Ptype != 2 && Ptype != 3 && Ptype != 13)
{
throw new NdrException("Unexpected ptype: " + Ptype);
}
if (Ptype == 2 || Ptype == 3)
{
AllocHint = buf.Dec_ndr_long();
buf.Dec_ndr_short();
buf.Dec_ndr_short();
}
if (Ptype == 3 || Ptype == 13)
{
Result = buf.Dec_ndr_long();
}
else
{
Decode_out(buf);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer buf)
{
Decode_header(buf);
if (Ptype != 12 && Ptype != 2 && Ptype != 3 && Ptype != 13)
{
throw new NdrException("Unexpected ptype: " + Ptype);
}
if (Ptype == 2 || Ptype == 3)
{
AllocHint = buf.Dec_ndr_long();
buf.Dec_ndr_short();
buf.Dec_ndr_short();
}
if (Ptype == 3 || Ptype == 13)
{
Result = buf.Dec_ndr_long();
}
else
{
Decode_out(buf);
}
}
public abstract int GetOpnum();
public abstract int GetOpnum();
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Encode_in(NdrBuffer dst);
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Encode_in(NdrBuffer dst);
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Decode_out(NdrBuffer src);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Decode_out(NdrBuffer src);
}
}

View File

@ -22,115 +22,114 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Dcerpc
{
public class DcerpcPipeHandle : DcerpcHandle
{
internal SmbNamedPipe Pipe;
public class DcerpcPipeHandle : DcerpcHandle
{
internal SmbNamedPipe Pipe;
internal SmbFileInputStream In;
internal SmbFileInputStream In;
internal SmbFileOutputStream Out;
internal SmbFileOutputStream Out;
internal bool IsStart = true;
internal bool IsStart = true;
/// <exception cref="UnknownHostException"></exception>
/// <exception cref="System.UriFormatException"></exception>
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
public DcerpcPipeHandle(string url, NtlmPasswordAuthentication auth)
{
Binding = ParseBinding(url);
url = "smb://" + Binding.Server + "/IPC$/" + Runtime.Substring(Binding.Endpoint, 6);
string @params = string.Empty;
string server;
string address;
server = (string)Binding.GetOption("server");
if (server != null)
{
@params += "&server=" + server;
}
address = (string)Binding.GetOption("address");
if (server != null)
{
@params += "&address=" + address;
}
if (@params.Length > 0)
{
url += "?" + Runtime.Substring(@params, 1);
}
Pipe = new SmbNamedPipe(url,
(unchecked(0x2019F) << 16)
| SmbNamedPipe.PipeTypeRdwr
| SmbNamedPipe.PipeTypeDceTransact,
auth);
}
/// <exception cref="UnknownHostException"></exception>
/// <exception cref="System.UriFormatException"></exception>
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
public DcerpcPipeHandle(string url, NtlmPasswordAuthentication auth)
{
Binding = ParseBinding(url);
url = "smb://" + Binding.Server + "/IPC$/" + Runtime.Substring(Binding.Endpoint
, 6);
string @params = string.Empty;
string server;
string address;
server = (string)Binding.GetOption("server");
if (server != null)
{
@params += "&server=" + server;
}
address = (string)Binding.GetOption("address");
if (server != null)
{
@params += "&address=" + address;
}
if (@params.Length > 0)
{
url += "?" + Runtime.Substring(@params, 1);
}
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)
{
if (Out != null && Out.IsOpen() == false)
{
throw new IOException("DCERPC pipe is no longer open");
}
if (In == null)
{
In = (SmbFileInputStream)Pipe.GetNamedPipeInputStream();
}
if (Out == null)
{
Out = (SmbFileOutputStream)Pipe.GetNamedPipeOutputStream();
}
if (isDirect)
{
Out.WriteDirect(buf, off, length, 1);
return;
}
Out.Write(buf, off, length);
}
/// <exception cref="System.IO.IOException"></exception>
protected internal override void DoSendFragment(byte[] buf, int off, int length,
bool isDirect)
{
if (Out != null && Out.IsOpen() == false)
{
throw new IOException("DCERPC pipe is no longer open");
}
if (In == null)
{
In = (SmbFileInputStream)Pipe.GetNamedPipeInputStream();
}
if (Out == null)
{
Out = (SmbFileOutputStream)Pipe.GetNamedPipeOutputStream();
}
if (isDirect)
{
Out.WriteDirect(buf, off, length, 1);
return;
}
Out.Write(buf, off, length);
}
/// <exception cref="System.IO.IOException"></exception>
protected internal override void DoReceiveFragment(byte[] buf, bool isDirect)
{
int off;
int flags;
int length;
if (buf.Length < MaxRecv)
{
throw new ArgumentException("buffer too small");
}
if (IsStart && !isDirect)
{
// start of new frag, do trans
off = In.Read(buf, 0, 1024);
}
else
{
off = In.ReadDirect(buf, 0, buf.Length);
}
if (buf[0] != 5 && buf[1] != 0)
{
throw new IOException("Unexpected DCERPC PDU header");
}
flags = buf[3] & unchecked(0xFF);
// next read is start of new frag
/// <exception cref="System.IO.IOException"></exception>
protected internal override void DoReceiveFragment(byte[] buf, bool isDirect)
{
int off;
int flags;
int length;
if (buf.Length < MaxRecv)
{
throw new ArgumentException("buffer too small");
}
if (IsStart && !isDirect)
{
// start of new frag, do trans
off = In.Read(buf, 0, 1024);
}
else
{
off = In.ReadDirect(buf, 0, buf.Length);
}
if (buf[0] != 5 && buf[1] != 0)
{
throw new IOException("Unexpected DCERPC PDU header");
}
flags = buf[3] & unchecked(0xFF);
// next read is start of new frag
IsStart = (flags & DcerpcConstants.DcerpcLastFrag) == DcerpcConstants.DcerpcLastFrag;
length = Encdec.Dec_uint16le(buf, 8);
if (length > MaxRecv)
{
throw new IOException("Unexpected fragment length: " + length);
}
while (off < length)
{
off += In.ReadDirect(buf, off, length - off);
}
}
length = Encdec.Dec_uint16le(buf, 8);
if (length > MaxRecv)
{
throw new IOException("Unexpected fragment length: " + length);
}
while (off < length)
{
off += In.ReadDirect(buf, off, length - off);
}
}
/// <exception cref="System.IO.IOException"></exception>
public override void Close()
{
State = 0;
if (Out != null)
{
Out.Close();
}
}
}
/// <exception cref="System.IO.IOException"></exception>
public override void Close()
{
State = 0;
if (Out != null)
{
Out.Close();
}
}
}
}

View File

@ -18,12 +18,12 @@ using SharpCifs.Dcerpc.Ndr;
namespace SharpCifs.Dcerpc
{
public interface IDcerpcSecurityProvider
{
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
void Wrap(NdrBuffer outgoing);
public interface IDcerpcSecurityProvider
{
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
void Wrap(NdrBuffer outgoing);
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
void Unwrap(NdrBuffer incoming);
}
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
void Unwrap(NdrBuffer incoming);
}
}

View File

@ -18,26 +18,26 @@ using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class LsaPolicyHandle : Rpc.PolicyHandle
{
/// <exception cref="System.IO.IOException"></exception>
public LsaPolicyHandle(DcerpcHandle handle, string server, int access)
{
if (server == null)
{
server = "\\\\";
}
MsrpcLsarOpenPolicy2 rpc = new MsrpcLsarOpenPolicy2(server, access, this);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
}
public class LsaPolicyHandle : Rpc.PolicyHandle
{
/// <exception cref="System.IO.IOException"></exception>
public LsaPolicyHandle(DcerpcHandle handle, string server, int access)
{
if (server == null)
{
server = "\\\\";
}
MsrpcLsarOpenPolicy2 rpc = new MsrpcLsarOpenPolicy2(server, access, this);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
}

View File

@ -18,17 +18,17 @@ using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
internal class LsarSidArrayX : Lsarpc.LsarSidArray
{
internal LsarSidArrayX(Sid[] sids)
{
NumSids = sids.Length;
this.Sids = new Lsarpc.LsarSidPtr[sids.Length];
for (int si = 0; si < sids.Length; si++)
{
this.Sids[si] = new Lsarpc.LsarSidPtr();
this.Sids[si].Sid = sids[si];
}
}
}
internal class LsarSidArrayX : Lsarpc.LsarSidArray
{
internal LsarSidArrayX(Sid[] sids)
{
NumSids = sids.Length;
this.Sids = new Lsarpc.LsarSidPtr[sids.Length];
for (int si = 0; si < sids.Length; si++)
{
this.Sids[si] = new Lsarpc.LsarSidPtr();
this.Sids[si].Sid = sids[si];
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -19,25 +19,25 @@ using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcDfsRootEnum : Netdfs.NetrDfsEnumEx
{
public MsrpcDfsRootEnum(string server) : base(server, 200, unchecked(0xFFFF), new Netdfs.DfsEnumStruct(), new NdrLong(0))
{
Info.Level = Level;
Info.E = new Netdfs.DfsEnumArray200();
Ptype = 0;
public class MsrpcDfsRootEnum : Netdfs.NetrDfsEnumEx
{
public MsrpcDfsRootEnum(string server) : base(server, 200, unchecked(0xFFFF), new Netdfs.DfsEnumStruct(), new NdrLong(0))
{
Info.Level = Level;
Info.E = new Netdfs.DfsEnumArray200();
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
public virtual IFileEntry[] GetEntries()
{
Netdfs.DfsEnumArray200 a200 = (Netdfs.DfsEnumArray200)Info.E;
SmbShareInfo[] entries = new SmbShareInfo[a200.Count];
for (int i = 0; i < a200.Count; i++)
{
entries[i] = new SmbShareInfo(a200.S[i].DfsName, 0, null);
}
return entries;
}
}
public virtual IFileEntry[] GetEntries()
{
Netdfs.DfsEnumArray200 a200 = (Netdfs.DfsEnumArray200)Info.E;
SmbShareInfo[] entries = new SmbShareInfo[a200.Count];
for (int i = 0; i < a200.Count; i++)
{
entries[i] = new SmbShareInfo(a200.S[i].DfsName, 0, null);
}
return entries;
}
}
}

View File

@ -16,14 +16,14 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcEnumerateAliasesInDomain : Samr.SamrEnumerateAliasesInDomain
{
public MsrpcEnumerateAliasesInDomain(SamrDomainHandle domainHandle, int acctFlags
, Samr.SamrSamArray sam) : base(domainHandle, 0, acctFlags, null, 0)
{
this.Sam = sam;
Ptype = 0;
public class MsrpcEnumerateAliasesInDomain : Samr.SamrEnumerateAliasesInDomain
{
public MsrpcEnumerateAliasesInDomain(SamrDomainHandle domainHandle, int acctFlags
, Samr.SamrSamArray sam) : base(domainHandle, 0, acctFlags, null, 0)
{
this.Sam = sam;
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}
}
}

View File

@ -16,14 +16,14 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcGetMembersInAlias : Samr.SamrGetMembersInAlias
{
public MsrpcGetMembersInAlias(SamrAliasHandle aliasHandle, Lsarpc.LsarSidArray sids
) : base(aliasHandle, sids)
{
this.Sids = sids;
Ptype = 0;
public class MsrpcGetMembersInAlias : Samr.SamrGetMembersInAlias
{
public MsrpcGetMembersInAlias(SamrAliasHandle aliasHandle, Lsarpc.LsarSidArray sids
) : base(aliasHandle, sids)
{
this.Sids = sids;
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}
}
}

View File

@ -18,21 +18,17 @@ using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcLookupSids : Lsarpc.LsarLookupSids
{
internal Sid[] sids;
public class MsrpcLookupSids : Lsarpc.LsarLookupSids
{
internal Sid[] sids;
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;
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;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}
}
}

View File

@ -16,23 +16,20 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcLsarOpenPolicy2 : Lsarpc.LsarOpenPolicy2
{
public MsrpcLsarOpenPolicy2(string server, int access, LsaPolicyHandle policyHandle)
: base(server,
new Lsarpc.LsarObjectAttributes(),
access,
policyHandle)
{
ObjectAttributes.Length = 24;
Lsarpc.LsarQosInfo qos = new Lsarpc.LsarQosInfo();
qos.Length = 12;
qos.ImpersonationLevel = 2;
qos.ContextMode = 1;
qos.EffectiveOnly = 0;
ObjectAttributes.SecurityQualityOfService = qos;
Ptype = 0;
public class MsrpcLsarOpenPolicy2 : Lsarpc.LsarOpenPolicy2
{
public MsrpcLsarOpenPolicy2(string server, int access, LsaPolicyHandle policyHandle
) : base(server, new Lsarpc.LsarObjectAttributes(), access, policyHandle)
{
ObjectAttributes.Length = 24;
Lsarpc.LsarQosInfo qos = new Lsarpc.LsarQosInfo();
qos.Length = 12;
qos.ImpersonationLevel = 2;
qos.ContextMode = 1;
qos.EffectiveOnly = 0;
ObjectAttributes.SecurityQualityOfService = qos;
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}
}
}

View File

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

View File

@ -16,13 +16,13 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcSamrConnect2 : Samr.SamrConnect2
{
public MsrpcSamrConnect2(string server, int access, SamrPolicyHandle policyHandle)
: base(server, access, policyHandle)
{
Ptype = 0;
public class MsrpcSamrConnect2 : Samr.SamrConnect2
{
public MsrpcSamrConnect2(string server, int access, SamrPolicyHandle policyHandle
) : base(server, access, policyHandle)
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}
}
}

View File

@ -16,13 +16,13 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcSamrConnect4 : Samr.SamrConnect4
{
public MsrpcSamrConnect4(string server, int access, SamrPolicyHandle policyHandle)
: base(server, 2, access, policyHandle)
{
Ptype = 0;
public class MsrpcSamrConnect4 : Samr.SamrConnect4
{
public MsrpcSamrConnect4(string server, int access, SamrPolicyHandle policyHandle
) : base(server, 2, access, policyHandle)
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}
}
}

View File

@ -16,16 +16,13 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcSamrOpenAlias : Samr.SamrOpenAlias
{
public MsrpcSamrOpenAlias(SamrDomainHandle handle,
int access,
int rid,
SamrAliasHandle aliasHandle)
: base(handle, access, rid, aliasHandle)
{
Ptype = 0;
public class MsrpcSamrOpenAlias : Samr.SamrOpenAlias
{
public MsrpcSamrOpenAlias(SamrDomainHandle handle, int access, int rid, SamrAliasHandle
aliasHandle) : base(handle, access, rid, aliasHandle)
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
}
}
}

View File

@ -18,11 +18,8 @@ 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;

View File

@ -18,38 +18,38 @@ using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcShareEnum : Srvsvc.ShareEnumAll
{
internal class MsrpcShareInfo1 : SmbShareInfo
{
internal MsrpcShareInfo1(MsrpcShareEnum enclosing, Srvsvc.ShareInfo1 info1)
{
this._enclosing = enclosing;
NetName = info1.Netname;
Type = info1.Type;
Remark = info1.Remark;
}
public class MsrpcShareEnum : Srvsvc.ShareEnumAll
{
internal class MsrpcShareInfo1 : SmbShareInfo
{
internal MsrpcShareInfo1(MsrpcShareEnum enclosing, Srvsvc.ShareInfo1 info1)
{
this._enclosing = enclosing;
NetName = info1.Netname;
Type = info1.Type;
Remark = info1.Remark;
}
private readonly MsrpcShareEnum _enclosing;
}
private readonly MsrpcShareEnum _enclosing;
}
public MsrpcShareEnum(string server)
: base("\\\\" + server, 1, new Srvsvc.ShareInfoCtr1(), -1, 0, 0)
{
Ptype = 0;
public MsrpcShareEnum(string server) : base("\\\\" + server, 1, new Srvsvc.ShareInfoCtr1
(), -1, 0, 0)
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
public virtual IFileEntry[] GetEntries()
{
Srvsvc.ShareInfoCtr1 ctr = (Srvsvc.ShareInfoCtr1)Info;
MsrpcShareInfo1[] entries = new MsrpcShareInfo1[ctr
.Count];
for (int i = 0; i < ctr.Count; i++)
{
entries[i] = new MsrpcShareInfo1(this, ctr.Array[i]);
}
return entries;
}
}
public virtual IFileEntry[] GetEntries()
{
Srvsvc.ShareInfoCtr1 ctr = (Srvsvc.ShareInfoCtr1)Info;
MsrpcShareInfo1[] entries = new MsrpcShareInfo1[ctr
.Count];
for (int i = 0; i < ctr.Count; i++)
{
entries[i] = new MsrpcShareInfo1(this, ctr.Array[i]);
}
return entries;
}
}
}

View File

@ -18,26 +18,26 @@ using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc
{
public class MsrpcShareGetInfo : Srvsvc.ShareGetInfo
{
public MsrpcShareGetInfo(string server, string sharename)
: base(server, sharename, 502, new Srvsvc.ShareInfo502())
{
Ptype = 0;
public class MsrpcShareGetInfo : Srvsvc.ShareGetInfo
{
public MsrpcShareGetInfo(string server, string sharename) : base(server, sharename
, 502, new Srvsvc.ShareInfo502())
{
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual Ace[] GetSecurity()
{
Srvsvc.ShareInfo502 info502 = (Srvsvc.ShareInfo502)Info;
if (info502.SecurityDescriptor != null)
{
SecurityDescriptor sd;
sd = new SecurityDescriptor(info502.SecurityDescriptor, 0, info502.SdSize);
return sd.Aces;
}
return null;
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual Ace[] GetSecurity()
{
Srvsvc.ShareInfo502 info502 = (Srvsvc.ShareInfo502)Info;
if (info502.SecurityDescriptor != null)
{
SecurityDescriptor sd;
sd = new SecurityDescriptor(info502.SecurityDescriptor, 0, info502.SdSize);
return sd.Aces;
}
return null;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -18,25 +18,23 @@ using SharpCifs.Smb;
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)
{
MsrpcSamrOpenAlias rpc = new MsrpcSamrOpenAlias(domainHandle, access, rid, this);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
}
public class SamrAliasHandle : Rpc.PolicyHandle
{
/// <exception cref="System.IO.IOException"></exception>
public SamrAliasHandle(DcerpcHandle handle, SamrDomainHandle domainHandle, int access
, int rid)
{
MsrpcSamrOpenAlias rpc = new MsrpcSamrOpenAlias(domainHandle, access, rid, this);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
}

View File

@ -18,25 +18,24 @@ using SharpCifs.Smb;
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)
{
MsrpcSamrOpenDomain rpc = new MsrpcSamrOpenDomain(policyHandle, access, sid, this);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
}
public class SamrDomainHandle : Rpc.PolicyHandle
{
/// <exception cref="System.IO.IOException"></exception>
public SamrDomainHandle(DcerpcHandle handle, SamrPolicyHandle policyHandle, int access
, Rpc.SidT sid)
{
MsrpcSamrOpenDomain rpc = new MsrpcSamrOpenDomain(policyHandle, access, sid, this
);
handle.Sendrecv(rpc);
if (rpc.Retval != 0)
{
throw new SmbException(rpc.Retval, false);
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
}

View File

@ -16,34 +16,34 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Msrpc
{
public class SamrPolicyHandle : Rpc.PolicyHandle
{
/// <exception cref="System.IO.IOException"></exception>
public SamrPolicyHandle(DcerpcHandle handle, string server, int access)
{
if (server == null)
{
server = "\\\\";
}
MsrpcSamrConnect4 rpc = new MsrpcSamrConnect4(server, access, this);
try
{
handle.Sendrecv(rpc);
}
catch (DcerpcException de)
{
if (de.GetErrorCode() != DcerpcError.DcerpcFaultOpRngError)
{
throw;
}
MsrpcSamrConnect2 rpc2 = new MsrpcSamrConnect2(server, access, this);
handle.Sendrecv(rpc2);
}
}
public class SamrPolicyHandle : Rpc.PolicyHandle
{
/// <exception cref="System.IO.IOException"></exception>
public SamrPolicyHandle(DcerpcHandle handle, string server, int access)
{
if (server == null)
{
server = "\\\\";
}
MsrpcSamrConnect4 rpc = new MsrpcSamrConnect4(server, access, this);
try
{
handle.Sendrecv(rpc);
}
catch (DcerpcException de)
{
if (de.GetErrorCode() != DcerpcError.DcerpcFaultOpRngError)
{
throw;
}
MsrpcSamrConnect2 rpc2 = new MsrpcSamrConnect2(server, access, this);
handle.Sendrecv(rpc2);
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
/// <exception cref="System.IO.IOException"></exception>
public virtual void Close()
{
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -20,285 +20,286 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrBuffer
{
internal int Referent;
public class NdrBuffer
{
internal int Referent;
internal Hashtable Referents;
internal Hashtable Referents;
internal class Entry
{
internal int Referent;
internal class Entry
{
internal int Referent;
internal object Obj;
}
internal object Obj;
}
public byte[] Buf;
public byte[] Buf;
public int Start;
public int Start;
public int Index;
public int Index;
public int Length;
public int Length;
public NdrBuffer Deferred;
public NdrBuffer Deferred;
public NdrBuffer(byte[] buf, int start)
{
this.Buf = buf;
this.Start = Index = start;
Length = 0;
Deferred = this;
}
public NdrBuffer(byte[] buf, int start)
{
this.Buf = buf;
this.Start = Index = start;
Length = 0;
Deferred = this;
}
public virtual NdrBuffer Derive(int idx)
{
NdrBuffer nb = new NdrBuffer(Buf, Start);
nb.Index = idx;
nb.Deferred = Deferred;
return nb;
}
public virtual NdrBuffer Derive(int idx)
{
NdrBuffer nb = new NdrBuffer(Buf, Start);
nb.Index = idx;
nb.Deferred = Deferred;
return nb;
}
public virtual void Reset()
{
Index = Start;
Length = 0;
Deferred = this;
}
public virtual void Reset()
{
Index = Start;
Length = 0;
Deferred = this;
}
public virtual int GetIndex()
{
return Index;
}
public virtual int GetIndex()
{
return Index;
}
public virtual void SetIndex(int index)
{
this.Index = index;
}
public virtual void SetIndex(int index)
{
this.Index = index;
}
public virtual int GetCapacity()
{
return Buf.Length - Start;
}
public virtual int GetCapacity()
{
return Buf.Length - Start;
}
public virtual int GetTailSpace()
{
return Buf.Length - Index;
}
public virtual int GetTailSpace()
{
return Buf.Length - Index;
}
public virtual byte[] GetBuffer()
{
return Buf;
}
public virtual byte[] GetBuffer()
{
return Buf;
}
public virtual int Align(int boundary, byte value)
{
int n = Align(boundary);
int i = n;
while (i > 0)
{
Buf[Index - i] = value;
i--;
}
return n;
}
public virtual int Align(int boundary, byte value)
{
int n = Align(boundary);
int i = n;
while (i > 0)
{
Buf[Index - i] = value;
i--;
}
return n;
}
public virtual void WriteOctetArray(byte[] b, int i, int l)
{
Array.Copy(b, i, Buf, Index, l);
Advance(l);
}
public virtual void WriteOctetArray(byte[] b, int i, int l)
{
Array.Copy(b, i, Buf, Index, l);
Advance(l);
}
public virtual void ReadOctetArray(byte[] b, int i, int l)
{
Array.Copy(Buf, Index, b, i, l);
Advance(l);
}
public virtual void ReadOctetArray(byte[] b, int i, int l)
{
Array.Copy(Buf, Index, b, i, l);
Advance(l);
}
public virtual int GetLength()
{
return Deferred.Length;
}
public virtual int GetLength()
{
return Deferred.Length;
}
public virtual void SetLength(int length)
{
Deferred.Length = length;
}
public virtual void SetLength(int length)
{
Deferred.Length = length;
}
public virtual void Advance(int n)
{
Index += n;
if ((Index - Start) > Deferred.Length)
{
Deferred.Length = Index - Start;
}
}
public virtual void Advance(int n)
{
Index += n;
if ((Index - Start) > Deferred.Length)
{
Deferred.Length = Index - Start;
}
}
public virtual int Align(int boundary)
{
int m = boundary - 1;
int i = Index - Start;
int n = ((i + m) & ~m) - i;
Advance(n);
return n;
}
public virtual int Align(int boundary)
{
int m = boundary - 1;
int i = Index - Start;
int n = ((i + m) & ~m) - i;
Advance(n);
return n;
}
public virtual void Enc_ndr_small(int s)
{
Buf[Index] = unchecked((byte)(s & unchecked(0xFF)));
Advance(1);
}
public virtual void Enc_ndr_small(int s)
{
Buf[Index] = unchecked((byte)(s & unchecked(0xFF)));
Advance(1);
}
public virtual int Dec_ndr_small()
{
int val = Buf[Index] & unchecked(0xFF);
Advance(1);
return val;
}
public virtual int Dec_ndr_small()
{
int val = Buf[Index] & unchecked(0xFF);
Advance(1);
return val;
}
public virtual void Enc_ndr_short(int s)
{
Align(2);
Encdec.Enc_uint16le((short)s, Buf, Index);
Advance(2);
}
public virtual void Enc_ndr_short(int s)
{
Align(2);
Encdec.Enc_uint16le((short)s, Buf, Index);
Advance(2);
}
public virtual int Dec_ndr_short()
{
Align(2);
int val = Encdec.Dec_uint16le(Buf, Index);
Advance(2);
return val;
}
public virtual int Dec_ndr_short()
{
Align(2);
int val = Encdec.Dec_uint16le(Buf, Index);
Advance(2);
return val;
}
public virtual void Enc_ndr_long(int l)
{
Align(4);
Encdec.Enc_uint32le(l, Buf, Index);
Advance(4);
}
public virtual void Enc_ndr_long(int l)
{
Align(4);
Encdec.Enc_uint32le(l, Buf, Index);
Advance(4);
}
public virtual int Dec_ndr_long()
{
Align(4);
int val = Encdec.Dec_uint32le(Buf, Index);
Advance(4);
return val;
}
public virtual int Dec_ndr_long()
{
Align(4);
int val = Encdec.Dec_uint32le(Buf, Index);
Advance(4);
return val;
}
public virtual void Enc_ndr_hyper(long h)
{
Align(8);
Encdec.Enc_uint64le(h, Buf, Index);
Advance(8);
}
public virtual void Enc_ndr_hyper(long h)
{
Align(8);
Encdec.Enc_uint64le(h, Buf, Index);
Advance(8);
}
public virtual long Dec_ndr_hyper()
{
Align(8);
long val = Encdec.Dec_uint64le(Buf, Index);
Advance(8);
return val;
}
public virtual long Dec_ndr_hyper()
{
Align(8);
long val = Encdec.Dec_uint64le(Buf, Index);
Advance(8);
return val;
}
public virtual void Enc_ndr_string(string s)
{
Align(4);
int i = Index;
int len = s.Length;
Encdec.Enc_uint32le(len + 1, Buf, i);
i += 4;
Encdec.Enc_uint32le(0, Buf, i);
i += 4;
Encdec.Enc_uint32le(len + 1, Buf, i);
i += 4;
try
{
Array.Copy(Runtime.GetBytesForString(s, "UTF-16LE"), 0, Buf, i, len * 2);
}
catch (UnsupportedEncodingException)
{
}
i += len * 2;
Buf[i++] = unchecked((byte)('\0'));
Buf[i++] = unchecked((byte)('\0'));
Advance(i - Index);
}
public virtual void Enc_ndr_string(string s)
{
Align(4);
int i = Index;
int len = s.Length;
Encdec.Enc_uint32le(len + 1, Buf, i);
i += 4;
Encdec.Enc_uint32le(0, Buf, i);
i += 4;
Encdec.Enc_uint32le(len + 1, Buf, i);
i += 4;
try
{
Array.Copy(Runtime.GetBytesForString(s, "UTF-16LE"), 0, Buf, i, len
* 2);
}
catch (UnsupportedEncodingException)
{
}
i += len * 2;
Buf[i++] = unchecked((byte)('\0'));
Buf[i++] = unchecked((byte)('\0'));
Advance(i - Index);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public virtual string Dec_ndr_string()
{
Align(4);
int i = Index;
string val = null;
int len = Encdec.Dec_uint32le(Buf, i);
i += 12;
if (len != 0)
{
len--;
int size = len * 2;
try
{
if (size < 0 || size > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
val = Runtime.GetStringForBytes(Buf, i, size, "UTF-16LE");
i += size + 2;
}
catch (UnsupportedEncodingException)
{
}
}
Advance(i - Index);
return val;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public virtual string Dec_ndr_string()
{
Align(4);
int i = Index;
string val = null;
int len = Encdec.Dec_uint32le(Buf, i);
i += 12;
if (len != 0)
{
len--;
int size = len * 2;
try
{
if (size < 0 || size > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
val = Runtime.GetStringForBytes(Buf, i, size, "UTF-16LE");
i += size + 2;
}
catch (UnsupportedEncodingException)
{
}
}
Advance(i - Index);
return val;
}
private int GetDceReferent(object obj)
{
Entry e;
if (Referents == null)
{
Referents = new Hashtable();
Referent = 1;
}
if ((e = (Entry)Referents.Get(obj)) == null)
{
e = new Entry();
e.Referent = Referent++;
e.Obj = obj;
Referents.Put(obj, e);
}
return e.Referent;
}
private int GetDceReferent(object obj)
{
Entry e;
if (Referents == null)
{
Referents = new Hashtable();
Referent = 1;
}
if ((e = (Entry)Referents.Get(obj)) == null)
{
e = new Entry();
e.Referent = Referent++;
e.Obj = obj;
Referents.Put(obj, e);
}
return e.Referent;
}
public virtual void Enc_ndr_referent(object obj, int type)
{
if (obj == null)
{
Enc_ndr_long(0);
return;
}
switch (type)
{
case 1:
case 3:
{
Enc_ndr_long(Runtime.IdentityHashCode(obj));
return;
}
public virtual void Enc_ndr_referent(object obj, int type)
{
if (obj == null)
{
Enc_ndr_long(0);
return;
}
switch (type)
{
case 1:
case 3:
{
Enc_ndr_long(Runtime.IdentityHashCode(obj));
return;
}
case 2:
{
Enc_ndr_long(GetDceReferent(obj));
return;
}
}
}
case 2:
{
Enc_ndr_long(GetDceReferent(obj));
return;
}
}
}
public override string ToString()
{
return "start=" + Start + ",index=" + Index + ",length=" + GetLength();
}
}
public override string ToString()
{
return "start=" + Start + ",index=" + Index + ",length=" + GetLength();
}
}
}

View File

@ -18,15 +18,15 @@ using System.IO;
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrException : IOException
{
public static readonly string NoNullRef = "ref pointer cannot be null";
public class NdrException : IOException
{
public static readonly string NoNullRef = "ref pointer cannot be null";
public static readonly string InvalidConformance = "invalid array conformance";
public static readonly string InvalidConformance = "invalid array conformance";
public NdrException(string msg) : base(msg)
{
}
}
public NdrException(string msg) : base(msg)
{
}
}
}

View File

@ -16,25 +16,25 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrHyper : NdrObject
{
public long Value;
public class NdrHyper : NdrObject
{
public long Value;
public NdrHyper(long value)
{
this.Value = value;
}
public NdrHyper(long value)
{
this.Value = value;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_hyper(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_hyper(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_hyper();
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_hyper();
}
}
}

View File

@ -16,25 +16,25 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrLong : NdrObject
{
public int Value;
public class NdrLong : NdrObject
{
public int Value;
public NdrLong(int value)
{
this.Value = value;
}
public NdrLong(int value)
{
this.Value = value;
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_long(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_long(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_long();
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_long();
}
}
}

View File

@ -16,12 +16,12 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Ndr
{
public abstract class NdrObject
{
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Encode(NdrBuffer dst);
public abstract class NdrObject
{
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Encode(NdrBuffer dst);
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Decode(NdrBuffer src);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public abstract void Decode(NdrBuffer src);
}
}

View File

@ -16,25 +16,25 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrShort : NdrObject
{
public int Value;
public class NdrShort : NdrObject
{
public int Value;
public NdrShort(int value)
{
this.Value = value & unchecked(0xFF);
}
public NdrShort(int value)
{
this.Value = value & unchecked(0xFF);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_short(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_short(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_short();
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_short();
}
}
}

View File

@ -16,25 +16,25 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc.Ndr
{
public class NdrSmall : NdrObject
{
public int Value;
public class NdrSmall : NdrObject
{
public int Value;
public NdrSmall(int value)
{
this.Value = value & unchecked(0xFF);
}
public NdrSmall(int value)
{
this.Value = value & unchecked(0xFF);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_small(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Enc_ndr_small(Value);
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_small();
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
Value = src.Dec_ndr_small();
}
}
}

View File

@ -18,268 +18,268 @@ using SharpCifs.Dcerpc.Ndr;
namespace SharpCifs.Dcerpc
{
public class Rpc
{
public class UuidT : NdrObject
{
public int TimeLow;
public class Rpc
{
public class UuidT : NdrObject
{
public int TimeLow;
public short TimeMid;
public short TimeMid;
public short TimeHiAndVersion;
public short TimeHiAndVersion;
public byte ClockSeqHiAndReserved;
public byte ClockSeqHiAndReserved;
public byte ClockSeqLow;
public byte ClockSeqLow;
public byte[] Node;
public byte[] Node;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(TimeLow);
dst.Enc_ndr_short(TimeMid);
dst.Enc_ndr_short(TimeHiAndVersion);
dst.Enc_ndr_small(ClockSeqHiAndReserved);
dst.Enc_ndr_small(ClockSeqLow);
int nodes = 6;
int nodei = dst.Index;
dst.Advance(1 * nodes);
dst = dst.Derive(nodei);
for (int i = 0; i < nodes; i++)
{
dst.Enc_ndr_small(Node[i]);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(TimeLow);
dst.Enc_ndr_short(TimeMid);
dst.Enc_ndr_short(TimeHiAndVersion);
dst.Enc_ndr_small(ClockSeqHiAndReserved);
dst.Enc_ndr_small(ClockSeqLow);
int nodes = 6;
int nodei = dst.Index;
dst.Advance(1 * nodes);
dst = dst.Derive(nodei);
for (int i = 0; i < nodes; i++)
{
dst.Enc_ndr_small(Node[i]);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
TimeLow = src.Dec_ndr_long();
TimeMid = (short)src.Dec_ndr_short();
TimeHiAndVersion = (short)src.Dec_ndr_short();
ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small());
ClockSeqLow = unchecked((byte)src.Dec_ndr_small());
int nodes = 6;
int nodei = src.Index;
src.Advance(1 * nodes);
if (Node == null)
{
if (nodes < 0 || nodes > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Node = new byte[nodes];
}
src = src.Derive(nodei);
for (int i = 0; i < nodes; i++)
{
Node[i] = unchecked((byte)src.Dec_ndr_small());
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
TimeLow = src.Dec_ndr_long();
TimeMid = (short)src.Dec_ndr_short();
TimeHiAndVersion = (short)src.Dec_ndr_short();
ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small());
ClockSeqLow = unchecked((byte)src.Dec_ndr_small());
int nodes = 6;
int nodei = src.Index;
src.Advance(1 * nodes);
if (Node == null)
{
if (nodes < 0 || nodes > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Node = new byte[nodes];
}
src = src.Derive(nodei);
for (int i = 0; i < nodes; i++)
{
Node[i] = unchecked((byte)src.Dec_ndr_small());
}
}
}
public class PolicyHandle : NdrObject
{
public int Type;
public class PolicyHandle : NdrObject
{
public int Type;
public UuidT Uuid;
public UuidT Uuid;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Type);
dst.Enc_ndr_long(Uuid.TimeLow);
dst.Enc_ndr_short(Uuid.TimeMid);
dst.Enc_ndr_short(Uuid.TimeHiAndVersion);
dst.Enc_ndr_small(Uuid.ClockSeqHiAndReserved);
dst.Enc_ndr_small(Uuid.ClockSeqLow);
int uuidNodes = 6;
int uuidNodei = dst.Index;
dst.Advance(1 * uuidNodes);
dst = dst.Derive(uuidNodei);
for (int i = 0; i < uuidNodes; i++)
{
dst.Enc_ndr_small(Uuid.Node[i]);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_long(Type);
dst.Enc_ndr_long(Uuid.TimeLow);
dst.Enc_ndr_short(Uuid.TimeMid);
dst.Enc_ndr_short(Uuid.TimeHiAndVersion);
dst.Enc_ndr_small(Uuid.ClockSeqHiAndReserved);
dst.Enc_ndr_small(Uuid.ClockSeqLow);
int uuidNodes = 6;
int uuidNodei = dst.Index;
dst.Advance(1 * uuidNodes);
dst = dst.Derive(uuidNodei);
for (int i = 0; i < uuidNodes; i++)
{
dst.Enc_ndr_small(Uuid.Node[i]);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Type = src.Dec_ndr_long();
src.Align(4);
if (Uuid == null)
{
Uuid = new UuidT();
}
Uuid.TimeLow = src.Dec_ndr_long();
Uuid.TimeMid = (short)src.Dec_ndr_short();
Uuid.TimeHiAndVersion = (short)src.Dec_ndr_short();
Uuid.ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small());
Uuid.ClockSeqLow = unchecked((byte)src.Dec_ndr_small());
int uuidNodes = 6;
int uuidNodei = src.Index;
src.Advance(1 * uuidNodes);
if (Uuid.Node == null)
{
if (uuidNodes < 0 || uuidNodes > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Uuid.Node = new byte[uuidNodes];
}
src = src.Derive(uuidNodei);
for (int i = 0; i < uuidNodes; i++)
{
Uuid.Node[i] = unchecked((byte)src.Dec_ndr_small());
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Type = src.Dec_ndr_long();
src.Align(4);
if (Uuid == null)
{
Uuid = new UuidT();
}
Uuid.TimeLow = src.Dec_ndr_long();
Uuid.TimeMid = (short)src.Dec_ndr_short();
Uuid.TimeHiAndVersion = (short)src.Dec_ndr_short();
Uuid.ClockSeqHiAndReserved = unchecked((byte)src.Dec_ndr_small());
Uuid.ClockSeqLow = unchecked((byte)src.Dec_ndr_small());
int uuidNodes = 6;
int uuidNodei = src.Index;
src.Advance(1 * uuidNodes);
if (Uuid.Node == null)
{
if (uuidNodes < 0 || uuidNodes > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Uuid.Node = new byte[uuidNodes];
}
src = src.Derive(uuidNodei);
for (int i = 0; i < uuidNodes; i++)
{
Uuid.Node[i] = unchecked((byte)src.Dec_ndr_small());
}
}
}
public class Unicode_string : NdrObject
{
public short Length;
public class Unicode_string : NdrObject
{
public short Length;
public short MaximumLength;
public short MaximumLength;
public short[] Buffer;
public short[] Buffer;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_short(Length);
dst.Enc_ndr_short(MaximumLength);
dst.Enc_ndr_referent(Buffer, 1);
if (Buffer != null)
{
dst = dst.Deferred;
int bufferl = Length / 2;
int buffers = MaximumLength / 2;
dst.Enc_ndr_long(buffers);
dst.Enc_ndr_long(0);
dst.Enc_ndr_long(bufferl);
int bufferi = dst.Index;
dst.Advance(2 * bufferl);
dst = dst.Derive(bufferi);
for (int i = 0; i < bufferl; i++)
{
dst.Enc_ndr_short(Buffer[i]);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
dst.Enc_ndr_short(Length);
dst.Enc_ndr_short(MaximumLength);
dst.Enc_ndr_referent(Buffer, 1);
if (Buffer != null)
{
dst = dst.Deferred;
int bufferl = Length / 2;
int buffers = MaximumLength / 2;
dst.Enc_ndr_long(buffers);
dst.Enc_ndr_long(0);
dst.Enc_ndr_long(bufferl);
int bufferi = dst.Index;
dst.Advance(2 * bufferl);
dst = dst.Derive(bufferi);
for (int i = 0; i < bufferl; i++)
{
dst.Enc_ndr_short(Buffer[i]);
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Length = (short)src.Dec_ndr_short();
MaximumLength = (short)src.Dec_ndr_short();
int bufferp = src.Dec_ndr_long();
if (bufferp != 0)
{
src = src.Deferred;
int buffers = src.Dec_ndr_long();
src.Dec_ndr_long();
int bufferl = src.Dec_ndr_long();
int bufferi = src.Index;
src.Advance(2 * bufferl);
if (Buffer == null)
{
if (buffers < 0 || buffers > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Buffer = new short[buffers];
}
src = src.Derive(bufferi);
for (int i = 0; i < bufferl; i++)
{
Buffer[i] = (short)src.Dec_ndr_short();
}
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
Length = (short)src.Dec_ndr_short();
MaximumLength = (short)src.Dec_ndr_short();
int bufferp = src.Dec_ndr_long();
if (bufferp != 0)
{
src = src.Deferred;
int buffers = src.Dec_ndr_long();
src.Dec_ndr_long();
int bufferl = src.Dec_ndr_long();
int bufferi = src.Index;
src.Advance(2 * bufferl);
if (Buffer == null)
{
if (buffers < 0 || buffers > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
Buffer = new short[buffers];
}
src = src.Derive(bufferi);
for (int i = 0; i < bufferl; i++)
{
Buffer[i] = (short)src.Dec_ndr_short();
}
}
}
}
public class SidT : NdrObject
{
public byte Revision;
public class SidT : NdrObject
{
public byte Revision;
public byte SubAuthorityCount;
public byte SubAuthorityCount;
public byte[] IdentifierAuthority;
public byte[] IdentifierAuthority;
public int[] SubAuthority;
public int[] SubAuthority;
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
int subAuthoritys = SubAuthorityCount;
dst.Enc_ndr_long(subAuthoritys);
dst.Enc_ndr_small(Revision);
dst.Enc_ndr_small(SubAuthorityCount);
int identifierAuthoritys = 6;
int identifierAuthorityi = dst.Index;
dst.Advance(1 * identifierAuthoritys);
int subAuthorityi = dst.Index;
dst.Advance(4 * subAuthoritys);
dst = dst.Derive(identifierAuthorityi);
for (int i = 0; i < identifierAuthoritys; i++)
{
dst.Enc_ndr_small(IdentifierAuthority[i]);
}
dst = dst.Derive(subAuthorityi);
for (int i1 = 0; i1 < subAuthoritys; i1++)
{
dst.Enc_ndr_long(SubAuthority[i1]);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Encode(NdrBuffer dst)
{
dst.Align(4);
int subAuthoritys = SubAuthorityCount;
dst.Enc_ndr_long(subAuthoritys);
dst.Enc_ndr_small(Revision);
dst.Enc_ndr_small(SubAuthorityCount);
int identifierAuthoritys = 6;
int identifierAuthorityi = dst.Index;
dst.Advance(1 * identifierAuthoritys);
int subAuthorityi = dst.Index;
dst.Advance(4 * subAuthoritys);
dst = dst.Derive(identifierAuthorityi);
for (int i = 0; i < identifierAuthoritys; i++)
{
dst.Enc_ndr_small(IdentifierAuthority[i]);
}
dst = dst.Derive(subAuthorityi);
for (int i1 = 0; i1 < subAuthoritys; i1++)
{
dst.Enc_ndr_long(SubAuthority[i1]);
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
int subAuthoritys = src.Dec_ndr_long();
Revision = unchecked((byte)src.Dec_ndr_small());
SubAuthorityCount = unchecked((byte)src.Dec_ndr_small());
int identifierAuthoritys = 6;
int identifierAuthorityi = src.Index;
src.Advance(1 * identifierAuthoritys);
int subAuthorityi = src.Index;
src.Advance(4 * subAuthoritys);
if (IdentifierAuthority == null)
{
if (identifierAuthoritys < 0 || identifierAuthoritys > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
IdentifierAuthority = new byte[identifierAuthoritys];
}
src = src.Derive(identifierAuthorityi);
for (int i = 0; i < identifierAuthoritys; i++)
{
IdentifierAuthority[i] = unchecked((byte)src.Dec_ndr_small());
}
if (SubAuthority == null)
{
if (subAuthoritys < 0 || subAuthoritys > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
SubAuthority = new int[subAuthoritys];
}
src = src.Derive(subAuthorityi);
for (int i1 = 0; i1 < subAuthoritys; i1++)
{
SubAuthority[i1] = src.Dec_ndr_long();
}
}
}
}
/// <exception cref="SharpCifs.Dcerpc.Ndr.NdrException"></exception>
public override void Decode(NdrBuffer src)
{
src.Align(4);
int subAuthoritys = src.Dec_ndr_long();
Revision = unchecked((byte)src.Dec_ndr_small());
SubAuthorityCount = unchecked((byte)src.Dec_ndr_small());
int identifierAuthoritys = 6;
int identifierAuthorityi = src.Index;
src.Advance(1 * identifierAuthoritys);
int subAuthorityi = src.Index;
src.Advance(4 * subAuthoritys);
if (IdentifierAuthority == null)
{
if (identifierAuthoritys < 0 || identifierAuthoritys > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
IdentifierAuthority = new byte[identifierAuthoritys];
}
src = src.Derive(identifierAuthorityi);
for (int i = 0; i < identifierAuthoritys; i++)
{
IdentifierAuthority[i] = unchecked((byte)src.Dec_ndr_small());
}
if (SubAuthority == null)
{
if (subAuthoritys < 0 || subAuthoritys > unchecked(0xFFFF))
{
throw new NdrException(NdrException.InvalidConformance);
}
SubAuthority = new int[subAuthoritys];
}
src = src.Derive(subAuthorityi);
for (int i1 = 0; i1 < subAuthoritys; i1++)
{
SubAuthority[i1] = src.Dec_ndr_long();
}
}
}
}
}

View File

@ -18,141 +18,131 @@ using System;
namespace SharpCifs.Dcerpc
{
public class Uuid : Rpc.UuidT
{
public static int Hex_to_bin(char[] arr, int offset, int length)
{
int value = 0;
int ai;
int count;
count = 0;
for (ai = offset; ai < arr.Length && count < length; ai++)
{
value <<= 4;
switch (arr[ai])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
value += arr[ai] - '0';
break;
}
public class Uuid : Rpc.UuidT
{
public static int Hex_to_bin(char[] arr, int offset, int length)
{
int value = 0;
int ai;
int count;
count = 0;
for (ai = offset; ai < arr.Length && count < length; ai++)
{
value <<= 4;
switch (arr[ai])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
value += arr[ai] - '0';
break;
}
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
{
value += 10 + (arr[ai] - 'A');
break;
}
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
{
value += 10 + (arr[ai] - 'A');
break;
}
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
{
value += 10 + (arr[ai] - 'a');
break;
}
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
{
value += 10 + (arr[ai] - 'a');
break;
}
default:
{
throw new ArgumentException(new string(arr, offset, length));
}
}
count++;
}
return value;
}
default:
{
throw new ArgumentException(new string(arr, offset, length));
}
}
count++;
}
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)
{
char[] arr = new char[length];
int ai = arr.Length;
while (ai-- > 0)
{
arr[ai] = Hexchars[value & unchecked(0xF)];
value = (int)(((uint)value) >> 4);
}
return new string(arr);
}
public static string Bin_to_hex(int value, int length)
{
char[] arr = new char[length];
int ai = arr.Length;
while (ai-- > 0)
{
arr[ai] = Hexchars[value & unchecked(0xF)];
value = (int)(((uint)value) >> 4);
}
return new string(arr);
}
private static byte B(int i)
{
return unchecked((byte)(i & unchecked(0xFF)));
}
private static byte B(int i)
{
return unchecked((byte)(i & unchecked(0xFF)));
}
private static short S(int i)
{
return (short)(i & unchecked(0xFFFF));
}
private static short S(int i)
{
return (short)(i & unchecked(0xFFFF));
}
public Uuid(Rpc.UuidT uuid)
{
TimeLow = uuid.TimeLow;
TimeMid = uuid.TimeMid;
TimeHiAndVersion = uuid.TimeHiAndVersion;
ClockSeqHiAndReserved = uuid.ClockSeqHiAndReserved;
ClockSeqLow = uuid.ClockSeqLow;
Node = new byte[6];
Node[0] = uuid.Node[0];
Node[1] = uuid.Node[1];
Node[2] = uuid.Node[2];
Node[3] = uuid.Node[3];
Node[4] = uuid.Node[4];
Node[5] = uuid.Node[5];
}
public Uuid(Rpc.UuidT uuid)
{
TimeLow = uuid.TimeLow;
TimeMid = uuid.TimeMid;
TimeHiAndVersion = uuid.TimeHiAndVersion;
ClockSeqHiAndReserved = uuid.ClockSeqHiAndReserved;
ClockSeqLow = uuid.ClockSeqLow;
Node = new byte[6];
Node[0] = uuid.Node[0];
Node[1] = uuid.Node[1];
Node[2] = uuid.Node[2];
Node[3] = uuid.Node[3];
Node[4] = uuid.Node[4];
Node[5] = uuid.Node[5];
}
public Uuid(string str)
{
char[] arr = str.ToCharArray();
TimeLow = Hex_to_bin(arr, 0, 8);
TimeMid = S(Hex_to_bin(arr, 9, 4));
TimeHiAndVersion = S(Hex_to_bin(arr, 14, 4));
ClockSeqHiAndReserved = B(Hex_to_bin(arr, 19, 2));
ClockSeqLow = B(Hex_to_bin(arr, 21, 2));
Node = new byte[6];
Node[0] = B(Hex_to_bin(arr, 24, 2));
Node[1] = B(Hex_to_bin(arr, 26, 2));
Node[2] = B(Hex_to_bin(arr, 28, 2));
Node[3] = B(Hex_to_bin(arr, 30, 2));
Node[4] = B(Hex_to_bin(arr, 32, 2));
Node[5] = B(Hex_to_bin(arr, 34, 2));
}
public Uuid(string str)
{
char[] arr = str.ToCharArray();
TimeLow = Hex_to_bin(arr, 0, 8);
TimeMid = S(Hex_to_bin(arr, 9, 4));
TimeHiAndVersion = S(Hex_to_bin(arr, 14, 4));
ClockSeqHiAndReserved = B(Hex_to_bin(arr, 19, 2));
ClockSeqLow = B(Hex_to_bin(arr, 21, 2));
Node = new byte[6];
Node[0] = B(Hex_to_bin(arr, 24, 2));
Node[1] = B(Hex_to_bin(arr, 26, 2));
Node[2] = B(Hex_to_bin(arr, 28, 2));
Node[3] = B(Hex_to_bin(arr, 30, 2));
Node[4] = B(Hex_to_bin(arr, 32, 2));
Node[5] = B(Hex_to_bin(arr, 34, 2));
}
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);
}
}
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);
}
}
}

View File

@ -16,50 +16,50 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc
{
public class UnicodeString : Rpc.Unicode_string
{
internal bool Zterm;
public class UnicodeString : Rpc.Unicode_string
{
internal bool Zterm;
public UnicodeString(bool zterm)
{
this.Zterm = zterm;
}
public UnicodeString(bool zterm)
{
this.Zterm = zterm;
}
public UnicodeString(Rpc.Unicode_string rus, bool zterm)
{
Length = rus.Length;
MaximumLength = rus.MaximumLength;
Buffer = rus.Buffer;
this.Zterm = zterm;
}
public UnicodeString(Rpc.Unicode_string rus, bool zterm)
{
Length = rus.Length;
MaximumLength = rus.MaximumLength;
Buffer = rus.Buffer;
this.Zterm = zterm;
}
public UnicodeString(string str, bool zterm)
{
this.Zterm = zterm;
int len = str.Length;
int zt = zterm ? 1 : 0;
Length = MaximumLength = (short)((len + zt) * 2);
Buffer = new short[len + zt];
int i;
for (i = 0; i < len; i++)
{
Buffer[i] = (short)str[i];
}
if (zterm)
{
Buffer[i] = 0;
}
}
public UnicodeString(string str, bool zterm)
{
this.Zterm = zterm;
int len = str.Length;
int zt = zterm ? 1 : 0;
Length = MaximumLength = (short)((len + zt) * 2);
Buffer = new short[len + zt];
int i;
for (i = 0; i < len; i++)
{
Buffer[i] = (short)str[i];
}
if (zterm)
{
Buffer[i] = 0;
}
}
public override string ToString()
{
int len = Length / 2 - (Zterm ? 1 : 0);
char[] ca = new char[len];
for (int i = 0; i < len; i++)
{
ca[i] = (char)Buffer[i];
}
return new string(ca, 0, len);
}
}
public override string ToString()
{
int len = Length / 2 - (Zterm ? 1 : 0);
char[] ca = new char[len];
for (int i = 0; i < len; i++)
{
ca[i] = (char)Buffer[i];
}
return new string(ca, 0, len);
}
}
}

View File

@ -21,181 +21,182 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
public class Lmhosts
{
private static readonly string Filename = Config.GetProperty("jcifs.netbios.lmhosts");
public class Lmhosts
{
private static readonly string Filename = Config.GetProperty("jcifs.netbios.lmhosts"
);
private static readonly Hashtable Tab = new Hashtable();
private static readonly Hashtable Tab = new Hashtable();
private static long _lastModified = 1L;
private static long _lastModified = 1L;
private static int _alt;
private static int _alt;
private static LogStream _log = LogStream.GetInstance();
private static LogStream _log = LogStream.GetInstance();
/// <summary>
/// This is really just for
/// <see cref="SharpCifs.UniAddress">Jcifs.UniAddress</see>
/// . It does
/// not throw an
/// <see cref="UnknownHostException">Sharpen.UnknownHostException</see>
/// because this
/// is queried frequently and exceptions would be rather costly to
/// throw on a regular basis here.
/// </summary>
public static NbtAddress GetByName(string host)
{
lock (typeof(Lmhosts))
{
return GetByName(new Name(host, 0x20, null));
}
}
/// <summary>
/// This is really just for
/// <see cref="SharpCifs.UniAddress">Jcifs.UniAddress</see>
/// . It does
/// not throw an
/// <see cref="UnknownHostException">Sharpen.UnknownHostException</see>
/// because this
/// is queried frequently and exceptions would be rather costly to
/// throw on a regular basis here.
/// </summary>
public static NbtAddress GetByName(string host)
{
lock (typeof(Lmhosts))
{
return GetByName(new Name(host, 0x20, null));
}
}
internal static NbtAddress GetByName(Name name)
{
lock (typeof(Lmhosts))
{
NbtAddress result = null;
try
{
if (Filename != null)
{
FilePath f = new FilePath(Filename);
long lm;
if ((lm = f.LastModified()) > _lastModified)
{
_lastModified = lm;
Tab.Clear();
_alt = 0;
//path -> fileStream
//Populate(new FileReader(f));
internal static NbtAddress GetByName(Name name)
{
lock (typeof(Lmhosts))
{
NbtAddress result = null;
try
{
if (Filename != null)
{
FilePath f = new FilePath(Filename);
long lm;
if ((lm = f.LastModified()) > _lastModified)
{
_lastModified = lm;
Tab.Clear();
_alt = 0;
//path -> fileStream
//Populate(new FileReader(f));
Populate(new FileReader(new FileStream(f, FileMode.Open)));
}
result = (NbtAddress)Tab[name];
}
}
catch (FileNotFoundException fnfe)
{
if (_log.Level > 1)
{
_log.WriteLine("lmhosts file: " + Filename);
Runtime.PrintStackTrace(fnfe, _log);
}
}
catch (IOException ioe)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(ioe, _log);
}
}
return result;
}
}
}
result = (NbtAddress)Tab[name];
}
}
catch (FileNotFoundException fnfe)
{
if (_log.Level > 1)
{
_log.WriteLine("lmhosts file: " + Filename);
Runtime.PrintStackTrace(fnfe, _log);
}
}
catch (IOException ioe)
{
if (_log.Level > 0)
{
Runtime.PrintStackTrace(ioe, _log);
}
}
return result;
}
}
/// <exception cref="System.IO.IOException"></exception>
internal static void Populate(StreamReader r)
{
string line;
/// <exception cref="System.IO.IOException"></exception>
internal static void Populate(StreamReader r)
{
string line;
BufferedReader br = new BufferedReader((InputStreamReader)r);
while ((line = br.ReadLine()) != null)
{
line = line.ToUpper().Trim();
if (line.Length == 0)
{
}
else
{
if (line[0] == '#')
{
if (line.StartsWith("#INCLUDE "))
{
line = Runtime.Substring(line, line.IndexOf('\\'));
string url = "smb:" + line.Replace('\\', '/');
if (_alt > 0)
{
try
{
Populate(new InputStreamReader(new SmbFileInputStream(url)));
}
catch (IOException ioe)
{
_log.WriteLine("lmhosts URL: " + url);
Runtime.PrintStackTrace(ioe, _log);
continue;
}
_alt--;
while ((line = br.ReadLine()) != null)
{
line = line.ToUpper().Trim();
if (line.StartsWith("#END_ALTERNATE"))
{
break;
}
}
}
else
{
Populate(new InputStreamReader(new SmbFileInputStream(url)));
}
}
else
{
if (line.StartsWith("#BEGIN_ALTERNATE"))
{
_alt++;
}
else
{
if (line.StartsWith("#END_ALTERNATE") && _alt > 0)
{
_alt--;
throw new IOException("no lmhosts alternate includes loaded");
}
}
}
}
else
{
if (char.IsDigit(line[0]))
{
char[] data = line.ToCharArray();
int ip;
int i;
int j;
Name name;
NbtAddress addr;
char c;
c = '.';
ip = i = 0;
for (; i < data.Length && c == '.'; i++)
{
int b = unchecked(0x00);
for (; i < data.Length && (c = data[i]) >= 48 && c <= 57; i++)
{
b = b * 10 + c - '0';
}
ip = (ip << 8) + b;
}
while (i < data.Length && char.IsWhiteSpace(data[i]))
{
i++;
}
j = i;
while (j < data.Length && char.IsWhiteSpace(data[j]) == false)
{
j++;
}
name = new Name(Runtime.Substring(line, i, j), unchecked(0x20), null
);
addr = new NbtAddress(name, ip, false, NbtAddress.BNode, false, false, true, true
, NbtAddress.UnknownMacAddress);
Tab.Put(name, addr);
}
}
}
}
}
}
while ((line = br.ReadLine()) != null)
{
line = line.ToUpper().Trim();
if (line.Length == 0)
{
}
else
{
if (line[0] == '#')
{
if (line.StartsWith("#INCLUDE "))
{
line = Runtime.Substring(line, line.IndexOf('\\'));
string url = "smb:" + line.Replace('\\', '/');
if (_alt > 0)
{
try
{
Populate(new InputStreamReader(new SmbFileInputStream(url)));
}
catch (IOException ioe)
{
_log.WriteLine("lmhosts URL: " + url);
Runtime.PrintStackTrace(ioe, _log);
continue;
}
_alt--;
while ((line = br.ReadLine()) != null)
{
line = line.ToUpper().Trim();
if (line.StartsWith("#END_ALTERNATE"))
{
break;
}
}
}
else
{
Populate(new InputStreamReader(new SmbFileInputStream(url)));
}
}
else
{
if (line.StartsWith("#BEGIN_ALTERNATE"))
{
_alt++;
}
else
{
if (line.StartsWith("#END_ALTERNATE") && _alt > 0)
{
_alt--;
throw new IOException("no lmhosts alternate includes loaded");
}
}
}
}
else
{
if (char.IsDigit(line[0]))
{
char[] data = line.ToCharArray();
int ip;
int i;
int j;
Name name;
NbtAddress addr;
char c;
c = '.';
ip = i = 0;
for (; i < data.Length && c == '.'; i++)
{
int b = unchecked(0x00);
for (; i < data.Length && (c = data[i]) >= 48 && c <= 57; i++)
{
b = b * 10 + c - '0';
}
ip = (ip << 8) + b;
}
while (i < data.Length && char.IsWhiteSpace(data[i]))
{
i++;
}
j = i;
while (j < data.Length && char.IsWhiteSpace(data[j]) == false)
{
j++;
}
name = new Name(Runtime.Substring(line, i, j), unchecked(0x20), null
);
addr = new NbtAddress(name, ip, false, NbtAddress.BNode, false, false, true, true
, NbtAddress.UnknownMacAddress);
Tab.Put(name, addr);
}
}
}
}
}
}
}

View File

@ -21,110 +21,102 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
public class Name
{
private const int TypeOffset = 31;
public class Name
{
private const int TypeOffset = 31;
private const int ScopeOffset = 33;
private const int ScopeOffset = 33;
private static readonly string DefaultScope
= Config.GetProperty("jcifs.netbios.scope");
private static readonly string DefaultScope = Config.GetProperty("jcifs.netbios.scope"
);
internal static readonly string OemEncoding
= Config.GetProperty("jcifs.encoding", Runtime.GetProperty("file.encoding"));
internal static readonly string OemEncoding = Config.GetProperty("jcifs.encoding"
, Runtime.GetProperty("file.encoding"));
public string name;
public string name;
public string Scope;
public string Scope;
public int HexCode;
public int HexCode;
internal int SrcHashCode;
internal int SrcHashCode;
public Name()
{
}
public Name()
{
}
public Name(string name, int hexCode, string scope)
{
if (name.Length > 15)
{
name = Runtime.Substring(name, 0, 15);
}
this.name = name.ToUpper();
this.HexCode = hexCode;
this.Scope = !string.IsNullOrEmpty(scope) ? scope : DefaultScope;
SrcHashCode = 0;
}
public Name(string name, int hexCode, string scope)
{
if (name.Length > 15)
{
name = Runtime.Substring(name, 0, 15);
}
this.name = name.ToUpper();
this.HexCode = hexCode;
this.Scope = !string.IsNullOrEmpty(scope) ? scope : DefaultScope;
SrcHashCode = 0;
}
internal virtual int WriteWireFormat(byte[] dst, int dstIndex)
{
// write 0x20 in first byte
dst[dstIndex] = unchecked(0x20);
// write name
try
{
byte[] tmp = Runtime.GetBytesForString(name, OemEncoding
);
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)));
}
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)));
}
catch (UnsupportedEncodingException)
{
}
return ScopeOffset + WriteScopeWireFormat(dst, dstIndex + ScopeOffset);
}
internal virtual int WriteWireFormat(byte[] dst, int dstIndex)
{
// write 0x20 in first byte
dst[dstIndex] = unchecked(0x20);
// write name
try
{
byte[] tmp = Runtime.GetBytesForString(name, OemEncoding
);
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)));
}
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)));
}
catch (UnsupportedEncodingException)
{
}
return ScopeOffset + WriteScopeWireFormat(dst, dstIndex + ScopeOffset);
}
internal virtual int ReadWireFormat(byte[] src, int srcIndex)
{
byte[] tmp = new byte[ScopeOffset];
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)
)
);
if (tmp[i] != unchecked((byte)' '))
{
length = i + 1;
}
}
try
{
name = Runtime.GetStringForBytes(tmp, 0, length, OemEncoding
);
}
catch (UnsupportedEncodingException)
{
}
HexCode = ((src[srcIndex + TypeOffset] & unchecked(0xFF)) - unchecked(0x41)) << 4;
HexCode |= ((src[srcIndex + TypeOffset + 1] & unchecked(0xFF)) - unchecked(0x41))
& unchecked(0x0F);
return ScopeOffset + ReadScopeWireFormat(src, srcIndex + ScopeOffset);
}
internal virtual int ReadWireFormat(byte[] src, int srcIndex)
{
byte[] tmp = new byte[ScopeOffset];
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)));
if (tmp[i] != unchecked((byte)' '))
{
length = i + 1;
}
}
try
{
name = Runtime.GetStringForBytes(tmp, 0, length, OemEncoding
);
}
catch (UnsupportedEncodingException)
{
}
HexCode = ((src[srcIndex + TypeOffset] & unchecked(0xFF)) - unchecked(0x41)) << 4;
HexCode |= ((src[srcIndex + TypeOffset + 1] & unchecked(0xFF)) - unchecked(
0x41)) & unchecked(0x0F);
return ScopeOffset + ReadScopeWireFormat(src, srcIndex + ScopeOffset);
}
internal int ReadWireFormatDos(byte[] src, int srcIndex)
{
@ -138,8 +130,9 @@ namespace SharpCifs.Netbios
{
name = Runtime.GetStringForBytes(tmp, 0, length).Trim();
}
catch (Exception)
catch (Exception ex)
{
}
HexCode = src[srcIndex + length];
@ -148,129 +141,129 @@ namespace SharpCifs.Netbios
}
internal virtual int WriteScopeWireFormat(byte[] dst, int dstIndex)
{
if (Scope == null)
{
dst[dstIndex] = unchecked(unchecked(0x00));
return 1;
}
// copy new scope in
dst[dstIndex++] = unchecked((byte)('.'));
try
{
Array.Copy(Runtime.GetBytesForString(Scope, OemEncoding),
0, dst, dstIndex, Scope.Length);
}
catch (UnsupportedEncodingException)
{
}
dstIndex += Scope.Length;
dst[dstIndex++] = unchecked(unchecked(0x00));
// now go over scope backwards converting '.' to label length
int i = dstIndex - 2;
int e = i - Scope.Length;
int c = 0;
do
{
if (dst[i] == '.')
{
dst[i] = unchecked((byte)c);
c = 0;
}
else
{
c++;
}
}
while (i-- > e);
return Scope.Length + 2;
}
internal virtual int WriteScopeWireFormat(byte[] dst, int dstIndex)
{
if (Scope == null)
{
dst[dstIndex] = unchecked(unchecked(0x00));
return 1;
}
// copy new scope in
dst[dstIndex++] = unchecked((byte)('.'));
try
{
Array.Copy(Runtime.GetBytesForString(Scope, OemEncoding
), 0, dst, dstIndex, Scope.Length);
}
catch (UnsupportedEncodingException)
{
}
dstIndex += Scope.Length;
dst[dstIndex++] = unchecked(unchecked(0x00));
// now go over scope backwards converting '.' to label length
int i = dstIndex - 2;
int e = i - Scope.Length;
int c = 0;
do
{
if (dst[i] == '.')
{
dst[i] = unchecked((byte)c);
c = 0;
}
else
{
c++;
}
}
while (i-- > e);
return Scope.Length + 2;
}
internal virtual int ReadScopeWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
int n;
StringBuilder sb;
if ((n = src[srcIndex++] & unchecked(0xFF)) == 0)
{
Scope = null;
return 1;
}
try
{
sb = new StringBuilder(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding));
srcIndex += n;
while ((n = src[srcIndex++] & unchecked(0xFF)) != 0)
{
sb.Append('.').Append(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding));
srcIndex += n;
}
Scope = sb.ToString();
}
catch (UnsupportedEncodingException)
{
}
return srcIndex - start;
}
internal virtual int ReadScopeWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
int n;
StringBuilder sb;
if ((n = src[srcIndex++] & unchecked(0xFF)) == 0)
{
Scope = null;
return 1;
}
try
{
sb = new StringBuilder(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding));
srcIndex += n;
while ((n = src[srcIndex++] & unchecked(0xFF)) != 0)
{
sb.Append('.').Append(Runtime.GetStringForBytes(src, srcIndex, n, OemEncoding));
srcIndex += n;
}
Scope = sb.ToString();
}
catch (UnsupportedEncodingException)
{
}
return srcIndex - start;
}
public override int GetHashCode()
{
int result;
result = name.GetHashCode();
result += 65599 * HexCode;
result += 65599 * SrcHashCode;
if (Scope != null && Scope.Length != 0)
{
result += Scope.GetHashCode();
}
return result;
}
public override int GetHashCode()
{
int result;
result = name.GetHashCode();
result += 65599 * HexCode;
result += 65599 * SrcHashCode;
if (Scope != null && Scope.Length != 0)
{
result += Scope.GetHashCode();
}
return result;
}
public override bool Equals(object obj)
{
Name n;
if (!(obj is Name))
{
return false;
}
n = (Name)obj;
if (Scope == null && n.Scope == null)
{
return name.Equals(n.name) && HexCode == n.HexCode;
}
return name.Equals(n.name) && HexCode == n.HexCode && Scope.Equals(n.Scope);
}
public override bool Equals(object obj)
{
Name n;
if (!(obj is Name))
{
return false;
}
n = (Name)obj;
if (Scope == null && n.Scope == null)
{
return name.Equals(n.name) && HexCode == n.HexCode;
}
return name.Equals(n.name) && HexCode == n.HexCode && Scope.Equals(n.Scope);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
public override string ToString()
{
StringBuilder sb = new StringBuilder();
//return "";
//return "";
string n = name;
// fix MSBROWSE name
if (n == null)
{
n = "null";
}
else
{
if (n[0] == unchecked(0x01))
{
char[] c = n.ToCharArray();
c[0] = '.';
c[1] = '.';
c[14] = '.';
n = new string(c);
}
}
sb.Append(n).Append("<").Append(Hexdump.ToHexString(HexCode, 2)).Append(">");
if (Scope != null)
{
sb.Append(".").Append(Scope);
}
return sb.ToString();
}
}
string n = name;
// fix MSBROWSE name
if (n == null)
{
n = "null";
}
else
{
if (n[0] == unchecked(0x01))
{
char[] c = n.ToCharArray();
c[0] = '.';
c[1] = '.';
c[14] = '.';
n = new string(c);
}
}
sb.Append(n).Append("<").Append(Hexdump.ToHexString(HexCode, 2)).Append(">");
if (Scope != null)
{
sb.Append(".").Append(Scope);
}
return sb.ToString();
}
}
}

View File

@ -16,37 +16,37 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Netbios
{
internal class NameQueryRequest : NameServicePacket
{
internal NameQueryRequest(Name name)
{
QuestionName = name;
QuestionType = Nb;
}
internal class NameQueryRequest : NameServicePacket
{
internal NameQueryRequest(Name name)
{
QuestionName = name;
QuestionType = Nb;
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
return WriteQuestionSectionWireFormat(dst, dstIndex);
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
return WriteQuestionSectionWireFormat(dst, dstIndex);
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return ReadQuestionSectionWireFormat(src, srcIndex);
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return ReadQuestionSectionWireFormat(src, srcIndex);
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
return 0;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
return 0;
}
public override string ToString()
{
return "NameQueryRequest[" + base.ToString() + "]";
}
}
public override string ToString()
{
return "NameQueryRequest[" + base.ToString() + "]";
}
}
}

View File

@ -16,52 +16,53 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Netbios
{
internal class NameQueryResponse : NameServicePacket
{
public NameQueryResponse()
{
RecordName = new Name();
}
internal class NameQueryResponse : NameServicePacket
{
public NameQueryResponse()
{
RecordName = new Name();
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return ReadResourceRecordWireFormat(src, srcIndex);
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return ReadResourceRecordWireFormat(src, srcIndex);
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
if (ResultCode != 0 || OpCode != Query)
{
return 0;
}
bool groupName = ((src[srcIndex] & unchecked(0x80)) == unchecked(0x80)) ? true : false;
int nodeType = (src[srcIndex] & unchecked(0x60)) >> 5;
srcIndex += 2;
int address = ReadInt4(src, srcIndex);
if (address != 0)
{
AddrEntry[AddrIndex] = new NbtAddress(RecordName, address, groupName, nodeType);
}
else
{
AddrEntry[AddrIndex] = null;
}
return 6;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
if (ResultCode != 0 || OpCode != Query)
{
return 0;
}
bool groupName = ((src[srcIndex] & unchecked(0x80)) == unchecked(0x80)) ? true : false;
int nodeType = (src[srcIndex] & unchecked(0x60)) >> 5;
srcIndex += 2;
int address = ReadInt4(src, srcIndex);
if (address != 0)
{
AddrEntry[AddrIndex] = new NbtAddress(RecordName, address, groupName, nodeType);
}
else
{
AddrEntry[AddrIndex] = null;
}
return 6;
}
public override string ToString()
{
return "NameQueryResponse[" + base.ToString() + ",addrEntry=" + AddrEntry + "]";
}
}
public override string ToString()
{
return "NameQueryResponse[" + base.ToString() + ",addrEntry=" + AddrEntry
+ "]";
}
}
}

View File

@ -21,13 +21,10 @@ 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
{
@ -51,29 +48,27 @@ 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();
@ -87,20 +82,18 @@ namespace SharpCifs.Netbios
private byte[] _rcvBuf;
private SocketEx _socketSender;
private SocketEx _socket;
private Hashtable _responseTable = new Hashtable();
private Thread _thread;
private int _nextNameTrnId;
private int[] _resolveOrder;
private bool _waitResponse = true;
private bool _isActive = false;
private AutoResetEvent _autoResetWaitReceive;
internal IPAddress laddr;
@ -116,17 +109,13 @@ namespace SharpCifs.Netbios
{
this._lport = lport;
this.laddr = laddr
?? Config.GetLocalHost()
?? Extensions.GetLocalAddresses()?.FirstOrDefault();
if (this.laddr == null)
throw new ArgumentNullException("IPAddress NOT found. if exec on localhost, set vallue to [jcifs.smb.client.laddr]");
this.laddr = laddr
?? Config.GetLocalHost()
?? Extensions.GetAddressesByName(Dns.GetHostName()).FirstOrDefault();
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)
{
@ -172,8 +161,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;
}
@ -219,93 +208,53 @@ 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 (
_socketSender == null
|| _socketSender.LocalEndPoint == null
|| _socketSender.GetLocalPort() != localPort
|| !IPAddress.Any.Equals(_socketSender.GetLocalInetAddress())
)
if (_socket == null)
{
if (_socketSender != null)
{
_socketSender.Dispose();
_socketSender = null;
}
_socketSender = new SocketEx(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
_socketSender.Bind(new IPEndPoint(IPAddress.Any, localPort));
_socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//IPAddress.`Address` property deleted
//_socket.Bind(new IPEndPoint(laddr.Address, _lport));
_socket.Bind(new IPEndPoint(laddr, _lport));
if (_waitResponse)
{
if (_thread != null)
{
_thread.Cancel(true);
_thread.Dispose();
}
_thread = new Thread(this);
_thread = new Thread(this); //new Sharpen.Thread(this, "JCIFS-NameServiceClient");
_thread.SetDaemon(true);
_thread.Start(true);
_thread.Start();
}
}
}
internal virtual void TryClose()
{
//Log.Out("NameSerciceClient.TryClose");
if (this._isActive)
{
//Log.Out("NameSerciceClient.TryClose - Now in Processing... Exit.");
return;
}
lock (_lock)
{
if (_socketSender != null)
if (_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");
//Socket.`Close` method deleted
//_socket.Close();
_socket.Dispose();
_socket = null;
}
_thread = null;
if (_waitResponse)
{
_responseTable.Clear();
}
else
} else
{
_autoResetWaitReceive.Set();
}
}
}
private int _recievedLength = -1;
public virtual void Run()
{
int nameTrnId;
@ -313,38 +262,12 @@ namespace SharpCifs.Netbios
try
{
while (Thread.CurrentThread().Equals(_thread))
while (_thread == Thread.CurrentThread())
{
if (_thread.IsCanceled)
break;
_socket.SoTimeOut = _closeTimeout;
var localPort = (SmbConstants.Lport == 0) ? _lport : SmbConstants.Lport;
var sockEvArg = new SocketAsyncEventArgs();
sockEvArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, localPort);
sockEvArg.SetBuffer(_rcvBuf, 0, RcvBufSize);
sockEvArg.Completed += this.OnReceiveCompleted;
_socketSender.SoTimeOut = _closeTimeout;
this._recievedLength = -1;
//Log.Out($"NameServiceClient.Run - Wait Recieve: {IPAddress.Any}: {localPort}");
_socketSender.ReceiveFromAsync(sockEvArg);
while (this._recievedLength == -1)
{
if (_thread.IsCanceled)
break;
Task.Delay(300).GetAwaiter().GetResult();
}
sockEvArg?.Dispose();
if (_thread.IsCanceled)
break;
int len = _socket.Receive(_rcvBuf, 0, RcvBufSize);
if (_log.Level > 3)
{
@ -361,15 +284,12 @@ 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, this._recievedLength);
Hexdump.ToHexdump(_log, _rcvBuf, 0, len);
}
if (response.IsResponse)
@ -380,6 +300,7 @@ namespace SharpCifs.Netbios
}
}
}
}
catch (TimeoutException) { }
catch (Exception ex)
@ -395,21 +316,10 @@ namespace SharpCifs.Netbios
}
}
private void OnReceiveCompleted(object sender, SocketAsyncEventArgs e)
{
//Log.Out("NameServiceClient.OnReceiveCompleted");
this._recievedLength = e.BytesTransferred;
}
/// <exception cref="System.IO.IOException"></exception>
internal virtual void Send(NameServicePacket request,
NameServicePacket response,
int timeout)
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)
@ -419,7 +329,6 @@ namespace SharpCifs.Netbios
lock (response)
{
this._isActive = true;
while (max-- > 0)
{
@ -429,75 +338,45 @@ 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);
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");
_socket.Send(_sndBuf, 0, requestLenght, new IPEndPoint(request.Addr, _lport));
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;
isRecieved = true;
break;
return;
}
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)
@ -514,24 +393,17 @@ 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.Addr.ToString() == Baddr.ToString());
request.IsBroadcast = request.Addr == null;
if (request.IsBroadcast)
{
request.Addr = Baddr;
@ -568,12 +440,10 @@ namespace SharpCifs.Netbios
/// <exception cref="UnknownHostException"></exception>
internal virtual NbtAddress GetByName(Name name, IPAddress addr)
{
//Log.Out("NameSerciceClient.GetByName");
int n;
NameQueryRequest request = new NameQueryRequest(name);
NameQueryResponse response = new NameQueryResponse();
if (addr != null)
{
request.Addr = addr;
@ -593,9 +463,7 @@ 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;
@ -603,11 +471,9 @@ namespace SharpCifs.Netbios
return response.AddrEntry[last];
}
}
while (--n > 0 && request.IsBroadcast);
throw new UnknownHostException();
}
for (int i = 0; i < _resolveOrder.Length; i++)
{
try
@ -630,9 +496,8 @@ namespace SharpCifs.Netbios
case ResolverWins:
case ResolverBcast:
{
if (_resolveOrder[i] == ResolverWins
&& name.name != NbtAddress.MasterBrowserName
&& name.HexCode != unchecked(0x1d))
if (_resolveOrder[i] == ResolverWins && name.name != NbtAddress.MasterBrowserName
&& name.HexCode != unchecked(0x1d))
{
request.Addr = NbtAddress.GetWinsAddress();
request.IsBroadcast = false;
@ -657,12 +522,11 @@ 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)
@ -678,15 +542,12 @@ 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;
@ -695,7 +556,6 @@ namespace SharpCifs.Netbios
request = new NodeStatusRequest(new Name(NbtAddress.AnyHostsName, unchecked(0x00), null));
request.Addr = addr.GetInetAddress();
n = RetryCount;
while (n-- > 0)
{
try
@ -725,8 +585,6 @@ namespace SharpCifs.Netbios
internal virtual NbtAddress[] GetHosts()
{
//Log.Out("NbtServiceClient.GetHosts");
try
{
_waitResponse = false;
@ -735,8 +593,6 @@ namespace SharpCifs.Netbios
for (int i = 1; i <= 254; i++)
{
//Log.Out($"NbtServiceClient.GetHosts - {i}");
NodeStatusRequest request;
NodeStatusResponse response;
@ -749,59 +605,49 @@ namespace SharpCifs.Netbios
IPAddress addr = new IPAddress(addrBytes);
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
};
//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));
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);
}
throw new UnknownHostException(ioe);
}
_autoResetWaitReceive = new AutoResetEvent(false);
if (_thread != null)
{
_thread.Cancel(true);
_thread.Dispose();
}
_thread = new Thread(this);
_thread = new Thread(this);
_thread.SetDaemon(true);
_thread.Start(true);
_thread.Start();
_autoResetWaitReceive.WaitOne();
_autoResetWaitReceive.WaitOne();
var result = new List<NbtAddress>();
List<NbtAddress> result = new List<NbtAddress>();
foreach (var key in _responseTable.Keys)
{
var resp = (NodeStatusResponse)_responseTable[key];
NodeStatusResponse resp = (NodeStatusResponse)_responseTable[key];
if (!resp.Received || resp.ResultCode != 0)
continue;
result.AddRange(resp.AddressArray
.Where(entry => entry.HostName.HexCode == 0x20));
if (resp.Received && resp.ResultCode == 0)
{
foreach (var entry in resp.AddressArray)
{
if (entry.HostName.HexCode == 0x20)
{
result.Add(entry);
}
}
}
}
_responseTable.Clear();

View File

@ -20,474 +20,429 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
internal abstract class NameServicePacket
{
internal const int Query = 0;
internal abstract class NameServicePacket
{
internal const int Query = 0;
internal const int Wack = 7;
internal const int Wack = 7;
internal const int FmtErr = 0x1;
internal const int FmtErr = 0x1;
internal const int SrvErr = 0x2;
internal const int SrvErr = 0x2;
internal const int ImpErr = 0x4;
internal const int ImpErr = 0x4;
internal const int RfsErr = 0x5;
internal const int RfsErr = 0x5;
internal const int ActErr = 0x6;
internal const int ActErr = 0x6;
internal const int CftErr = 0x7;
internal const int CftErr = 0x7;
internal const int NbIn = 0x00200001;
internal const int NbIn = 0x00200001;
internal const int NbstatIn = 0x00210001;
internal const int NbstatIn = 0x00210001;
internal const int Nb = 0x0020;
internal const int Nb = 0x0020;
internal const int Nbstat = 0x0021;
internal const int Nbstat = 0x0021;
internal const int In = 0x0001;
internal const int In = 0x0001;
internal const int A = 0x0001;
internal const int A = 0x0001;
internal const int Ns = 0x0002;
internal const int Ns = 0x0002;
internal const int Null = 0x000a;
internal const int Null = 0x000a;
internal const int HeaderLength = 12;
internal const int HeaderLength = 12;
internal const int OpcodeOffset = 2;
internal const int OpcodeOffset = 2;
internal const int QuestionOffset = 4;
internal const int QuestionOffset = 4;
internal const int AnswerOffset = 6;
internal const int AnswerOffset = 6;
internal const int AuthorityOffset = 8;
internal const int AuthorityOffset = 8;
internal const int AdditionalOffset = 10;
internal const int AdditionalOffset = 10;
// opcode
// rcode
// type/class
// header field offsets
internal static void WriteInt2(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
// opcode
// rcode
// type/class
// header field offsets
internal static void WriteInt2(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
internal static void WriteInt4(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
internal static void WriteInt4(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
internal static int ReadInt2(byte[] src, int srcIndex)
{
return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked(
0xFF));
}
internal static int ReadInt2(byte[] src, int srcIndex)
{
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));
}
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));
}
internal static int ReadNameTrnId(byte[] src, int srcIndex)
{
return ReadInt2(src, srcIndex);
}
internal static int ReadNameTrnId(byte[] src, int srcIndex)
{
return ReadInt2(src, srcIndex);
}
internal int AddrIndex;
internal int AddrIndex;
internal NbtAddress[] AddrEntry;
internal NbtAddress[] AddrEntry;
internal int NameTrnId;
internal int NameTrnId;
internal int OpCode;
internal int OpCode;
internal int ResultCode;
internal int ResultCode;
internal int QuestionCount;
internal int QuestionCount;
internal int AnswerCount;
internal int AnswerCount;
internal int AuthorityCount;
internal int AuthorityCount;
internal int AdditionalCount;
internal int AdditionalCount;
internal bool Received;
internal bool Received;
internal bool IsResponse;
internal bool IsResponse;
internal bool IsAuthAnswer;
internal bool IsAuthAnswer;
internal bool IsTruncated;
internal bool IsTruncated;
internal bool IsRecurDesired;
internal bool IsRecurDesired;
internal bool IsRecurAvailable;
internal bool IsRecurAvailable;
internal bool IsBroadcast;
internal bool IsBroadcast;
internal Name QuestionName;
internal Name QuestionName;
internal Name RecordName;
internal int QuestionType;
internal int QuestionClass;
internal int RecordType;
internal int RecordClass;
internal int Ttl;
internal int RDataLength;
internal IPAddress Addr;
public NameServicePacket()
{
IsRecurDesired = true;
IsBroadcast = true;
QuestionCount = 1;
QuestionClass = In;
}
internal virtual int WriteWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dstIndex += WriteHeaderWireFormat(dst, dstIndex);
dstIndex += WriteBodyWireFormat(dst, dstIndex);
return dstIndex - start;
}
internal virtual int ReadWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
srcIndex += ReadHeaderWireFormat(src, srcIndex);
srcIndex += ReadBodyWireFormat(src, srcIndex);
return srcIndex - start;
}
internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
{
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))
)
);
WriteInt2(QuestionCount, dst, start + QuestionOffset);
WriteInt2(AnswerCount, dst, start + AnswerOffset);
WriteInt2(AuthorityCount, dst, start + AuthorityOffset);
WriteInt2(AdditionalCount, dst, start + AdditionalOffset);
return HeaderLength;
}
internal virtual int ReadHeaderWireFormat(byte[] src, int srcIndex)
{
NameTrnId = ReadInt2(src, srcIndex);
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
: 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;
ResultCode = src[srcIndex + OpcodeOffset + 1] & unchecked(0x0F);
QuestionCount = ReadInt2(src, srcIndex + QuestionOffset);
AnswerCount = ReadInt2(src, srcIndex + AnswerOffset);
AuthorityCount = ReadInt2(src, srcIndex + AuthorityOffset);
AdditionalCount = ReadInt2(src, srcIndex + AdditionalOffset);
return HeaderLength;
}
internal virtual int WriteQuestionSectionWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dstIndex += QuestionName.WriteWireFormat(dst, dstIndex);
WriteInt2(QuestionType, dst, dstIndex);
dstIndex += 2;
WriteInt2(QuestionClass, dst, dstIndex);
dstIndex += 2;
return dstIndex - start;
}
internal virtual int ReadQuestionSectionWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
srcIndex += QuestionName.ReadWireFormat(src, srcIndex);
QuestionType = ReadInt2(src, srcIndex);
srcIndex += 2;
QuestionClass = ReadInt2(src, srcIndex);
srcIndex += 2;
return srcIndex - start;
}
internal virtual int WriteResourceRecordWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
if (RecordName == QuestionName)
{
dst[dstIndex++] = unchecked(unchecked(0xC0));
// label string pointer to
dst[dstIndex++] = unchecked(unchecked(0x0C));
}
else
{
// questionName (offset 12)
dstIndex += RecordName.WriteWireFormat(dst, dstIndex);
}
WriteInt2(RecordType, dst, dstIndex);
dstIndex += 2;
WriteInt2(RecordClass, dst, dstIndex);
dstIndex += 2;
WriteInt4(Ttl, dst, dstIndex);
dstIndex += 4;
RDataLength = WriteRDataWireFormat(dst, dstIndex + 2);
WriteInt2(RDataLength, dst, dstIndex);
dstIndex += 2 + RDataLength;
return dstIndex - start;
}
internal virtual int ReadResourceRecordWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
int end;
if ((src[srcIndex] & unchecked(0xC0)) == unchecked(0xC0))
{
RecordName = QuestionName;
// label string pointer to questionName
srcIndex += 2;
}
else
{
srcIndex += RecordName.ReadWireFormat(src, srcIndex);
}
RecordType = ReadInt2(src, srcIndex);
srcIndex += 2;
RecordClass = ReadInt2(src, srcIndex);
srcIndex += 2;
Ttl = ReadInt4(src, srcIndex);
srcIndex += 4;
RDataLength = ReadInt2(src, srcIndex);
srcIndex += 2;
AddrEntry = new NbtAddress[RDataLength / 6];
end = srcIndex + RDataLength;
for (AddrIndex = 0; srcIndex < end; AddrIndex++)
{
srcIndex += ReadRDataWireFormat(src, srcIndex);
}
return srcIndex - start;
}
internal abstract int WriteBodyWireFormat(byte[] dst, int dstIndex);
internal abstract int ReadBodyWireFormat(byte[] src, int srcIndex);
internal abstract int WriteRDataWireFormat(byte[] dst, int dstIndex);
internal abstract int ReadRDataWireFormat(byte[] src, int srcIndex);
public override string ToString()
{
string opCodeString;
string resultCodeString;
string questionTypeString;
string recordTypeString;
switch (OpCode)
{
case Query:
{
opCodeString = "QUERY";
break;
}
case Wack:
{
opCodeString = "WACK";
break;
}
default:
{
opCodeString = Extensions.ToString(OpCode);
break;
}
}
switch (ResultCode)
{
case FmtErr:
{
resultCodeString = "FMT_ERR";
break;
}
case SrvErr:
{
resultCodeString = "SRV_ERR";
break;
}
case ImpErr:
{
resultCodeString = "IMP_ERR";
break;
}
case RfsErr:
{
resultCodeString = "RFS_ERR";
break;
}
case ActErr:
{
resultCodeString = "ACT_ERR";
break;
}
case CftErr:
{
resultCodeString = "CFT_ERR";
break;
}
default:
{
resultCodeString = "0x" + Hexdump.ToHexString(ResultCode, 1);
break;
}
}
switch (QuestionType)
{
case Nb:
{
questionTypeString = "NB";
break;
}
case Nbstat:
{
questionTypeString = "NBSTAT";
break;
}
default:
{
questionTypeString = "0x" + Hexdump.ToHexString(QuestionType, 4);
break;
}
}
switch (RecordType)
{
case A:
{
recordTypeString = "A";
break;
}
case Ns:
{
recordTypeString = "NS";
break;
}
case Null:
{
recordTypeString = "NULL";
break;
}
case Nb:
{
recordTypeString = "NB";
break;
}
case Nbstat:
{
recordTypeString = "NBSTAT";
break;
}
default:
{
recordTypeString = "0x" + Hexdump.ToHexString(RecordType, 4);
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;
}
}
internal Name RecordName;
internal int QuestionType;
internal int QuestionClass;
internal int RecordType;
internal int RecordClass;
internal int Ttl;
internal int RDataLength;
internal IPAddress Addr;
public NameServicePacket()
{
IsRecurDesired = true;
IsBroadcast = true;
QuestionCount = 1;
QuestionClass = In;
}
internal virtual int WriteWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dstIndex += WriteHeaderWireFormat(dst, dstIndex);
dstIndex += WriteBodyWireFormat(dst, dstIndex);
return dstIndex - start;
}
internal virtual int ReadWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
srcIndex += ReadHeaderWireFormat(src, srcIndex);
srcIndex += ReadBodyWireFormat(src, srcIndex);
return srcIndex - start;
}
internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
{
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))));
WriteInt2(QuestionCount, dst, start + QuestionOffset);
WriteInt2(AnswerCount, dst, start + AnswerOffset);
WriteInt2(AuthorityCount, dst, start + AuthorityOffset);
WriteInt2(AdditionalCount, dst, start + AdditionalOffset);
return HeaderLength;
}
internal virtual int ReadHeaderWireFormat(byte[] src, int srcIndex)
{
NameTrnId = ReadInt2(src, srcIndex);
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
: 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;
ResultCode = src[srcIndex + OpcodeOffset + 1] & unchecked(0x0F);
QuestionCount = ReadInt2(src, srcIndex + QuestionOffset);
AnswerCount = ReadInt2(src, srcIndex + AnswerOffset);
AuthorityCount = ReadInt2(src, srcIndex + AuthorityOffset);
AdditionalCount = ReadInt2(src, srcIndex + AdditionalOffset);
return HeaderLength;
}
internal virtual int WriteQuestionSectionWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dstIndex += QuestionName.WriteWireFormat(dst, dstIndex);
WriteInt2(QuestionType, dst, dstIndex);
dstIndex += 2;
WriteInt2(QuestionClass, dst, dstIndex);
dstIndex += 2;
return dstIndex - start;
}
internal virtual int ReadQuestionSectionWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
srcIndex += QuestionName.ReadWireFormat(src, srcIndex);
QuestionType = ReadInt2(src, srcIndex);
srcIndex += 2;
QuestionClass = ReadInt2(src, srcIndex);
srcIndex += 2;
return srcIndex - start;
}
internal virtual int WriteResourceRecordWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
if (RecordName == QuestionName)
{
dst[dstIndex++] = unchecked(unchecked(0xC0));
// label string pointer to
dst[dstIndex++] = unchecked(unchecked(0x0C));
}
else
{
// questionName (offset 12)
dstIndex += RecordName.WriteWireFormat(dst, dstIndex);
}
WriteInt2(RecordType, dst, dstIndex);
dstIndex += 2;
WriteInt2(RecordClass, dst, dstIndex);
dstIndex += 2;
WriteInt4(Ttl, dst, dstIndex);
dstIndex += 4;
RDataLength = WriteRDataWireFormat(dst, dstIndex + 2);
WriteInt2(RDataLength, dst, dstIndex);
dstIndex += 2 + RDataLength;
return dstIndex - start;
}
internal virtual int ReadResourceRecordWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
int end;
if ((src[srcIndex] & unchecked(0xC0)) == unchecked(0xC0))
{
RecordName = QuestionName;
// label string pointer to questionName
srcIndex += 2;
}
else
{
srcIndex += RecordName.ReadWireFormat(src, srcIndex);
}
RecordType = ReadInt2(src, srcIndex);
srcIndex += 2;
RecordClass = ReadInt2(src, srcIndex);
srcIndex += 2;
Ttl = ReadInt4(src, srcIndex);
srcIndex += 4;
RDataLength = ReadInt2(src, srcIndex);
srcIndex += 2;
AddrEntry = new NbtAddress[RDataLength / 6];
end = srcIndex + RDataLength;
for (AddrIndex = 0; srcIndex < end; AddrIndex++)
{
srcIndex += ReadRDataWireFormat(src, srcIndex);
}
return srcIndex - start;
}
internal abstract int WriteBodyWireFormat(byte[] dst, int dstIndex);
internal abstract int ReadBodyWireFormat(byte[] src, int srcIndex);
internal abstract int WriteRDataWireFormat(byte[] dst, int dstIndex);
internal abstract int ReadRDataWireFormat(byte[] src, int srcIndex);
public override string ToString()
{
string opCodeString;
string resultCodeString;
string questionTypeString;
string recordTypeString;
switch (OpCode)
{
case Query:
{
opCodeString = "QUERY";
break;
}
case Wack:
{
opCodeString = "WACK";
break;
}
default:
{
opCodeString = Extensions.ToString(OpCode);
break;
}
}
switch (ResultCode)
{
case FmtErr:
{
resultCodeString = "FMT_ERR";
break;
}
case SrvErr:
{
resultCodeString = "SRV_ERR";
break;
}
case ImpErr:
{
resultCodeString = "IMP_ERR";
break;
}
case RfsErr:
{
resultCodeString = "RFS_ERR";
break;
}
case ActErr:
{
resultCodeString = "ACT_ERR";
break;
}
case CftErr:
{
resultCodeString = "CFT_ERR";
break;
}
default:
{
resultCodeString = "0x" + Hexdump.ToHexString(ResultCode, 1);
break;
}
}
switch (QuestionType)
{
case Nb:
{
questionTypeString = "NB";
break;
}
case Nbstat:
{
questionTypeString = "NBSTAT";
break;
}
default:
{
questionTypeString = "0x" + Hexdump.ToHexString(QuestionType, 4);
break;
}
}
switch (RecordType)
{
case A:
{
recordTypeString = "A";
break;
}
case Ns:
{
recordTypeString = "NS";
break;
}
case Null:
{
recordTypeString = "NULL";
break;
}
case Nb:
{
recordTypeString = "NB";
break;
}
case Nbstat:
{
recordTypeString = "NBSTAT";
break;
}
default:
{
recordTypeString = "0x" + Hexdump.ToHexString(RecordType, 4);
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;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -19,147 +19,146 @@ using System.IO;
namespace SharpCifs.Netbios
{
public class NbtException : IOException
{
public const int Success = 0;
public class NbtException : IOException
{
public const int Success = 0;
public const int ErrNamSrvc = unchecked(0x01);
public const int ErrNamSrvc = unchecked(0x01);
public const int ErrSsnSrvc = unchecked(0x02);
public const int ErrSsnSrvc = unchecked(0x02);
public const int FmtErr = unchecked(0x1);
public const int FmtErr = unchecked(0x1);
public const int SrvErr = unchecked(0x2);
public const int SrvErr = unchecked(0x2);
public const int ImpErr = unchecked(0x4);
public const int ImpErr = unchecked(0x4);
public const int RfsErr = unchecked(0x5);
public const int RfsErr = unchecked(0x5);
public const int ActErr = unchecked(0x6);
public const int ActErr = unchecked(0x6);
public const int CftErr = unchecked(0x7);
public const int CftErr = unchecked(0x7);
public const int ConnectionRefused = -1;
public const int ConnectionRefused = -1;
public const int NotListeningCalled = unchecked(0x80);
public const int NotListeningCalled = unchecked(0x80);
public const int NotListeningCalling = unchecked(0x81);
public const int NotListeningCalling = unchecked(0x81);
public const int CalledNotPresent = unchecked(0x82);
public const int CalledNotPresent = unchecked(0x82);
public const int NoResources = unchecked(0x83);
public const int NoResources = unchecked(0x83);
public const int Unspecified = unchecked(0x8F);
public const int Unspecified = unchecked(0x8F);
public int ErrorClass;
public int ErrorClass;
public int ErrorCode;
public int ErrorCode;
// error classes
// name service error codes
// session service error codes
public static string GetErrorString(int errorClass, int errorCode)
{
string result = string.Empty;
switch (errorClass)
{
case Success:
{
result += "SUCCESS";
break;
}
// error classes
// name service error codes
// session service error codes
public static string GetErrorString(int errorClass, int errorCode)
{
string result = string.Empty;
switch (errorClass)
{
case Success:
{
result += "SUCCESS";
break;
}
case ErrNamSrvc:
{
result += "ERR_NAM_SRVC/";
switch (errorCode)
{
case FmtErr:
{
result += "FMT_ERR: Format Error";
goto default;
}
case ErrNamSrvc:
{
result += "ERR_NAM_SRVC/";
switch (errorCode)
{
case FmtErr:
{
result += "FMT_ERR: Format Error";
goto default;
}
default:
{
result += "Unknown error code: " + errorCode;
break;
}
}
break;
}
default:
{
result += "Unknown error code: " + errorCode;
break;
}
}
break;
}
case ErrSsnSrvc:
{
result += "ERR_SSN_SRVC/";
switch (errorCode)
{
case ConnectionRefused:
{
result += "Connection refused";
break;
}
case ErrSsnSrvc:
{
result += "ERR_SSN_SRVC/";
switch (errorCode)
{
case ConnectionRefused:
{
result += "Connection refused";
break;
}
case NotListeningCalled:
{
result += "Not listening on called name";
break;
}
case NotListeningCalled:
{
result += "Not listening on called name";
break;
}
case NotListeningCalling:
{
result += "Not listening for calling name";
break;
}
case NotListeningCalling:
{
result += "Not listening for calling name";
break;
}
case CalledNotPresent:
{
result += "Called name not present";
break;
}
case CalledNotPresent:
{
result += "Called name not present";
break;
}
case NoResources:
{
result += "Called name present, but insufficient resources";
break;
}
case NoResources:
{
result += "Called name present, but insufficient resources";
break;
}
case Unspecified:
{
result += "Unspecified error";
break;
}
case Unspecified:
{
result += "Unspecified error";
break;
}
default:
{
result += "Unknown error code: " + errorCode;
break;
}
}
break;
}
default:
{
result += "Unknown error code: " + errorCode;
break;
}
}
break;
}
default:
{
result += "unknown error class: " + errorClass;
break;
}
}
return result;
}
default:
{
result += "unknown error class: " + errorClass;
break;
}
}
return result;
}
public NbtException(int errorClass, int errorCode) : base(GetErrorString(errorClass
, errorCode))
{
this.ErrorClass = errorClass;
this.ErrorCode = errorCode;
}
public NbtException(int errorClass, int errorCode) : base(GetErrorString(errorClass
, errorCode))
{
this.ErrorClass = errorClass;
this.ErrorCode = errorCode;
}
public override string ToString()
{
return "errorClass=" + ErrorClass
+ ",errorCode=" + ErrorCode
+ ",errorString=" + GetErrorString(ErrorClass, ErrorCode);
}
}
public override string ToString()
{
return "errorClass=" + ErrorClass + ",errorCode=" + ErrorCode + ",errorString="
+ GetErrorString(ErrorClass, ErrorCode);
}
}
}

View File

@ -16,44 +16,44 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Netbios
{
internal class NodeStatusRequest : NameServicePacket
{
internal NodeStatusRequest(Name name)
{
QuestionName = name;
QuestionType = Nbstat;
IsRecurDesired = false;
IsBroadcast = false;
}
internal class NodeStatusRequest : NameServicePacket
{
internal NodeStatusRequest(Name name)
{
QuestionName = name;
QuestionType = Nbstat;
IsRecurDesired = false;
IsBroadcast = false;
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
int tmp = QuestionName.HexCode;
QuestionName.HexCode = unchecked(0x00);
// type has to be 0x00 for node status
int result = WriteQuestionSectionWireFormat(dst, dstIndex);
QuestionName.HexCode = tmp;
return result;
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
int tmp = QuestionName.HexCode;
QuestionName.HexCode = unchecked(0x00);
// type has to be 0x00 for node status
int result = WriteQuestionSectionWireFormat(dst, dstIndex);
QuestionName.HexCode = tmp;
return result;
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return 0;
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return 0;
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
return 0;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
return 0;
}
public override string ToString()
{
return "NodeStatusRequest[" + base.ToString() + "]";
}
}
public override string ToString()
{
return "NodeStatusRequest[" + base.ToString() + "]";
}
}
}

View File

@ -19,140 +19,122 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
internal class NodeStatusResponse : NameServicePacket
{
private NbtAddress _queryAddress;
internal class NodeStatusResponse : NameServicePacket
{
private NbtAddress _queryAddress;
private int _numberOfNames;
private int _numberOfNames;
private byte[] _macAddress;
private byte[] _macAddress;
private byte[] _stats;
private byte[] _stats;
internal NbtAddress[] AddressArray;
internal NbtAddress[] AddressArray;
internal NodeStatusResponse(NbtAddress queryAddress)
{
this._queryAddress = queryAddress;
RecordName = new Name();
_macAddress = new byte[6];
}
internal NodeStatusResponse(NbtAddress queryAddress)
{
this._queryAddress = queryAddress;
RecordName = new Name();
_macAddress = new byte[6];
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBodyWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return ReadResourceRecordWireFormat(src, srcIndex);
}
internal override int ReadBodyWireFormat(byte[] src, int srcIndex)
{
return ReadResourceRecordWireFormat(src, srcIndex);
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteRDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
_numberOfNames = src[srcIndex] & unchecked(0xFF);
int namesLength = _numberOfNames * 18;
int statsLength = RDataLength - namesLength - 1;
_numberOfNames = src[srcIndex++] & unchecked(0xFF);
// gotta read the mac first so we can populate addressArray with it
Array.Copy(src, srcIndex + namesLength, _macAddress, 0, 6);
srcIndex += ReadNodeNameArray(src, srcIndex);
_stats = new byte[statsLength];
Array.Copy(src, srcIndex, _stats, 0, statsLength);
srcIndex += statsLength;
return srcIndex - start;
}
internal override int ReadRDataWireFormat(byte[] src, int srcIndex)
{
int start = srcIndex;
_numberOfNames = src[srcIndex] & unchecked(0xFF);
int namesLength = _numberOfNames * 18;
int statsLength = RDataLength - namesLength - 1;
_numberOfNames = src[srcIndex++] & unchecked(0xFF);
// gotta read the mac first so we can populate addressArray with it
Array.Copy(src, srcIndex + namesLength, _macAddress, 0, 6);
srcIndex += ReadNodeNameArray(src, srcIndex);
_stats = new byte[statsLength];
Array.Copy(src, srcIndex, _stats, 0, statsLength);
srcIndex += statsLength;
return srcIndex - start;
}
private int ReadNodeNameArray(byte[] src, int srcIndex)
{
int start = srcIndex;
AddressArray = new NbtAddress[_numberOfNames];
string n;
int hexCode;
string scope = _queryAddress.HostName.Scope;
bool groupName;
int ownerNodeType;
bool isBeingDeleted;
bool isInConflict;
bool isActive;
bool isPermanent;
int j;
bool addrFound = false;
try
{
for (int i = 0; i < _numberOfNames; srcIndex += 18, i++)
{
for (j = srcIndex + 14; src[j] == unchecked(0x20); j--)
{
}
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;
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)))
{
if (_queryAddress.HostName == NbtAddress.UnknownName)
{
_queryAddress.HostName = new Name(n, hexCode, scope);
}
_queryAddress.GroupName = groupName;
_queryAddress.NodeType = ownerNodeType;
_queryAddress.isBeingDeleted = isBeingDeleted;
_queryAddress.isInConflict = isInConflict;
_queryAddress.isActive = isActive;
_queryAddress.isPermanent = isPermanent;
_queryAddress.MacAddress = _macAddress;
_queryAddress.IsDataFromNodeStatus = true;
addrFound = true;
AddressArray[i] = _queryAddress;
}
else
{
AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope),
_queryAddress.Address,
groupName,
ownerNodeType,
isBeingDeleted,
isInConflict,
isActive,
isPermanent,
_macAddress);
}
}
}
catch (UnsupportedEncodingException)
{
}
return srcIndex - start;
}
private int ReadNodeNameArray(byte[] src, int srcIndex)
{
int start = srcIndex;
AddressArray = new NbtAddress[_numberOfNames];
string n;
int hexCode;
string scope = _queryAddress.HostName.Scope;
bool groupName;
int ownerNodeType;
bool isBeingDeleted;
bool isInConflict;
bool isActive;
bool isPermanent;
int j;
bool addrFound = false;
try
{
for (int i = 0; i < _numberOfNames; srcIndex += 18, i++)
{
for (j = srcIndex + 14; src[j] == unchecked(0x20); j--)
{
}
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;
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)))
{
if (_queryAddress.HostName == NbtAddress.UnknownName)
{
_queryAddress.HostName = new Name(n, hexCode, scope);
}
_queryAddress.GroupName = groupName;
_queryAddress.NodeType = ownerNodeType;
_queryAddress.isBeingDeleted = isBeingDeleted;
_queryAddress.isInConflict = isInConflict;
_queryAddress.isActive = isActive;
_queryAddress.isPermanent = isPermanent;
_queryAddress.MacAddress = _macAddress;
_queryAddress.IsDataFromNodeStatus = true;
addrFound = true;
AddressArray[i] = _queryAddress;
}
else
{
AddressArray[i] = new NbtAddress(new Name(n, hexCode, scope), _queryAddress.Address
, groupName, ownerNodeType, isBeingDeleted, isInConflict, isActive, isPermanent,
_macAddress);
}
}
}
catch (UnsupportedEncodingException)
{
}
return srcIndex - start;
}
public override string ToString()
{
return "NodeStatusResponse[" + base.ToString() + "]";
}
}
public override string ToString()
{
return "NodeStatusResponse[" + base.ToString() + "]";
}
}
}

View File

@ -19,44 +19,45 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
public class SessionRequestPacket : SessionServicePacket
{
private Name _calledName;
public class SessionRequestPacket : SessionServicePacket
{
private Name _calledName;
private Name _callingName;
private Name _callingName;
public SessionRequestPacket()
{
_calledName = new Name();
_callingName = new Name();
}
public SessionRequestPacket()
{
_calledName = new Name();
_callingName = new Name();
}
public SessionRequestPacket(Name calledName, Name callingName)
{
Type = SessionRequest;
this._calledName = calledName;
this._callingName = callingName;
}
public SessionRequestPacket(Name calledName, Name callingName)
{
Type = SessionRequest;
this._calledName = calledName;
this._callingName = callingName;
}
internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dstIndex += _calledName.WriteWireFormat(dst, dstIndex);
dstIndex += _callingName.WriteWireFormat(dst, dstIndex);
return dstIndex - start;
}
internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dstIndex += _calledName.WriteWireFormat(dst, dstIndex);
dstIndex += _callingName.WriteWireFormat(dst, dstIndex);
return dstIndex - start;
}
/// <exception cref="System.IO.IOException"></exception>
internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
if (@in.Read(buffer, bufferIndex, Length) != Length)
{
throw new IOException("invalid session request wire format");
}
bufferIndex += _calledName.ReadWireFormat(buffer, bufferIndex);
bufferIndex += _callingName.ReadWireFormat(buffer, bufferIndex);
return bufferIndex - start;
}
}
/// <exception cref="System.IO.IOException"></exception>
internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
)
{
int start = bufferIndex;
if (@in.Read(buffer, bufferIndex, Length) != Length)
{
throw new IOException("invalid session request wire format");
}
bufferIndex += _calledName.ReadWireFormat(buffer, bufferIndex);
bufferIndex += _callingName.ReadWireFormat(buffer, bufferIndex);
return bufferIndex - start;
}
}
}

View File

@ -19,35 +19,36 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
internal class SessionRetargetResponsePacket : SessionServicePacket
{
private NbtAddress _retargetAddress;
internal class SessionRetargetResponsePacket : SessionServicePacket
{
private NbtAddress _retargetAddress;
private int _retargetPort;
private int _retargetPort;
public SessionRetargetResponsePacket()
{
Type = SessionRetargetResponse;
Length = 6;
}
public SessionRetargetResponsePacket()
{
Type = SessionRetargetResponse;
Length = 6;
}
internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteTrailerWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
/// <exception cref="System.IO.IOException"></exception>
internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex)
{
if (@in.Read(buffer, bufferIndex, Length) != Length)
{
throw new IOException("unexpected EOF reading netbios retarget session response");
}
int addr = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
_retargetAddress = new NbtAddress(null, addr, false, NbtAddress.BNode);
_retargetPort = ReadInt2(buffer, bufferIndex);
return Length;
}
}
/// <exception cref="System.IO.IOException"></exception>
internal override int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
)
{
if (@in.Read(buffer, bufferIndex, Length) != Length)
{
throw new IOException("unexpected EOF reading netbios retarget session response");
}
int addr = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
_retargetAddress = new NbtAddress(null, addr, false, NbtAddress.BNode);
_retargetPort = ReadInt2(buffer, bufferIndex);
return Length;
}
}
}

View File

@ -19,136 +19,138 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios
{
public abstract class SessionServicePacket
{
internal const int SessionMessage = unchecked(0x00);
public abstract class SessionServicePacket
{
internal const int SessionMessage = unchecked(0x00);
internal const int SessionRequest = unchecked(0x81);
internal const int SessionRequest = unchecked(0x81);
public const int PositiveSessionResponse = unchecked(0x82);
public const int PositiveSessionResponse = unchecked(0x82);
public const int NegativeSessionResponse = unchecked(0x83);
public const int NegativeSessionResponse = unchecked(0x83);
internal const int SessionRetargetResponse = unchecked(0x84);
internal const int SessionRetargetResponse = unchecked(0x84);
internal const int SessionKeepAlive = unchecked(0x85);
internal const int SessionKeepAlive = unchecked(0x85);
internal const int MaxMessageSize = unchecked(0x0001FFFF);
internal const int MaxMessageSize = unchecked(0x0001FFFF);
internal const int HeaderLength = 4;
internal const int HeaderLength = 4;
// session service packet types
internal static void WriteInt2(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
// session service packet types
internal static void WriteInt2(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
internal static void WriteInt4(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
internal static void WriteInt4(int val, byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
}
internal static int ReadInt2(byte[] src, int srcIndex)
{
return ((src[srcIndex] & unchecked(0xFF)) << 8)
+ (src[srcIndex + 1] & unchecked(0xFF));
}
internal static int ReadInt2(byte[] src, int srcIndex)
{
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));
}
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));
}
internal static int ReadLength(byte[] src, int srcIndex)
{
srcIndex++;
return ((src[srcIndex++] & unchecked(0x01)) << 16)
+ ((src[srcIndex++] & unchecked(0xFF)) << 8)
+ (src[srcIndex++] & 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));
}
/// <exception cref="System.IO.IOException"></exception>
internal static int Readn(InputStream @in, byte[] b, int off, int len)
{
int i = 0;
int n;
while (i < len)
{
n = @in.Read(b, off + i, len - i);
if (n <= 0)
{
break;
}
i += n;
}
return i;
}
/// <exception cref="System.IO.IOException"></exception>
internal static int Readn(InputStream @in, byte[] b, int off, int len)
{
int i = 0;
int n;
while (i < len)
{
n = @in.Read(b, off + i, len - i);
if (n <= 0)
{
break;
}
i += n;
}
return i;
}
/// <exception cref="System.IO.IOException"></exception>
internal static int ReadPacketType(InputStream @in, byte[] buffer, int bufferIndex)
{
int n;
if ((n = Readn(@in, buffer, bufferIndex, HeaderLength)) != HeaderLength)
{
if (n == -1)
{
return -1;
}
throw new IOException("unexpected EOF reading netbios session header");
}
int t = buffer[bufferIndex] & unchecked(0xFF);
return t;
}
/// <exception cref="System.IO.IOException"></exception>
internal static int ReadPacketType(InputStream @in, byte[] buffer, int bufferIndex
)
{
int n;
if ((n = Readn(@in, buffer, bufferIndex, HeaderLength)) != HeaderLength)
{
if (n == -1)
{
return -1;
}
throw new IOException("unexpected EOF reading netbios session header");
}
int t = buffer[bufferIndex] & unchecked(0xFF);
return t;
}
internal int Type;
internal int Type;
internal int Length;
internal int Length;
public virtual int WriteWireFormat(byte[] dst, int dstIndex)
{
Length = WriteTrailerWireFormat(dst, dstIndex + HeaderLength);
WriteHeaderWireFormat(dst, dstIndex);
return HeaderLength + Length;
}
public virtual int WriteWireFormat(byte[] dst, int dstIndex)
{
Length = WriteTrailerWireFormat(dst, dstIndex + HeaderLength);
WriteHeaderWireFormat(dst, dstIndex);
return HeaderLength + Length;
}
/// <exception cref="System.IO.IOException"></exception>
internal virtual int ReadWireFormat(InputStream @in, byte[] buffer, int bufferIndex)
{
ReadHeaderWireFormat(@in, buffer, bufferIndex);
return HeaderLength + ReadTrailerWireFormat(@in, buffer, bufferIndex);
}
/// <exception cref="System.IO.IOException"></exception>
internal virtual int ReadWireFormat(InputStream @in, byte[] buffer, int bufferIndex
)
{
ReadHeaderWireFormat(@in, buffer, bufferIndex);
return HeaderLength + ReadTrailerWireFormat(@in, buffer, bufferIndex);
}
internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)Type);
if (Length > unchecked(0x0000FFFF))
{
dst[dstIndex] = unchecked(unchecked(0x01));
}
dstIndex++;
WriteInt2(Length, dst, dstIndex);
return HeaderLength;
}
internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
{
dst[dstIndex++] = unchecked((byte)Type);
if (Length > unchecked(0x0000FFFF))
{
dst[dstIndex] = unchecked(unchecked(0x01));
}
dstIndex++;
WriteInt2(Length, dst, dstIndex);
return HeaderLength;
}
/// <exception cref="System.IO.IOException"></exception>
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);
return HeaderLength;
}
/// <exception cref="System.IO.IOException"></exception>
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);
return HeaderLength;
}
internal abstract int WriteTrailerWireFormat(byte[] dst, int dstIndex);
internal abstract int WriteTrailerWireFormat(byte[] dst, int dstIndex);
/// <exception cref="System.IO.IOException"></exception>
internal abstract int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex);
}
/// <exception cref="System.IO.IOException"></exception>
internal abstract int ReadTrailerWireFormat(InputStream @in, byte[] buffer, int bufferIndex
);
}
}

View File

@ -16,181 +16,182 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Ntlmssp
{
/// <summary>Flags used during negotiation of NTLMSSP authentication.</summary>
/// <remarks>Flags used during negotiation of NTLMSSP authentication.</remarks>
public abstract class NtlmFlags
{
/// <summary>Indicates whether Unicode strings are supported or used.</summary>
/// <remarks>Indicates whether Unicode strings are supported or used.</remarks>
public const int NtlmsspNegotiateUnicode = unchecked(0x00000001);
/// <summary>Flags used during negotiation of NTLMSSP authentication.</summary>
/// <remarks>Flags used during negotiation of NTLMSSP authentication.</remarks>
public abstract class NtlmFlags
{
/// <summary>Indicates whether Unicode strings are supported or used.</summary>
/// <remarks>Indicates whether Unicode strings are supported or used.</remarks>
public const int NtlmsspNegotiateUnicode = unchecked(0x00000001);
/// <summary>Indicates whether OEM strings are supported or used.</summary>
/// <remarks>Indicates whether OEM strings are supported or used.</remarks>
public const int NtlmsspNegotiateOem = unchecked(0x00000002);
/// <summary>Indicates whether OEM strings are supported or used.</summary>
/// <remarks>Indicates whether OEM strings are supported or used.</remarks>
public const int NtlmsspNegotiateOem = unchecked(0x00000002);
/// <summary>
/// Indicates whether the authentication target is requested from
/// the server.
/// </summary>
/// <remarks>
/// Indicates whether the authentication target is requested from
/// the server.
/// </remarks>
public const int NtlmsspRequestTarget = unchecked(0x00000004);
/// <summary>
/// Indicates whether the authentication target is requested from
/// the server.
/// </summary>
/// <remarks>
/// Indicates whether the authentication target is requested from
/// the server.
/// </remarks>
public const int NtlmsspRequestTarget = unchecked(0x00000004);
/// <summary>
/// Specifies that communication across the authenticated channel
/// should carry a digital signature (message integrity).
/// </summary>
/// <remarks>
/// Specifies that communication across the authenticated channel
/// should carry a digital signature (message integrity).
/// </remarks>
public const int NtlmsspNegotiateSign = unchecked(0x00000010);
/// <summary>
/// Specifies that communication across the authenticated channel
/// should carry a digital signature (message integrity).
/// </summary>
/// <remarks>
/// Specifies that communication across the authenticated channel
/// should carry a digital signature (message integrity).
/// </remarks>
public const int NtlmsspNegotiateSign = unchecked(0x00000010);
/// <summary>
/// Specifies that communication across the authenticated channel
/// should be encrypted (message confidentiality).
/// </summary>
/// <remarks>
/// Specifies that communication across the authenticated channel
/// should be encrypted (message confidentiality).
/// </remarks>
public const int NtlmsspNegotiateSeal = unchecked(0x00000020);
/// <summary>
/// Specifies that communication across the authenticated channel
/// should be encrypted (message confidentiality).
/// </summary>
/// <remarks>
/// Specifies that communication across the authenticated channel
/// should be encrypted (message confidentiality).
/// </remarks>
public const int NtlmsspNegotiateSeal = unchecked(0x00000020);
/// <summary>Indicates datagram authentication.</summary>
/// <remarks>Indicates datagram authentication.</remarks>
public const int NtlmsspNegotiateDatagramStyle = unchecked(0x00000040);
/// <summary>Indicates datagram authentication.</summary>
/// <remarks>Indicates datagram authentication.</remarks>
public const int NtlmsspNegotiateDatagramStyle = unchecked(0x00000040);
/// <summary>
/// Indicates that the LAN Manager session key should be used for
/// signing and sealing authenticated communication.
/// </summary>
/// <remarks>
/// Indicates that the LAN Manager session key should be used for
/// signing and sealing authenticated communication.
/// </remarks>
public const int NtlmsspNegotiateLmKey = unchecked(0x00000080);
/// <summary>
/// Indicates that the LAN Manager session key should be used for
/// signing and sealing authenticated communication.
/// </summary>
/// <remarks>
/// Indicates that the LAN Manager session key should be used for
/// signing and sealing authenticated communication.
/// </remarks>
public const int NtlmsspNegotiateLmKey = unchecked(0x00000080);
public const int NtlmsspNegotiateNetware = unchecked(0x00000100);
public const int NtlmsspNegotiateNetware = unchecked(0x00000100);
/// <summary>Indicates support for NTLM authentication.</summary>
/// <remarks>Indicates support for NTLM authentication.</remarks>
public const int NtlmsspNegotiateNtlm = unchecked(0x00000200);
/// <summary>Indicates support for NTLM authentication.</summary>
/// <remarks>Indicates support for NTLM authentication.</remarks>
public const int NtlmsspNegotiateNtlm = unchecked(0x00000200);
/// <summary>
/// Indicates whether the OEM-formatted domain name in which the
/// client workstation has membership is supplied in the Type-1 message.
/// </summary>
/// <remarks>
/// Indicates whether the OEM-formatted domain name in which the
/// client workstation has membership is supplied in the Type-1 message.
/// This is used in the negotation of local authentication.
/// </remarks>
public const int NtlmsspNegotiateOemDomainSupplied = unchecked(0x00001000);
/// <summary>
/// Indicates whether the OEM-formatted domain name in which the
/// client workstation has membership is supplied in the Type-1 message.
/// </summary>
/// <remarks>
/// Indicates whether the OEM-formatted domain name in which the
/// client workstation has membership is supplied in the Type-1 message.
/// This is used in the negotation of local authentication.
/// </remarks>
public const int NtlmsspNegotiateOemDomainSupplied = unchecked(0x00001000);
/// <summary>
/// Indicates whether the OEM-formatted workstation name is supplied
/// in the Type-1 message.
/// </summary>
/// <remarks>
/// Indicates whether the OEM-formatted workstation name is supplied
/// in the Type-1 message. This is used in the negotiation of local
/// authentication.
/// </remarks>
public const int NtlmsspNegotiateOemWorkstationSupplied = unchecked(0x00002000);
/// <summary>
/// Indicates whether the OEM-formatted workstation name is supplied
/// in the Type-1 message.
/// </summary>
/// <remarks>
/// Indicates whether the OEM-formatted workstation name is supplied
/// in the Type-1 message. This is used in the negotiation of local
/// authentication.
/// </remarks>
public const int NtlmsspNegotiateOemWorkstationSupplied = unchecked(0x00002000);
/// <summary>
/// Sent by the server to indicate that the server and client are
/// on the same machine.
/// </summary>
/// <remarks>
/// Sent by the server to indicate that the server and client are
/// on the same machine. This implies that the server will include
/// a local security context handle in the Type 2 message, for
/// use in local authentication.
/// </remarks>
public const int NtlmsspNegotiateLocalCall = unchecked(0x00004000);
/// <summary>
/// Sent by the server to indicate that the server and client are
/// on the same machine.
/// </summary>
/// <remarks>
/// Sent by the server to indicate that the server and client are
/// on the same machine. This implies that the server will include
/// a local security context handle in the Type 2 message, for
/// use in local authentication.
/// </remarks>
public const int NtlmsspNegotiateLocalCall = unchecked(0x00004000);
/// <summary>
/// Indicates that authenticated communication between the client
/// and server should carry a "dummy" digital signature.
/// </summary>
/// <remarks>
/// Indicates that authenticated communication between the client
/// and server should carry a "dummy" digital signature.
/// </remarks>
public const int NtlmsspNegotiateAlwaysSign = unchecked(0x00008000);
/// <summary>
/// Indicates that authenticated communication between the client
/// and server should carry a "dummy" digital signature.
/// </summary>
/// <remarks>
/// Indicates that authenticated communication between the client
/// and server should carry a "dummy" digital signature.
/// </remarks>
public const int NtlmsspNegotiateAlwaysSign = unchecked(0x00008000);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a domain.
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a domain.
/// </remarks>
public const int NtlmsspTargetTypeDomain = unchecked(0x00010000);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a domain.
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a domain.
/// </remarks>
public const int NtlmsspTargetTypeDomain = unchecked(0x00010000);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a server.
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a server.
/// </remarks>
public const int NtlmsspTargetTypeServer = unchecked(0x00020000);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a server.
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a server.
/// </remarks>
public const int NtlmsspTargetTypeServer = unchecked(0x00020000);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a share (presumably for share-level
/// authentication).
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a share (presumably for share-level
/// authentication).
/// </remarks>
public const int NtlmsspTargetTypeShare = unchecked(0x00040000);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a share (presumably for share-level
/// authentication).
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that the
/// target authentication realm is a share (presumably for share-level
/// authentication).
/// </remarks>
public const int NtlmsspTargetTypeShare = unchecked(0x00040000);
/// <summary>
/// Indicates that the NTLM2 signing and sealing scheme should be used
/// for protecting authenticated communications.
/// </summary>
/// <remarks>
/// Indicates that the NTLM2 signing and sealing scheme should be used
/// for protecting authenticated communications. This refers to a
/// particular session security scheme, and is not related to the use
/// of NTLMv2 authentication.
/// </remarks>
public const int NtlmsspNegotiateNtlm2 = unchecked(0x00080000);
/// <summary>
/// Indicates that the NTLM2 signing and sealing scheme should be used
/// for protecting authenticated communications.
/// </summary>
/// <remarks>
/// Indicates that the NTLM2 signing and sealing scheme should be used
/// for protecting authenticated communications. This refers to a
/// particular session security scheme, and is not related to the use
/// of NTLMv2 authentication.
/// </remarks>
public const int NtlmsspNegotiateNtlm2 = unchecked(0x00080000);
public const int NtlmsspRequestInitResponse = unchecked(0x00100000);
public const int NtlmsspRequestInitResponse = unchecked(0x00100000);
public const int NtlmsspRequestAcceptResponse = unchecked(0x00200000);
public const int NtlmsspRequestAcceptResponse = unchecked(0x00200000);
public const int NtlmsspRequestNonNtSessionKey = unchecked(0x00400000);
public const int NtlmsspRequestNonNtSessionKey = unchecked(0x00400000
);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that it is
/// including a Target Information block in the message.
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that it is
/// including a Target Information block in the message. The Target
/// Information block is used in the calculation of the NTLMv2 response.
/// </remarks>
public const int NtlmsspNegotiateTargetInfo = unchecked(0x00800000);
/// <summary>
/// Sent by the server in the Type 2 message to indicate that it is
/// including a Target Information block in the message.
/// </summary>
/// <remarks>
/// Sent by the server in the Type 2 message to indicate that it is
/// including a Target Information block in the message. The Target
/// Information block is used in the calculation of the NTLMv2 response.
/// </remarks>
public const int NtlmsspNegotiateTargetInfo = unchecked(0x00800000);
/// <summary>Indicates that 128-bit encryption is supported.</summary>
/// <remarks>Indicates that 128-bit encryption is supported.</remarks>
public const int NtlmsspNegotiate128 = unchecked(0x20000000);
/// <summary>Indicates that 128-bit encryption is supported.</summary>
/// <remarks>Indicates that 128-bit encryption is supported.</remarks>
public const int NtlmsspNegotiate128 = unchecked(0x20000000);
public const int NtlmsspNegotiateKeyExch = unchecked(0x40000000);
public const int NtlmsspNegotiateKeyExch = unchecked(0x40000000);
/// <summary>Indicates that 56-bit encryption is supported.</summary>
/// <remarks>Indicates that 56-bit encryption is supported.</remarks>
public const int NtlmsspNegotiate56 = unchecked((int)(0x80000000));
}
/// <summary>Indicates that 56-bit encryption is supported.</summary>
/// <remarks>Indicates that 56-bit encryption is supported.</remarks>
public const int NtlmsspNegotiate56 = unchecked((int)(0x80000000));
}
}

View File

@ -18,137 +18,123 @@ using System;
namespace SharpCifs.Ntlmssp
{
/// <summary>Abstract superclass for all NTLMSSP messages.</summary>
/// <remarks>Abstract superclass for all NTLMSSP messages.</remarks>
public abstract class NtlmMessage : NtlmFlags
{
/// <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)
};
/// <summary>Abstract superclass for all NTLMSSP messages.</summary>
/// <remarks>Abstract superclass for all NTLMSSP messages.</remarks>
public abstract class NtlmMessage : NtlmFlags
{
/// <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) };
private static readonly string OemEncoding = Config.DefaultOemEncoding;
private static readonly string OemEncoding = Config.DefaultOemEncoding;
protected internal static readonly string UniEncoding = "UTF-16LE";
protected internal static readonly string UniEncoding = "UTF-16LE";
private int _flags;
private int _flags;
/// <summary>Returns the flags currently in use for this message.</summary>
/// <remarks>Returns the flags currently in use for this message.</remarks>
/// <returns>
/// An <code>int</code> containing the flags in use for this
/// message.
/// </returns>
public virtual int GetFlags()
{
return _flags;
}
/// <summary>Returns the flags currently in use for this message.</summary>
/// <remarks>Returns the flags currently in use for this message.</remarks>
/// <returns>
/// An <code>int</code> containing the flags in use for this
/// message.
/// </returns>
public virtual int GetFlags()
{
return _flags;
}
/// <summary>Sets the flags for this message.</summary>
/// <remarks>Sets the flags for this message.</remarks>
/// <param name="flags">The flags for this message.</param>
public virtual void SetFlags(int flags)
{
this._flags = flags;
}
/// <summary>Sets the flags for this message.</summary>
/// <remarks>Sets the flags for this message.</remarks>
/// <param name="flags">The flags for this message.</param>
public virtual void SetFlags(int flags)
{
this._flags = flags;
}
/// <summary>Returns the status of the specified flag.</summary>
/// <remarks>Returns the status of the specified flag.</remarks>
/// <param name="flag">The flag to test (i.e., <code>NTLMSSP_NEGOTIATE_OEM</code>).</param>
/// <returns>A <code>boolean</code> indicating whether the flag is set.</returns>
public virtual bool GetFlag(int flag)
{
return (GetFlags() & flag) != 0;
}
/// <summary>Returns the status of the specified flag.</summary>
/// <remarks>Returns the status of the specified flag.</remarks>
/// <param name="flag">The flag to test (i.e., <code>NTLMSSP_NEGOTIATE_OEM</code>).</param>
/// <returns>A <code>boolean</code> indicating whether the flag is set.</returns>
public virtual bool GetFlag(int flag)
{
return (GetFlags() & flag) != 0;
}
/// <summary>Sets or clears the specified flag.</summary>
/// <remarks>Sets or clears the specified flag.</remarks>
/// <param name="flag">
/// The flag to set/clear (i.e.,
/// <code>NTLMSSP_NEGOTIATE_OEM</code>).
/// </param>
/// <param name="value">
/// Indicates whether to set (<code>true</code>) or
/// clear (<code>false</code>) the specified flag.
/// </param>
public virtual void SetFlag(int flag, bool value)
{
SetFlags(value
? (GetFlags() | flag)
: (GetFlags() & (unchecked((int)(0xffffffff)) ^ flag)));
}
/// <summary>Sets or clears the specified flag.</summary>
/// <remarks>Sets or clears the specified flag.</remarks>
/// <param name="flag">
/// The flag to set/clear (i.e.,
/// <code>NTLMSSP_NEGOTIATE_OEM</code>).
/// </param>
/// <param name="value">
/// Indicates whether to set (<code>true</code>) or
/// clear (<code>false</code>) the specified flag.
/// </param>
public virtual void SetFlag(int flag, bool value)
{
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);
}
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);
}
internal static int ReadUShort(byte[] src, int index)
{
return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8);
}
internal static int ReadUShort(byte[] src, int index)
{
return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8);
}
internal static byte[] ReadSecurityBuffer(byte[] src, int index)
{
int length = ReadUShort(src, index);
int offset = ReadULong(src, index + 4);
byte[] buffer = new byte[length];
Array.Copy(src, offset, buffer, 0, length);
return buffer;
}
internal static byte[] ReadSecurityBuffer(byte[] src, int index)
{
int length = ReadUShort(src, index);
int offset = ReadULong(src, index + 4);
byte[] buffer = new byte[length];
Array.Copy(src, offset, buffer, 0, length);
return buffer;
}
internal static void WriteULong(byte[] dest, int offset, int value)
{
dest[offset] = unchecked((byte)(value & unchecked(0xff)));
internal static void WriteULong(byte[] dest, int offset, int value)
{
dest[offset] = unchecked((byte)(value & unchecked(0xff)));
dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff)));
dest[offset + 2] = unchecked((byte)(value >> 16 & unchecked(0xff)));
dest[offset + 3] = unchecked((byte)(value >> 24 & unchecked(0xff)));
}
internal static void WriteUShort(byte[] dest, int offset, int value)
{
dest[offset] = unchecked((byte)(value & unchecked(0xff)));
dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff)));
dest[offset + 2] = unchecked((byte)(value >> 16 & unchecked(0xff)));
dest[offset + 3] = unchecked((byte)(value >> 24 & unchecked(0xff)));
}
}
internal static void WriteUShort(byte[] dest, int offset, int value)
{
dest[offset] = unchecked((byte)(value & unchecked(0xff)));
dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff)));
}
internal static void WriteSecurityBuffer(byte[] dest, int offset, int bodyOffset,
byte[] src)
{
int length = (src != null) ? src.Length : 0;
if (length == 0)
{
return;
}
WriteUShort(dest, offset, length);
WriteUShort(dest, offset + 2, length);
WriteULong(dest, offset + 4, bodyOffset);
Array.Copy(src, 0, dest, bodyOffset, length);
}
internal static void WriteSecurityBuffer(byte[] dest,
int offset,
int bodyOffset,
byte[] src)
{
int length = (src != null)
? src.Length
: 0;
if (length == 0)
{
return;
}
WriteUShort(dest, offset, length);
WriteUShort(dest, offset + 2, length);
WriteULong(dest, offset + 4, bodyOffset);
Array.Copy(src, 0, dest, bodyOffset, length);
}
internal static string GetOemEncoding()
{
return OemEncoding;
}
internal static string GetOemEncoding()
{
return OemEncoding;
}
/// <summary>Returns the raw byte representation of this message.</summary>
/// <remarks>Returns the raw byte representation of this message.</remarks>
/// <returns>A <code>byte[]</code> containing the raw message material.</returns>
public abstract byte[] ToByteArray();
}
/// <summary>Returns the raw byte representation of this message.</summary>
/// <remarks>Returns the raw byte representation of this message.</remarks>
/// <returns>A <code>byte[]</code> containing the raw message material.</returns>
public abstract byte[] ToByteArray();
}
}

View File

@ -22,230 +22,228 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Ntlmssp
{
/// <summary>Represents an NTLMSSP Type-1 message.</summary>
/// <remarks>Represents an NTLMSSP Type-1 message.</remarks>
public class Type1Message : NtlmMessage
{
private static readonly int DefaultFlags;
/// <summary>Represents an NTLMSSP Type-1 message.</summary>
/// <remarks>Represents an NTLMSSP Type-1 message.</remarks>
public class Type1Message : NtlmMessage
{
private static readonly int DefaultFlags;
private static readonly string DefaultDomain;
private static readonly string DefaultDomain;
private static readonly string DefaultWorkstation;
private static readonly string DefaultWorkstation;
private string _suppliedDomain;
private string _suppliedDomain;
private string _suppliedWorkstation;
private string _suppliedWorkstation;
static Type1Message()
{
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode", true)
? NtlmsspNegotiateUnicode
: NtlmsspNegotiateOem);
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
string defaultWorkstation = null;
try
{
defaultWorkstation = NbtAddress.GetLocalHost().GetHostName();
}
catch (UnknownHostException)
{
}
DefaultWorkstation = defaultWorkstation;
}
static Type1Message()
{
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode"
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem);
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
string defaultWorkstation = null;
try
{
defaultWorkstation = NbtAddress.GetLocalHost().GetHostName();
}
catch (UnknownHostException)
{
}
DefaultWorkstation = defaultWorkstation;
}
/// <summary>
/// Creates a Type-1 message using default values from the current
/// environment.
/// </summary>
/// <remarks>
/// Creates a Type-1 message using default values from the current
/// environment.
/// </remarks>
public Type1Message() : this(GetDefaultFlags(),
GetDefaultDomain(),
GetDefaultWorkstation())
{
}
/// <summary>
/// Creates a Type-1 message using default values from the current
/// environment.
/// </summary>
/// <remarks>
/// Creates a Type-1 message using default values from the current
/// environment.
/// </remarks>
public Type1Message() : this(GetDefaultFlags(), GetDefaultDomain(), GetDefaultWorkstation
())
{
}
/// <summary>Creates a Type-1 message with the specified parameters.</summary>
/// <remarks>Creates a Type-1 message with the specified parameters.</remarks>
/// <param name="flags">The flags to apply to this message.</param>
/// <param name="suppliedDomain">The supplied authentication domain.</param>
/// <param name="suppliedWorkstation">The supplied workstation name.</param>
public Type1Message(int flags, string suppliedDomain, string suppliedWorkstation)
{
SetFlags(GetDefaultFlags() | flags);
SetSuppliedDomain(suppliedDomain);
if (suppliedWorkstation == null)
{
suppliedWorkstation = GetDefaultWorkstation();
}
SetSuppliedWorkstation(suppliedWorkstation);
}
/// <summary>Creates a Type-1 message with the specified parameters.</summary>
/// <remarks>Creates a Type-1 message with the specified parameters.</remarks>
/// <param name="flags">The flags to apply to this message.</param>
/// <param name="suppliedDomain">The supplied authentication domain.</param>
/// <param name="suppliedWorkstation">The supplied workstation name.</param>
public Type1Message(int flags, string suppliedDomain, string suppliedWorkstation)
{
SetFlags(GetDefaultFlags() | flags);
SetSuppliedDomain(suppliedDomain);
if (suppliedWorkstation == null)
{
suppliedWorkstation = GetDefaultWorkstation();
}
SetSuppliedWorkstation(suppliedWorkstation);
}
/// <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>
public Type1Message(byte[] material)
{
Parse(material);
}
/// <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>
public Type1Message(byte[] material)
{
Parse(material);
}
/// <summary>Returns the supplied authentication domain.</summary>
/// <remarks>Returns the supplied authentication domain.</remarks>
/// <returns>A <code>String</code> containing the supplied domain.</returns>
public virtual string GetSuppliedDomain()
{
return _suppliedDomain;
}
/// <summary>Returns the supplied authentication domain.</summary>
/// <remarks>Returns the supplied authentication domain.</remarks>
/// <returns>A <code>String</code> containing the supplied domain.</returns>
public virtual string GetSuppliedDomain()
{
return _suppliedDomain;
}
/// <summary>Sets the supplied authentication domain for this message.</summary>
/// <remarks>Sets the supplied authentication domain for this message.</remarks>
/// <param name="suppliedDomain">The supplied domain for this message.</param>
public virtual void SetSuppliedDomain(string suppliedDomain)
{
this._suppliedDomain = suppliedDomain;
}
/// <summary>Sets the supplied authentication domain for this message.</summary>
/// <remarks>Sets the supplied authentication domain for this message.</remarks>
/// <param name="suppliedDomain">The supplied domain for this message.</param>
public virtual void SetSuppliedDomain(string suppliedDomain)
{
this._suppliedDomain = suppliedDomain;
}
/// <summary>Returns the supplied workstation name.</summary>
/// <remarks>Returns the supplied workstation name.</remarks>
/// <returns>A <code>String</code> containing the supplied workstation name.</returns>
public virtual string GetSuppliedWorkstation()
{
return _suppliedWorkstation;
}
/// <summary>Returns the supplied workstation name.</summary>
/// <remarks>Returns the supplied workstation name.</remarks>
/// <returns>A <code>String</code> containing the supplied workstation name.</returns>
public virtual string GetSuppliedWorkstation()
{
return _suppliedWorkstation;
}
/// <summary>Sets the supplied workstation name for this message.</summary>
/// <remarks>Sets the supplied workstation name for this message.</remarks>
/// <param name="suppliedWorkstation">The supplied workstation for this message.</param>
public virtual void SetSuppliedWorkstation(string suppliedWorkstation)
{
this._suppliedWorkstation = suppliedWorkstation;
}
/// <summary>Sets the supplied workstation name for this message.</summary>
/// <remarks>Sets the supplied workstation name for this message.</remarks>
/// <param name="suppliedWorkstation">The supplied workstation for this message.</param>
public virtual void SetSuppliedWorkstation(string suppliedWorkstation)
{
this._suppliedWorkstation = suppliedWorkstation;
}
public override byte[] ToByteArray()
{
try
{
string suppliedDomain = GetSuppliedDomain();
string suppliedWorkstation = GetSuppliedWorkstation();
int flags = GetFlags();
bool hostInfo = false;
byte[] domain = new byte[0];
if (!string.IsNullOrEmpty(suppliedDomain))
{
hostInfo = true;
flags |= NtlmsspNegotiateOemDomainSupplied;
domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(),
GetOemEncoding());
}
else
{
flags &= (NtlmsspNegotiateOemDomainSupplied ^ unchecked((int)(0xffffffff)));
}
byte[] workstation = new byte[0];
if (!string.IsNullOrEmpty(suppliedWorkstation))
{
hostInfo = true;
flags |= NtlmsspNegotiateOemWorkstationSupplied;
workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(),
GetOemEncoding());
}
else
{
flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff)));
}
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);
if (hostInfo)
{
WriteSecurityBuffer(type1, 16, 32, domain);
WriteSecurityBuffer(type1, 24, 32 + domain.Length, workstation);
}
return type1;
}
catch (IOException ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public override byte[] ToByteArray()
{
try
{
string suppliedDomain = GetSuppliedDomain();
string suppliedWorkstation = GetSuppliedWorkstation();
int flags = GetFlags();
bool hostInfo = false;
byte[] domain = new byte[0];
if (!string.IsNullOrEmpty(suppliedDomain))
{
hostInfo = true;
flags |= NtlmsspNegotiateOemDomainSupplied;
domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(), GetOemEncoding
());
}
else
{
flags &= (NtlmsspNegotiateOemDomainSupplied ^ unchecked((int)(0xffffffff)));
}
byte[] workstation = new byte[0];
if (!string.IsNullOrEmpty(suppliedWorkstation))
{
hostInfo = true;
flags |= NtlmsspNegotiateOemWorkstationSupplied;
workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(), GetOemEncoding
());
}
else
{
flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff
)));
}
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);
if (hostInfo)
{
WriteSecurityBuffer(type1, 16, 32, domain);
WriteSecurityBuffer(type1, 24, 32 + domain.Length, workstation);
}
return type1;
}
catch (IOException ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public override string ToString()
{
string suppliedDomain = GetSuppliedDomain();
string suppliedWorkstation = GetSuppliedWorkstation();
return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null")
+ ",suppliedWorkstation=" + (suppliedWorkstation ?? "null")
+ ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
}
public override string ToString()
{
string suppliedDomain = GetSuppliedDomain();
string suppliedWorkstation = GetSuppliedWorkstation();
return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null"
) + ",suppliedWorkstation=" + (suppliedWorkstation ?? "null"
) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
}
/// <summary>
/// Returns the default flags for a generic Type-1 message in the
/// current environment.
/// </summary>
/// <remarks>
/// Returns the default flags for a generic Type-1 message in the
/// current environment.
/// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags()
{
return DefaultFlags;
}
/// <summary>
/// Returns the default flags for a generic Type-1 message in the
/// current environment.
/// </summary>
/// <remarks>
/// Returns the default flags for a generic Type-1 message in the
/// current environment.
/// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags()
{
return DefaultFlags;
}
/// <summary>Returns the default domain from the current environment.</summary>
/// <remarks>Returns the default domain from the current environment.</remarks>
/// <returns>A <code>String</code> containing the default domain.</returns>
public static string GetDefaultDomain()
{
return DefaultDomain;
}
/// <summary>Returns the default domain from the current environment.</summary>
/// <remarks>Returns the default domain from the current environment.</remarks>
/// <returns>A <code>String</code> containing the default domain.</returns>
public static string GetDefaultDomain()
{
return DefaultDomain;
}
/// <summary>Returns the default workstation from the current environment.</summary>
/// <remarks>Returns the default workstation from the current environment.</remarks>
/// <returns>A <code>String</code> containing the default workstation.</returns>
public static string GetDefaultWorkstation()
{
return DefaultWorkstation;
}
/// <summary>Returns the default workstation from the current environment.</summary>
/// <remarks>Returns the default workstation from the current environment.</remarks>
/// <returns>A <code>String</code> containing the default workstation.</returns>
public static string GetDefaultWorkstation()
{
return DefaultWorkstation;
}
/// <exception cref="System.IO.IOException"></exception>
private void Parse(byte[] material)
{
for (int i = 0; i < 8; i++)
{
if (material[i] != NtlmsspSignature[i])
{
throw new IOException("Not an NTLMSSP message.");
}
}
if (ReadULong(material, 8) != 1)
{
throw new IOException("Not a Type 1 message.");
}
int flags = ReadULong(material, 12);
string suppliedDomain = null;
if ((flags & NtlmsspNegotiateOemDomainSupplied) != 0)
{
byte[] domain = ReadSecurityBuffer(material, 16);
suppliedDomain = Runtime.GetStringForBytes(domain, GetOemEncoding());
}
string suppliedWorkstation = null;
if ((flags & NtlmsspNegotiateOemWorkstationSupplied) != 0)
{
byte[] workstation = ReadSecurityBuffer(material, 24);
suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding());
}
SetFlags(flags);
SetSuppliedDomain(suppliedDomain);
SetSuppliedWorkstation(suppliedWorkstation);
}
}
/// <exception cref="System.IO.IOException"></exception>
private void Parse(byte[] material)
{
for (int i = 0; i < 8; i++)
{
if (material[i] != NtlmsspSignature[i])
{
throw new IOException("Not an NTLMSSP message.");
}
}
if (ReadULong(material, 8) != 1)
{
throw new IOException("Not a Type 1 message.");
}
int flags = ReadULong(material, 12);
string suppliedDomain = null;
if ((flags & NtlmsspNegotiateOemDomainSupplied) != 0)
{
byte[] domain = ReadSecurityBuffer(material, 16);
suppliedDomain = Runtime.GetStringForBytes(domain, GetOemEncoding());
}
string suppliedWorkstation = null;
if ((flags & NtlmsspNegotiateOemWorkstationSupplied) != 0)
{
byte[] workstation = ReadSecurityBuffer(material, 24);
suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding
());
}
SetFlags(flags);
SetSuppliedDomain(suppliedDomain);
SetSuppliedWorkstation(suppliedWorkstation);
}
}
}

View File

@ -22,440 +22,417 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Ntlmssp
{
/// <summary>Represents an NTLMSSP Type-2 message.</summary>
/// <remarks>Represents an NTLMSSP Type-2 message.</remarks>
public class Type2Message : NtlmMessage
{
private static readonly int DefaultFlags;
/// <summary>Represents an NTLMSSP Type-2 message.</summary>
/// <remarks>Represents an NTLMSSP Type-2 message.</remarks>
public class Type2Message : NtlmMessage
{
private static readonly int DefaultFlags;
private static readonly string DefaultDomain;
private static readonly string DefaultDomain;
private static readonly byte[] DefaultTargetInformation;
private static readonly byte[] DefaultTargetInformation;
private byte[] _challenge;
private byte[] _challenge;
private string _target;
private string _target;
private byte[] _context;
private byte[] _context;
private byte[] _targetInformation;
private byte[] _targetInformation;
static Type2Message()
{
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)
{
try
{
domain = Runtime.GetBytesForString(DefaultDomain, UniEncoding);
}
catch (IOException)
{
}
}
int domainLength = domain.Length;
byte[] server = new byte[0];
try
{
string host = NbtAddress.GetLocalHost().GetHostName();
if (host != null)
{
try
{
server = Runtime.GetBytesForString(host, UniEncoding);
}
catch (IOException)
{
}
}
}
catch (UnknownHostException)
{
}
int serverLength = server.Length;
byte[] targetInfo = new byte[(domainLength > 0
? domainLength + 4
: 0)
+ (serverLength > 0
? serverLength + 4
: 0)
+ 4];
int offset = 0;
if (domainLength > 0)
{
WriteUShort(targetInfo, offset, 2);
offset += 2;
WriteUShort(targetInfo, offset, domainLength);
offset += 2;
Array.Copy(domain, 0, targetInfo, offset, domainLength);
offset += domainLength;
}
if (serverLength > 0)
{
WriteUShort(targetInfo, offset, 1);
offset += 2;
WriteUShort(targetInfo, offset, serverLength);
offset += 2;
Array.Copy(server, 0, targetInfo, offset, serverLength);
}
DefaultTargetInformation = targetInfo;
}
static Type2Message()
{
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)
{
try
{
domain = Runtime.GetBytesForString(DefaultDomain, UniEncoding);
}
catch (IOException)
{
}
}
int domainLength = domain.Length;
byte[] server = new byte[0];
try
{
string host = NbtAddress.GetLocalHost().GetHostName();
if (host != null)
{
try
{
server = Runtime.GetBytesForString(host, UniEncoding);
}
catch (IOException)
{
}
}
}
catch (UnknownHostException)
{
}
int serverLength = server.Length;
byte[] targetInfo = new byte[(domainLength > 0 ? domainLength + 4 : 0) + (serverLength
> 0 ? serverLength + 4 : 0) + 4];
int offset = 0;
if (domainLength > 0)
{
WriteUShort(targetInfo, offset, 2);
offset += 2;
WriteUShort(targetInfo, offset, domainLength);
offset += 2;
Array.Copy(domain, 0, targetInfo, offset, domainLength);
offset += domainLength;
}
if (serverLength > 0)
{
WriteUShort(targetInfo, offset, 1);
offset += 2;
WriteUShort(targetInfo, offset, serverLength);
offset += 2;
Array.Copy(server, 0, targetInfo, offset, serverLength);
}
DefaultTargetInformation = targetInfo;
}
/// <summary>
/// Creates a Type-2 message using default values from the current
/// environment.
/// </summary>
/// <remarks>
/// Creates a Type-2 message using default values from the current
/// environment.
/// </remarks>
public Type2Message() : this(GetDefaultFlags(), null, null)
{
}
/// <summary>
/// Creates a Type-2 message using default values from the current
/// environment.
/// </summary>
/// <remarks>
/// Creates a Type-2 message using default values from the current
/// environment.
/// </remarks>
public Type2Message() : this(GetDefaultFlags(), null, null)
{
}
/// <summary>
/// Creates a Type-2 message in response to the given Type-1 message
/// using default values from the current environment.
/// </summary>
/// <remarks>
/// Creates a Type-2 message in response to the given Type-1 message
/// using default values from the current environment.
/// </remarks>
/// <param name="type1">The Type-1 message which this represents a response to.</param>
public Type2Message(Type1Message type1) : this(type1, null, null)
{
}
/// <summary>
/// Creates a Type-2 message in response to the given Type-1 message
/// using default values from the current environment.
/// </summary>
/// <remarks>
/// Creates a Type-2 message in response to the given Type-1 message
/// using default values from the current environment.
/// </remarks>
/// <param name="type1">The Type-1 message which this represents a response to.</param>
public Type2Message(Type1Message type1) : this(type1, null, null)
{
}
/// <summary>Creates a Type-2 message in response to the given Type-1 message.</summary>
/// <remarks>Creates a Type-2 message in response to the given Type-1 message.</remarks>
/// <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)
{
}
/// <summary>Creates a Type-2 message in response to the given Type-1 message.</summary>
/// <remarks>Creates a Type-2 message in response to the given Type-1 message.</remarks>
/// <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)
{
}
/// <summary>Creates a Type-2 message with the specified parameters.</summary>
/// <remarks>Creates a Type-2 message with the specified parameters.</remarks>
/// <param name="flags">The flags to apply to this message.</param>
/// <param name="challenge">The challenge from the domain controller/server.</param>
/// <param name="target">The authentication target.</param>
public Type2Message(int flags, byte[] challenge, string target)
{
SetFlags(flags);
SetChallenge(challenge);
SetTarget(target);
if (target != null)
{
SetTargetInformation(GetDefaultTargetInformation());
}
}
/// <summary>Creates a Type-2 message with the specified parameters.</summary>
/// <remarks>Creates a Type-2 message with the specified parameters.</remarks>
/// <param name="flags">The flags to apply to this message.</param>
/// <param name="challenge">The challenge from the domain controller/server.</param>
/// <param name="target">The authentication target.</param>
public Type2Message(int flags, byte[] challenge, string target)
{
SetFlags(flags);
SetChallenge(challenge);
SetTarget(target);
if (target != null)
{
SetTargetInformation(GetDefaultTargetInformation());
}
}
/// <summary>Creates a Type-2 message using the given raw Type-2 material.</summary>
/// <remarks>Creates a Type-2 message using the given raw Type-2 material.</remarks>
/// <param name="material">The raw Type-2 material used to construct this message.</param>
/// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
/// </exception>
public Type2Message(byte[] material)
{
Parse(material);
}
/// <summary>Creates a Type-2 message using the given raw Type-2 material.</summary>
/// <remarks>Creates a Type-2 message using the given raw Type-2 material.</remarks>
/// <param name="material">The raw Type-2 material used to construct this message.</param>
/// <exception cref="System.IO.IOException">If an error occurs while parsing the material.
/// </exception>
public Type2Message(byte[] material)
{
Parse(material);
}
/// <summary>Returns the challenge for this message.</summary>
/// <remarks>Returns the challenge for this message.</remarks>
/// <returns>A <code>byte[]</code> containing the challenge.</returns>
public virtual byte[] GetChallenge()
{
return _challenge;
}
/// <summary>Returns the challenge for this message.</summary>
/// <remarks>Returns the challenge for this message.</remarks>
/// <returns>A <code>byte[]</code> containing the challenge.</returns>
public virtual byte[] GetChallenge()
{
return _challenge;
}
/// <summary>Sets the challenge for this message.</summary>
/// <remarks>Sets the challenge for this message.</remarks>
/// <param name="challenge">The challenge from the domain controller/server.</param>
public virtual void SetChallenge(byte[] challenge)
{
this._challenge = challenge;
}
/// <summary>Sets the challenge for this message.</summary>
/// <remarks>Sets the challenge for this message.</remarks>
/// <param name="challenge">The challenge from the domain controller/server.</param>
public virtual void SetChallenge(byte[] challenge)
{
this._challenge = challenge;
}
/// <summary>Returns the authentication target.</summary>
/// <remarks>Returns the authentication target.</remarks>
/// <returns>A <code>String</code> containing the authentication target.</returns>
public virtual string GetTarget()
{
return _target;
}
/// <summary>Returns the authentication target.</summary>
/// <remarks>Returns the authentication target.</remarks>
/// <returns>A <code>String</code> containing the authentication target.</returns>
public virtual string GetTarget()
{
return _target;
}
/// <summary>Sets the authentication target.</summary>
/// <remarks>Sets the authentication target.</remarks>
/// <param name="target">The authentication target.</param>
public virtual void SetTarget(string target)
{
this._target = target;
}
/// <summary>Sets the authentication target.</summary>
/// <remarks>Sets the authentication target.</remarks>
/// <param name="target">The authentication target.</param>
public virtual void SetTarget(string target)
{
this._target = target;
}
/// <summary>Returns the target information block.</summary>
/// <remarks>Returns the target information block.</remarks>
/// <returns>
/// A <code>byte[]</code> containing the target information block.
/// The target information block is used by the client to create an
/// NTLMv2 response.
/// </returns>
public virtual byte[] GetTargetInformation()
{
return _targetInformation;
}
/// <summary>Returns the target information block.</summary>
/// <remarks>Returns the target information block.</remarks>
/// <returns>
/// A <code>byte[]</code> containing the target information block.
/// The target information block is used by the client to create an
/// NTLMv2 response.
/// </returns>
public virtual byte[] GetTargetInformation()
{
return _targetInformation;
}
/// <summary>Sets the target information block.</summary>
/// <remarks>
/// Sets the target information block.
/// The target information block is used by the client to create
/// an NTLMv2 response.
/// </remarks>
/// <param name="targetInformation">The target information block.</param>
public virtual void SetTargetInformation(byte[] targetInformation)
{
this._targetInformation = targetInformation;
}
/// <summary>Sets the target information block.</summary>
/// <remarks>
/// Sets the target information block.
/// The target information block is used by the client to create
/// an NTLMv2 response.
/// </remarks>
/// <param name="targetInformation">The target information block.</param>
public virtual void SetTargetInformation(byte[] targetInformation)
{
this._targetInformation = targetInformation;
}
/// <summary>Returns the local security context.</summary>
/// <remarks>Returns the local security context.</remarks>
/// <returns>
/// A <code>byte[]</code> containing the local security
/// context. This is used by the client to negotiate local
/// authentication.
/// </returns>
public virtual byte[] GetContext()
{
return _context;
}
/// <summary>Returns the local security context.</summary>
/// <remarks>Returns the local security context.</remarks>
/// <returns>
/// A <code>byte[]</code> containing the local security
/// context. This is used by the client to negotiate local
/// authentication.
/// </returns>
public virtual byte[] GetContext()
{
return _context;
}
/// <summary>Sets the local security context.</summary>
/// <remarks>
/// Sets the local security context. This is used by the client
/// to negotiate local authentication.
/// </remarks>
/// <param name="context">The local security context.</param>
public virtual void SetContext(byte[] context)
{
this._context = context;
}
/// <summary>Sets the local security context.</summary>
/// <remarks>
/// Sets the local security context. This is used by the client
/// to negotiate local authentication.
/// </remarks>
/// <param name="context">The local security context.</param>
public virtual void SetContext(byte[] context)
{
this._context = context;
}
public override byte[] ToByteArray()
{
try
{
string targetName = GetTarget();
byte[] challenge = GetChallenge();
byte[] context = GetContext();
byte[] targetInformation = GetTargetInformation();
int flags = GetFlags();
byte[] target = new byte[0];
if ((flags & NtlmsspRequestTarget) != 0)
{
if (!string.IsNullOrEmpty(targetName))
{
target = (flags & NtlmsspNegotiateUnicode) != 0
? Runtime.GetBytesForString(targetName, UniEncoding)
: Runtime.GetBytesForString(targetName.ToUpper(), GetOemEncoding());
}
else
{
flags &= (unchecked((int)(0xffffffff)) ^ NtlmsspRequestTarget);
}
}
if (targetInformation != null)
{
flags |= NtlmsspNegotiateTargetInfo;
// empty context is needed for padding when t.i. is supplied.
if (context == null)
{
context = new byte[8];
}
}
int data = 32;
if (context != null)
{
data += 8;
}
if (targetInformation != null)
{
data += 8;
}
byte[] type2 = new byte[data
+ target.Length
+ (targetInformation != null
? targetInformation.Length
: 0)];
Array.Copy(NtlmsspSignature, 0, type2, 0, 8);
WriteULong(type2, 8, 2);
WriteSecurityBuffer(type2, 12, data, target);
WriteULong(type2, 20, flags);
Array.Copy(challenge ?? new byte[8], 0, type2, 24, 8);
if (context != null)
{
Array.Copy(context, 0, type2, 32, 8);
}
if (targetInformation != null)
{
WriteSecurityBuffer(type2, 40, data + target.Length, targetInformation);
}
return type2;
}
catch (IOException ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public override byte[] ToByteArray()
{
try
{
string targetName = GetTarget();
byte[] challenge = GetChallenge();
byte[] context = GetContext();
byte[] targetInformation = GetTargetInformation();
int flags = GetFlags();
byte[] target = new byte[0];
if ((flags & NtlmsspRequestTarget) != 0)
{
if (!string.IsNullOrEmpty(targetName))
{
target = (flags & NtlmsspNegotiateUnicode) != 0 ? Runtime.GetBytesForString
(targetName, UniEncoding) : Runtime.GetBytesForString(targetName.ToUpper
(), GetOemEncoding());
}
else
{
flags &= (unchecked((int)(0xffffffff)) ^ NtlmsspRequestTarget);
}
}
if (targetInformation != null)
{
flags |= NtlmsspNegotiateTargetInfo;
// empty context is needed for padding when t.i. is supplied.
if (context == null)
{
context = new byte[8];
}
}
int data = 32;
if (context != null)
{
data += 8;
}
if (targetInformation != null)
{
data += 8;
}
byte[] type2 = new byte[data + target.Length + (targetInformation != null ? targetInformation
.Length : 0)];
Array.Copy(NtlmsspSignature, 0, type2, 0, 8);
WriteULong(type2, 8, 2);
WriteSecurityBuffer(type2, 12, data, target);
WriteULong(type2, 20, flags);
Array.Copy(challenge ?? new byte[8], 0, type2, 24, 8);
if (context != null)
{
Array.Copy(context, 0, type2, 32, 8);
}
if (targetInformation != null)
{
WriteSecurityBuffer(type2, 40, data + target.Length, targetInformation);
}
return type2;
}
catch (IOException ex)
{
throw new InvalidOperationException(ex.Message);
}
}
public override string ToString()
{
string target = GetTarget();
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) + "]";
}
public override string ToString()
{
string target = GetTarget();
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) + "]";
}
/// <summary>
/// Returns the default flags for a generic Type-2 message in the
/// current environment.
/// </summary>
/// <remarks>
/// Returns the default flags for a generic Type-2 message in the
/// current environment.
/// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags()
{
return DefaultFlags;
}
/// <summary>
/// Returns the default flags for a generic Type-2 message in the
/// current environment.
/// </summary>
/// <remarks>
/// Returns the default flags for a generic Type-2 message in the
/// current environment.
/// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags()
{
return DefaultFlags;
}
/// <summary>
/// Returns the default flags for a Type-2 message created in response
/// to the given Type-1 message in the current environment.
/// </summary>
/// <remarks>
/// Returns the default flags for a Type-2 message created in response
/// to the given Type-1 message in the current environment.
/// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags(Type1Message type1)
{
if (type1 == null)
{
return DefaultFlags;
}
int flags = NtlmsspNegotiateNtlm;
int type1Flags = type1.GetFlags();
flags |= ((type1Flags & NtlmsspNegotiateUnicode) != 0)
? NtlmsspNegotiateUnicode
: NtlmsspNegotiateOem;
if ((type1Flags & NtlmsspRequestTarget) != 0)
{
string domain = GetDefaultDomain();
if (domain != null)
{
flags |= NtlmsspRequestTarget | NtlmsspTargetTypeDomain;
}
}
return flags;
}
/// <summary>
/// Returns the default flags for a Type-2 message created in response
/// to the given Type-1 message in the current environment.
/// </summary>
/// <remarks>
/// Returns the default flags for a Type-2 message created in response
/// to the given Type-1 message in the current environment.
/// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags(Type1Message type1)
{
if (type1 == null)
{
return DefaultFlags;
}
int flags = NtlmsspNegotiateNtlm;
int type1Flags = type1.GetFlags();
flags |= ((type1Flags & NtlmsspNegotiateUnicode) != 0) ? NtlmsspNegotiateUnicode
: NtlmsspNegotiateOem;
if ((type1Flags & NtlmsspRequestTarget) != 0)
{
string domain = GetDefaultDomain();
if (domain != null)
{
flags |= NtlmsspRequestTarget | NtlmsspTargetTypeDomain;
}
}
return flags;
}
/// <summary>Returns the default domain from the current environment.</summary>
/// <remarks>Returns the default domain from the current environment.</remarks>
/// <returns>A <code>String</code> containing the domain.</returns>
public static string GetDefaultDomain()
{
return DefaultDomain;
}
/// <summary>Returns the default domain from the current environment.</summary>
/// <remarks>Returns the default domain from the current environment.</remarks>
/// <returns>A <code>String</code> containing the domain.</returns>
public static string GetDefaultDomain()
{
return DefaultDomain;
}
public static byte[] GetDefaultTargetInformation()
{
return DefaultTargetInformation;
}
public static byte[] GetDefaultTargetInformation()
{
return DefaultTargetInformation;
}
/// <exception cref="System.IO.IOException"></exception>
private void Parse(byte[] material)
{
for (int i = 0; i < 8; i++)
{
if (material[i] != NtlmsspSignature[i])
{
throw new IOException("Not an NTLMSSP message.");
}
}
if (ReadULong(material, 8) != 2)
{
throw new IOException("Not a Type 2 message.");
}
int flags = ReadULong(material, 20);
SetFlags(flags);
string target = null;
byte[] bytes = ReadSecurityBuffer(material, 12);
if (bytes.Length != 0)
{
target = Runtime.GetStringForBytes(bytes,
((flags & NtlmsspNegotiateUnicode) != 0)
? UniEncoding
: GetOemEncoding());
}
SetTarget(target);
for (int i1 = 24; i1 < 32; i1++)
{
if (material[i1] != 0)
{
byte[] challenge = new byte[8];
Array.Copy(material, 24, challenge, 0, 8);
SetChallenge(challenge);
break;
}
}
int offset = ReadULong(material, 16);
// offset of targetname start
if (offset == 32 || material.Length == 32)
{
return;
}
for (int i2 = 32; i2 < 40; i2++)
{
if (material[i2] != 0)
{
byte[] context = new byte[8];
Array.Copy(material, 32, context, 0, 8);
SetContext(context);
break;
}
}
if (offset == 40 || material.Length == 40)
{
return;
}
bytes = ReadSecurityBuffer(material, 40);
if (bytes.Length != 0)
{
SetTargetInformation(bytes);
}
}
}
/// <exception cref="System.IO.IOException"></exception>
private void Parse(byte[] material)
{
for (int i = 0; i < 8; i++)
{
if (material[i] != NtlmsspSignature[i])
{
throw new IOException("Not an NTLMSSP message.");
}
}
if (ReadULong(material, 8) != 2)
{
throw new IOException("Not a Type 2 message.");
}
int flags = ReadULong(material, 20);
SetFlags(flags);
string target = null;
byte[] bytes = ReadSecurityBuffer(material, 12);
if (bytes.Length != 0)
{
target = Runtime.GetStringForBytes(bytes, ((flags & NtlmsspNegotiateUnicode
) != 0) ? UniEncoding : GetOemEncoding());
}
SetTarget(target);
for (int i1 = 24; i1 < 32; i1++)
{
if (material[i1] != 0)
{
byte[] challenge = new byte[8];
Array.Copy(material, 24, challenge, 0, 8);
SetChallenge(challenge);
break;
}
}
int offset = ReadULong(material, 16);
// offset of targetname start
if (offset == 32 || material.Length == 32)
{
return;
}
for (int i2 = 32; i2 < 40; i2++)
{
if (material[i2] != 0)
{
byte[] context = new byte[8];
Array.Copy(material, 32, context, 0, 8);
SetContext(context);
break;
}
}
if (offset == 40 || material.Length == 40)
{
return;
}
bytes = ReadSecurityBuffer(material, 40);
if (bytes.Length != 0)
{
SetTargetInformation(bytes);
}
}
}
}

View File

@ -19,272 +19,269 @@ using SharpCifs.Util;
namespace SharpCifs.Smb
{
/// <summary>
/// An Access Control Entry (ACE) is an element in a security descriptor
/// such as those associated with files and directories.
/// </summary>
/// <remarks>
/// An Access Control Entry (ACE) is an element in a security descriptor
/// such as those associated with files and directories. The Windows OS
/// determines which users have the necessary permissions to access objects
/// based on these entries.
/// <p>
/// To fully understand the information exposed by this class a description
/// of the access check algorithm used by Windows is required. The following
/// is a basic description of the algorithm. For a more complete description
/// we recommend reading the section on Access Control in Keith Brown's
/// "The .NET Developer's Guide to Windows Security" (which is also
/// available online).
/// <p>
/// Direct ACEs are evaluated first in order. The SID of the user performing
/// the operation and the desired access bits are compared to the SID
/// and access mask of each ACE. If the SID matches, the allow/deny flags
/// and access mask are considered. If the ACE is a "deny"
/// ACE and <i>any</i> of the desired access bits match bits in the access
/// mask of the ACE, the whole access check fails. If the ACE is an "allow"
/// ACE and <i>all</i> of the bits in the desired access bits match bits in
/// the access mask of the ACE, the access check is successful. Otherwise,
/// more ACEs are evaluated until all desired access bits (combined)
/// are "allowed". If all of the desired access bits are not "allowed"
/// the then same process is repeated for inherited ACEs.
/// <p>
/// For example, if user <tt>WNET\alice</tt> tries to open a file
/// with desired access bits <tt>0x00000003</tt> (<tt>FILE_READ_DATA |
/// FILE_WRITE_DATA</tt>) and the target file has the following security
/// descriptor ACEs:
/// <pre>
/// Allow WNET\alice 0x001200A9 Direct
/// Allow Administrators 0x001F01FF Inherited
/// Allow SYSTEM 0x001F01FF Inherited
/// </pre>
/// the access check would fail because the direct ACE has an access mask
/// of <tt>0x001200A9</tt> which doesn't have the
/// <tt>FILE_WRITE_DATA</tt> bit on (bit <tt>0x00000002</tt>). Actually, this isn't quite correct. If
/// <tt>WNET\alice</tt> is in the local <tt>Administrators</tt> group the access check
/// will succeed because the inherited ACE allows local <tt>Administrators</tt>
/// both <tt>FILE_READ_DATA</tt> and <tt>FILE_WRITE_DATA</tt> access.
/// </remarks>
public class Ace
{
public const int FileReadData = unchecked(0x00000001);
/// <summary>
/// An Access Control Entry (ACE) is an element in a security descriptor
/// such as those associated with files and directories.
/// </summary>
/// <remarks>
/// An Access Control Entry (ACE) is an element in a security descriptor
/// such as those associated with files and directories. The Windows OS
/// determines which users have the necessary permissions to access objects
/// based on these entries.
/// <p>
/// To fully understand the information exposed by this class a description
/// of the access check algorithm used by Windows is required. The following
/// is a basic description of the algorithm. For a more complete description
/// we recommend reading the section on Access Control in Keith Brown's
/// "The .NET Developer's Guide to Windows Security" (which is also
/// available online).
/// <p>
/// Direct ACEs are evaluated first in order. The SID of the user performing
/// the operation and the desired access bits are compared to the SID
/// and access mask of each ACE. If the SID matches, the allow/deny flags
/// and access mask are considered. If the ACE is a "deny"
/// ACE and <i>any</i> of the desired access bits match bits in the access
/// mask of the ACE, the whole access check fails. If the ACE is an "allow"
/// ACE and <i>all</i> of the bits in the desired access bits match bits in
/// the access mask of the ACE, the access check is successful. Otherwise,
/// more ACEs are evaluated until all desired access bits (combined)
/// are "allowed". If all of the desired access bits are not "allowed"
/// the then same process is repeated for inherited ACEs.
/// <p>
/// For example, if user <tt>WNET\alice</tt> tries to open a file
/// with desired access bits <tt>0x00000003</tt> (<tt>FILE_READ_DATA |
/// FILE_WRITE_DATA</tt>) and the target file has the following security
/// descriptor ACEs:
/// <pre>
/// Allow WNET\alice 0x001200A9 Direct
/// Allow Administrators 0x001F01FF Inherited
/// Allow SYSTEM 0x001F01FF Inherited
/// </pre>
/// the access check would fail because the direct ACE has an access mask
/// of <tt>0x001200A9</tt> which doesn't have the
/// <tt>FILE_WRITE_DATA</tt> bit on (bit <tt>0x00000002</tt>). Actually, this isn't quite correct. If
/// <tt>WNET\alice</tt> is in the local <tt>Administrators</tt> group the access check
/// will succeed because the inherited ACE allows local <tt>Administrators</tt>
/// both <tt>FILE_READ_DATA</tt> and <tt>FILE_WRITE_DATA</tt> access.
/// </remarks>
public class Ace
{
public const int FileReadData = unchecked(0x00000001);
public const int FileWriteData = unchecked(0x00000002);
public const int FileWriteData = unchecked(0x00000002);
public const int FileAppendData = unchecked(0x00000004);
public const int FileAppendData = unchecked(0x00000004);
public const int FileReadEa = unchecked(0x00000008);
public const int FileReadEa = unchecked(0x00000008);
public const int FileWriteEa = unchecked(0x00000010);
public const int FileWriteEa = unchecked(0x00000010);
public const int FileExecute = unchecked(0x00000020);
public const int FileExecute = unchecked(0x00000020);
public const int FileDelete = unchecked(0x00000040);
public const int FileDelete = unchecked(0x00000040);
public const int FileReadAttributes = unchecked(0x00000080);
public const int FileReadAttributes = unchecked(0x00000080);
public const int FileWriteAttributes = unchecked(0x00000100);
public const int FileWriteAttributes = unchecked(0x00000100);
public const int Delete = unchecked(0x00010000);
public const int Delete = unchecked(0x00010000);
public const int ReadControl = unchecked(0x00020000);
public const int ReadControl = unchecked(0x00020000);
public const int WriteDac = unchecked(0x00040000);
public const int WriteDac = unchecked(0x00040000);
public const int WriteOwner = unchecked(0x00080000);
public const int WriteOwner = unchecked(0x00080000);
public const int Synchronize = unchecked(0x00100000);
public const int Synchronize = unchecked(0x00100000);
public const int GenericAll = unchecked(0x10000000);
public const int GenericAll = unchecked(0x10000000);
public const int GenericExecute = unchecked(0x20000000);
public const int GenericExecute = unchecked(0x20000000);
public const int GenericWrite = unchecked(0x40000000);
public const int GenericWrite = unchecked(0x40000000);
public const int GenericRead = unchecked((int)(0x80000000));
public const int GenericRead = unchecked((int)(0x80000000));
public const int FlagsObjectInherit = unchecked(0x01);
public const int FlagsObjectInherit = unchecked(0x01);
public const int FlagsContainerInherit = unchecked(0x02);
public const int FlagsContainerInherit = unchecked(0x02);
public const int FlagsNoPropagate = unchecked(0x04);
public const int FlagsNoPropagate = unchecked(0x04);
public const int FlagsInheritOnly = unchecked(0x08);
public const int FlagsInheritOnly = unchecked(0x08);
public const int FlagsInherited = unchecked(0x10);
public const int FlagsInherited = unchecked(0x10);
internal bool Allow;
internal bool Allow;
internal int Flags;
internal int Flags;
internal int Access;
internal int Access;
internal Sid Sid;
internal Sid Sid;
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 16
// 17
// 18
// 19
// 20
// 28
// 29
// 30
// 31
/// <summary>Returns true if this ACE is an allow ACE and false if it is a deny ACE.</summary>
/// <remarks>Returns true if this ACE is an allow ACE and false if it is a deny ACE.</remarks>
public virtual bool IsAllow()
{
return Allow;
}
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 16
// 17
// 18
// 19
// 20
// 28
// 29
// 30
// 31
/// <summary>Returns true if this ACE is an allow ACE and false if it is a deny ACE.</summary>
/// <remarks>Returns true if this ACE is an allow ACE and false if it is a deny ACE.</remarks>
public virtual bool IsAllow()
{
return Allow;
}
/// <summary>Returns true if this ACE is an inherited ACE and false if it is a direct ACE.
/// </summary>
/// <remarks>
/// Returns true if this ACE is an inherited ACE and false if it is a direct ACE.
/// <p>
/// Note: For reasons not fully understood, <tt>FLAGS_INHERITED</tt> may
/// not be set within all security descriptors even though the ACE was in
/// face inherited. If an inherited ACE is added to a parent the Windows
/// ACL editor will rebuild all children ACEs and set this flag accordingly.
/// </remarks>
public virtual bool IsInherited()
{
return (Flags & FlagsInherited) != 0;
}
/// <summary>Returns true if this ACE is an inherited ACE and false if it is a direct ACE.
/// </summary>
/// <remarks>
/// Returns true if this ACE is an inherited ACE and false if it is a direct ACE.
/// <p>
/// Note: For reasons not fully understood, <tt>FLAGS_INHERITED</tt> may
/// not be set within all security descriptors even though the ACE was in
/// face inherited. If an inherited ACE is added to a parent the Windows
/// ACL editor will rebuild all children ACEs and set this flag accordingly.
/// </remarks>
public virtual bool IsInherited()
{
return (Flags & FlagsInherited) != 0;
}
/// <summary>Returns the flags for this ACE.</summary>
/// <remarks>
/// 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()
{
return Flags;
}
/// <summary>Returns the flags for this ACE.</summary>
/// <remarks>
/// 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()
{
return Flags;
}
/// <summary>
/// Returns the 'Apply To' text for inheritance of ACEs on
/// directories such as 'This folder, subfolder and files'.
/// </summary>
/// <remarks>
/// Returns the 'Apply To' text for inheritance of ACEs on
/// directories such as 'This folder, subfolder and files'. For
/// files the text is always 'This object only'.
/// </remarks>
public virtual string GetApplyToText()
{
switch (Flags & (FlagsObjectInherit | FlagsContainerInherit | FlagsInheritOnly))
{
case unchecked(0x00):
{
return "This folder only";
}
/// <summary>
/// Returns the 'Apply To' text for inheritance of ACEs on
/// directories such as 'This folder, subfolder and files'.
/// </summary>
/// <remarks>
/// Returns the 'Apply To' text for inheritance of ACEs on
/// directories such as 'This folder, subfolder and files'. For
/// files the text is always 'This object only'.
/// </remarks>
public virtual string GetApplyToText()
{
switch (Flags & (FlagsObjectInherit | FlagsContainerInherit | FlagsInheritOnly
))
{
case unchecked(0x00):
{
return "This folder only";
}
case unchecked(0x03):
{
return "This folder, subfolders and files";
}
case unchecked(0x03):
{
return "This folder, subfolders and files";
}
case unchecked(0x0B):
{
return "Subfolders and files only";
}
case unchecked(0x0B):
{
return "Subfolders and files only";
}
case unchecked(0x02):
{
return "This folder and subfolders";
}
case unchecked(0x02):
{
return "This folder and subfolders";
}
case unchecked(0x0A):
{
return "Subfolders only";
}
case unchecked(0x0A):
{
return "Subfolders only";
}
case unchecked(0x01):
{
return "This folder and files";
}
case unchecked(0x01):
{
return "This folder and files";
}
case unchecked(0x09):
{
return "Files only";
}
}
return "Invalid";
}
case unchecked(0x09):
{
return "Files only";
}
}
return "Invalid";
}
/// <summary>Returns the access mask accociated with this ACE.</summary>
/// <remarks>
/// Returns the access mask accociated with this ACE. Use the
/// constants for <tt>FILE_READ_DATA</tt>, <tt>FILE_WRITE_DATA</tt>,
/// <tt>READ_CONTROL</tt>, <tt>GENERIC_ALL</tt>, etc with bitwise
/// operators to determine which bits of the mask are on or off.
/// </remarks>
public virtual int GetAccessMask()
{
return Access;
}
/// <summary>Returns the access mask accociated with this ACE.</summary>
/// <remarks>
/// Returns the access mask accociated with this ACE. Use the
/// constants for <tt>FILE_READ_DATA</tt>, <tt>FILE_WRITE_DATA</tt>,
/// <tt>READ_CONTROL</tt>, <tt>GENERIC_ALL</tt>, etc with bitwise
/// operators to determine which bits of the mask are on or off.
/// </remarks>
public virtual int GetAccessMask()
{
return Access;
}
/// <summary>Return the SID associated with this ACE.</summary>
/// <remarks>Return the SID associated with this ACE.</remarks>
public virtual Sid GetSid()
{
return Sid;
}
/// <summary>Return the SID associated with this ACE.</summary>
/// <remarks>Return the SID associated with this ACE.</remarks>
public virtual Sid GetSid()
{
return Sid;
}
internal virtual int Decode(byte[] buf, int bi)
{
Allow = buf[bi++] == unchecked(unchecked(0x00));
Flags = buf[bi++] & unchecked(0xFF);
int size = ServerMessageBlock.ReadInt2(buf, bi);
bi += 2;
Access = ServerMessageBlock.ReadInt4(buf, bi);
bi += 4;
Sid = new Sid(buf, bi);
return size;
}
internal virtual int Decode(byte[] buf, int bi)
{
Allow = buf[bi++] == unchecked(unchecked(0x00));
Flags = buf[bi++] & unchecked(0xFF);
int size = ServerMessageBlock.ReadInt2(buf, bi);
bi += 2;
Access = ServerMessageBlock.ReadInt4(buf, bi);
bi += 4;
Sid = new Sid(buf, bi);
return size;
}
internal virtual void AppendCol(StringBuilder sb, string str, int width)
{
sb.Append(str);
int count = width - str.Length;
for (int i = 0; i < count; i++)
{
sb.Append(' ');
}
}
internal virtual void AppendCol(StringBuilder sb, string str, int width)
{
sb.Append(str);
int count = width - str.Length;
for (int i = 0; i < count; i++)
{
sb.Append(' ');
}
}
/// <summary>Return a string represeting this ACE.</summary>
/// <remarks>
/// Return a string represeting this ACE.
/// <p>
/// Note: This function should probably be changed to return SDDL
/// fragments but currently it does not.
/// </remarks>
public override string ToString()
{
int count;
int i;
string str;
StringBuilder sb = new StringBuilder();
sb.Append(IsAllow()
? "Allow "
: "Deny ");
AppendCol(sb, Sid.ToDisplayString(), 25);
sb.Append(" 0x").Append(Hexdump.ToHexString(Access, 8)).Append(' ');
sb.Append(IsInherited()
? "Inherited "
: "Direct ");
AppendCol(sb, GetApplyToText(), 34);
return sb.ToString();
}
}
/// <summary>Return a string represeting this ACE.</summary>
/// <remarks>
/// Return a string represeting this ACE.
/// <p>
/// Note: This function should probably be changed to return SDDL
/// fragments but currently it does not.
/// </remarks>
public override string ToString()
{
int count;
int i;
string str;
StringBuilder sb = new StringBuilder();
sb.Append(IsAllow() ? "Allow " : "Deny ");
AppendCol(sb, Sid.ToDisplayString(), 25);
sb.Append(" 0x").Append(Hexdump.ToHexString(Access, 8)).Append(' ');
sb.Append(IsInherited() ? "Inherited " : "Direct ");
AppendCol(sb, GetApplyToText(), 34);
return sb.ToString();
}
}
}

View File

@ -16,10 +16,10 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal interface IAllocInfo
{
long GetCapacity();
internal interface IAllocInfo
{
long GetCapacity();
long GetFree();
}
long GetFree();
}
}

View File

@ -19,202 +19,203 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal abstract class AndXServerMessageBlock : ServerMessageBlock
{
private const int AndxCommandOffset = 1;
internal abstract class AndXServerMessageBlock : ServerMessageBlock
{
private const int AndxCommandOffset = 1;
private const int AndxReservedOffset = 2;
private const int AndxReservedOffset = 2;
private const int AndxOffsetOffset = 3;
private const int AndxOffsetOffset = 3;
private byte _andxCommand = unchecked(unchecked(0xFF));
private byte _andxCommand = unchecked(unchecked(0xFF));
private int _andxOffset;
private int _andxOffset;
internal ServerMessageBlock Andx;
internal ServerMessageBlock Andx;
public AndXServerMessageBlock()
{
}
public AndXServerMessageBlock()
{
}
internal AndXServerMessageBlock(ServerMessageBlock andx)
{
if (andx != null)
{
this.Andx = andx;
_andxCommand = andx.Command;
}
}
internal AndXServerMessageBlock(ServerMessageBlock andx)
{
if (andx != null)
{
this.Andx = andx;
_andxCommand = andx.Command;
}
}
internal virtual int GetBatchLimit(byte command)
{
return 0;
}
internal virtual int GetBatchLimit(byte command)
{
return 0;
}
internal override int Encode(byte[] dst, int dstIndex)
{
int start = HeaderStart = dstIndex;
dstIndex += WriteHeaderWireFormat(dst, dstIndex);
dstIndex += WriteAndXWireFormat(dst, dstIndex);
Length = dstIndex - start;
if (Digest != null)
{
Digest.Sign(dst, HeaderStart, Length, this, Response);
}
return Length;
}
internal override int Encode(byte[] dst, int dstIndex)
{
int start = HeaderStart = dstIndex;
dstIndex += WriteHeaderWireFormat(dst, dstIndex);
dstIndex += WriteAndXWireFormat(dst, dstIndex);
Length = dstIndex - start;
if (Digest != null)
{
Digest.Sign(dst, HeaderStart, Length, this, Response);
}
return Length;
}
internal override int Decode(byte[] buffer, int bufferIndex)
{
int start = HeaderStart = bufferIndex;
bufferIndex += ReadHeaderWireFormat(buffer, bufferIndex);
bufferIndex += ReadAndXWireFormat(buffer, bufferIndex);
Length = bufferIndex - start;
return Length;
}
internal override int Decode(byte[] buffer, int bufferIndex)
{
int start = HeaderStart = bufferIndex;
bufferIndex += ReadHeaderWireFormat(buffer, bufferIndex);
bufferIndex += ReadAndXWireFormat(buffer, bufferIndex);
Length = bufferIndex - start;
return Length;
}
internal virtual int WriteAndXWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
WordCount = WriteParameterWordsWireFormat(dst, start + AndxOffsetOffset + 2);
WordCount += 4;
// for command, reserved, and offset
dstIndex += WordCount + 1;
WordCount /= 2;
dst[start] = unchecked((byte)(WordCount & unchecked(0xFF)));
ByteCount = WriteBytesWireFormat(dst, dstIndex + 2);
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))
{
_andxCommand = unchecked(unchecked(0xFF));
Andx = null;
dst[start + AndxCommandOffset] = unchecked(unchecked(0xFF));
dst[start + AndxReservedOffset] = unchecked(unchecked(0x00));
// dst[start + ANDX_OFFSET_OFFSET] = (byte)0x00;
// dst[start + ANDX_OFFSET_OFFSET + 1] = (byte)0x00;
dst[start + AndxOffsetOffset] = unchecked(unchecked(0xde));
dst[start + AndxOffsetOffset + 1] = unchecked(unchecked(0xde));
// andx not used; return
return dstIndex - start;
}
Andx.BatchLevel = BatchLevel + 1;
dst[start + AndxCommandOffset] = _andxCommand;
dst[start + AndxReservedOffset] = unchecked(unchecked(0x00));
_andxOffset = dstIndex - HeaderStart;
WriteInt2(_andxOffset, dst, start + AndxOffsetOffset);
Andx.UseUnicode = UseUnicode;
if (Andx is AndXServerMessageBlock)
{
Andx.Uid = Uid;
dstIndex += ((AndXServerMessageBlock)Andx).WriteAndXWireFormat(dst, dstIndex);
}
else
{
// the andx smb is not of type andx so lets just write it here and
// were done.
int andxStart = dstIndex;
Andx.WordCount = Andx.WriteParameterWordsWireFormat(dst, dstIndex);
dstIndex += Andx.WordCount + 1;
Andx.WordCount /= 2;
dst[andxStart] = 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)));
dstIndex += Andx.ByteCount;
}
return dstIndex - start;
}
internal virtual int WriteAndXWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
WordCount = WriteParameterWordsWireFormat(dst, start + AndxOffsetOffset + 2);
WordCount += 4;
// for command, reserved, and offset
dstIndex += WordCount + 1;
WordCount /= 2;
dst[start] = unchecked((byte)(WordCount & unchecked(0xFF)));
ByteCount = WriteBytesWireFormat(dst, dstIndex + 2);
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
))
{
_andxCommand = unchecked(unchecked(0xFF));
Andx = null;
dst[start + AndxCommandOffset] = unchecked(unchecked(0xFF));
dst[start + AndxReservedOffset] = unchecked(unchecked(0x00));
// dst[start + ANDX_OFFSET_OFFSET] = (byte)0x00;
// dst[start + ANDX_OFFSET_OFFSET + 1] = (byte)0x00;
dst[start + AndxOffsetOffset] = unchecked(unchecked(0xde));
dst[start + AndxOffsetOffset + 1] = unchecked(unchecked(0xde));
// andx not used; return
return dstIndex - start;
}
Andx.BatchLevel = BatchLevel + 1;
dst[start + AndxCommandOffset] = _andxCommand;
dst[start + AndxReservedOffset] = unchecked(unchecked(0x00));
_andxOffset = dstIndex - HeaderStart;
WriteInt2(_andxOffset, dst, start + AndxOffsetOffset);
Andx.UseUnicode = UseUnicode;
if (Andx is AndXServerMessageBlock)
{
Andx.Uid = Uid;
dstIndex += ((AndXServerMessageBlock)Andx).WriteAndXWireFormat(dst, dstIndex
);
}
else
{
// the andx smb is not of type andx so lets just write it here and
// were done.
int andxStart = dstIndex;
Andx.WordCount = Andx.WriteParameterWordsWireFormat(dst, dstIndex);
dstIndex += Andx.WordCount + 1;
Andx.WordCount /= 2;
dst[andxStart] = 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)
));
dstIndex += Andx.ByteCount;
}
return dstIndex - start;
}
internal virtual int ReadAndXWireFormat(byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
WordCount = buffer[bufferIndex++];
if (WordCount != 0)
{
_andxCommand = buffer[bufferIndex];
_andxOffset = ReadInt2(buffer, bufferIndex + 2);
if (_andxOffset == 0)
{
_andxCommand = unchecked(unchecked(0xFF));
}
if (WordCount > 2)
{
ReadParameterWordsWireFormat(buffer, bufferIndex + 4);
if (Command == SmbComNtCreateAndx && ((SmbComNtCreateAndXResponse)this).IsExtended)
{
WordCount += 8;
}
}
bufferIndex = start + 1 + (WordCount * 2);
}
ByteCount = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
if (ByteCount != 0)
{
int n;
n = ReadBytesWireFormat(buffer, bufferIndex);
bufferIndex += ByteCount;
}
if (ErrorCode != 0 || _andxCommand == unchecked(unchecked(0xFF)))
{
_andxCommand = unchecked(unchecked(0xFF));
Andx = null;
}
else
{
if (Andx == null)
{
_andxCommand = unchecked(unchecked(0xFF));
throw new RuntimeException("no andx command supplied with response");
}
bufferIndex = HeaderStart + _andxOffset;
Andx.HeaderStart = HeaderStart;
Andx.Command = _andxCommand;
Andx.ErrorCode = ErrorCode;
Andx.Flags = Flags;
Andx.Flags2 = Flags2;
Andx.Tid = Tid;
Andx.Pid = Pid;
Andx.Uid = Uid;
Andx.Mid = Mid;
Andx.UseUnicode = UseUnicode;
if (Andx is AndXServerMessageBlock)
{
bufferIndex += ((AndXServerMessageBlock)Andx).ReadAndXWireFormat(buffer,
bufferIndex);
}
else
{
buffer[bufferIndex++] = unchecked((byte)(Andx.WordCount & unchecked(0xFF)));
if (Andx.WordCount != 0)
{
if (Andx.WordCount > 2)
{
bufferIndex += Andx.ReadParameterWordsWireFormat(buffer, bufferIndex);
}
}
Andx.ByteCount = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
if (Andx.ByteCount != 0)
{
Andx.ReadBytesWireFormat(buffer, bufferIndex);
bufferIndex += Andx.ByteCount;
}
}
Andx.Received = true;
}
return bufferIndex - start;
}
internal virtual int ReadAndXWireFormat(byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
WordCount = buffer[bufferIndex++];
if (WordCount != 0)
{
_andxCommand = buffer[bufferIndex];
_andxOffset = ReadInt2(buffer, bufferIndex + 2);
if (_andxOffset == 0)
{
_andxCommand = unchecked(unchecked(0xFF));
}
if (WordCount > 2)
{
ReadParameterWordsWireFormat(buffer, bufferIndex + 4);
if (Command == SmbComNtCreateAndx && ((SmbComNtCreateAndXResponse)this).IsExtended)
{
WordCount += 8;
}
}
bufferIndex = start + 1 + (WordCount * 2);
}
ByteCount = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
if (ByteCount != 0)
{
int n;
n = ReadBytesWireFormat(buffer, bufferIndex);
bufferIndex += ByteCount;
}
if (ErrorCode != 0 || _andxCommand == unchecked(unchecked(0xFF)))
{
_andxCommand = unchecked(unchecked(0xFF));
Andx = null;
}
else
{
if (Andx == null)
{
_andxCommand = unchecked(unchecked(0xFF));
throw new RuntimeException("no andx command supplied with response");
}
bufferIndex = HeaderStart + _andxOffset;
Andx.HeaderStart = HeaderStart;
Andx.Command = _andxCommand;
Andx.ErrorCode = ErrorCode;
Andx.Flags = Flags;
Andx.Flags2 = Flags2;
Andx.Tid = Tid;
Andx.Pid = Pid;
Andx.Uid = Uid;
Andx.Mid = Mid;
Andx.UseUnicode = UseUnicode;
if (Andx is AndXServerMessageBlock)
{
bufferIndex += ((AndXServerMessageBlock)Andx).ReadAndXWireFormat(buffer
, bufferIndex);
}
else
{
buffer[bufferIndex++] = unchecked((byte)(Andx.WordCount & unchecked(0xFF))
);
if (Andx.WordCount != 0)
{
if (Andx.WordCount > 2)
{
bufferIndex += Andx.ReadParameterWordsWireFormat(buffer, bufferIndex);
}
}
Andx.ByteCount = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
if (Andx.ByteCount != 0)
{
Andx.ReadBytesWireFormat(buffer, bufferIndex);
bufferIndex += Andx.ByteCount;
}
}
Andx.Received = true;
}
return bufferIndex - start;
}
public override string ToString()
{
return base.ToString()
+ ",andxCommand=0x" + Hexdump.ToHexString(_andxCommand, 2)
+ ",andxOffset=" + _andxOffset;
}
}
public override string ToString()
{
return base.ToString() + ",andxCommand=0x" + Hexdump.ToHexString(_andxCommand
, 2) + ",andxOffset=" + _andxOffset;
}
}
}

View File

@ -16,63 +16,65 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
public class BufferCache
{
private static readonly int MaxBuffers = Config.GetInt("jcifs.smb.maxBuffers", 16);
public class BufferCache
{
private static readonly int MaxBuffers = Config.GetInt("jcifs.smb.maxBuffers", 16
);
internal static object[] Cache = new object[MaxBuffers];
internal static object[] Cache = new object[MaxBuffers];
private static int _freeBuffers;
private static int _freeBuffers;
public static byte[] GetBuffer()
{
lock (Cache)
{
byte[] buf;
if (_freeBuffers > 0)
{
for (int i = 0; i < MaxBuffers; i++)
{
if (Cache[i] != null)
{
buf = (byte[])Cache[i];
Cache[i] = null;
_freeBuffers--;
return buf;
}
}
}
buf = new byte[SmbComTransaction.TransactionBufSize];
return buf;
}
}
public static byte[] GetBuffer()
{
lock (Cache)
{
byte[] buf;
if (_freeBuffers > 0)
{
for (int i = 0; i < MaxBuffers; i++)
{
if (Cache[i] != null)
{
buf = (byte[])Cache[i];
Cache[i] = null;
_freeBuffers--;
return buf;
}
}
}
buf = new byte[SmbComTransaction.TransactionBufSize];
return buf;
}
}
internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse rsp)
{
lock (Cache)
{
req.TxnBuf = GetBuffer();
rsp.TxnBuf = GetBuffer();
}
}
internal static void GetBuffers(SmbComTransaction req, SmbComTransactionResponse
rsp)
{
lock (Cache)
{
req.TxnBuf = GetBuffer();
rsp.TxnBuf = GetBuffer();
}
}
public static void ReleaseBuffer(byte[] buf)
{
lock (Cache)
{
if (_freeBuffers < MaxBuffers)
{
for (int i = 0; i < MaxBuffers; i++)
{
if (Cache[i] == null)
{
Cache[i] = buf;
_freeBuffers++;
return;
}
}
}
}
}
}
public static void ReleaseBuffer(byte[] buf)
{
lock (Cache)
{
if (_freeBuffers < MaxBuffers)
{
for (int i = 0; i < MaxBuffers; i++)
{
if (Cache[i] == null)
{
Cache[i] = buf;
_freeBuffers++;
return;
}
}
}
}
}
}
}

View File

@ -20,374 +20,370 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
public class Dfs
{
internal class CacheEntry
{
internal long Expiration;
public class Dfs
{
internal class CacheEntry
{
internal long Expiration;
internal Hashtable Map;
internal Hashtable Map;
internal CacheEntry(long ttl)
{
if (ttl == 0)
{
ttl = Ttl;
}
Expiration = Runtime.CurrentTimeMillis() + ttl * 1000L;
Map = new Hashtable();
}
}
internal CacheEntry(long ttl)
{
if (ttl == 0)
{
ttl = Ttl;
}
Expiration = Runtime.CurrentTimeMillis() + ttl * 1000L;
Map = new Hashtable();
}
}
internal static LogStream Log = LogStream.GetInstance();
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);
internal static CacheEntry FalseEntry = new CacheEntry(0L);
internal CacheEntry Domains;
internal CacheEntry Domains;
internal CacheEntry Referrals;
internal CacheEntry Referrals;
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual Hashtable GetTrustedDomains(NtlmPasswordAuthentication auth)
{
if (Disabled || auth.Domain == "?")
{
return null;
}
if (Domains != null && Runtime.CurrentTimeMillis() > Domains.Expiration)
{
Domains = null;
}
if (Domains != null)
{
return Domains.Map;
}
try
{
UniAddress addr = UniAddress.GetByName(auth.Domain, true);
SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0);
CacheEntry entry = new CacheEntry(Ttl * 10L);
DfsReferral dr = trans.GetDfsReferrals(auth, string.Empty, 0);
if (dr != null)
{
DfsReferral start = dr;
do
{
string domain = dr.Server.ToLower();
entry.Map.Put(domain, new Hashtable());
dr = dr.Next;
}
while (dr != start);
Domains = entry;
return Domains.Map;
}
}
catch (IOException ioe)
{
if (Log.Level >= 3)
{
Runtime.PrintStackTrace(ioe, Log);
}
if (StrictView && ioe is SmbAuthException)
{
throw (SmbAuthException)ioe;
}
}
return null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual Hashtable GetTrustedDomains(NtlmPasswordAuthentication auth)
{
if (Disabled || auth.Domain == "?")
{
return null;
}
if (Domains != null && Runtime.CurrentTimeMillis() > Domains.Expiration)
{
Domains = null;
}
if (Domains != null)
{
return Domains.Map;
}
try
{
UniAddress addr = UniAddress.GetByName(auth.Domain, true);
SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0);
CacheEntry entry = new CacheEntry(Ttl * 10L);
DfsReferral dr = trans.GetDfsReferrals(auth, string.Empty, 0);
if (dr != null)
{
DfsReferral start = dr;
do
{
string domain = dr.Server.ToLower();
entry.Map.Put(domain, new Hashtable());
dr = dr.Next;
}
while (dr != start);
Domains = entry;
return Domains.Map;
}
}
catch (IOException ioe)
{
if (Log.Level >= 3)
{
Runtime.PrintStackTrace(ioe, Log);
}
if (StrictView && ioe is SmbAuthException)
{
throw (SmbAuthException)ioe;
}
}
return null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual bool IsTrustedDomain(string domain, NtlmPasswordAuthentication auth)
{
Hashtable domains = GetTrustedDomains(auth);
if (domains == null)
{
return false;
}
domain = domain.ToLower();
return domains.Get(domain) != null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual bool IsTrustedDomain(string domain, NtlmPasswordAuthentication auth
)
{
Hashtable domains = GetTrustedDomains(auth);
if (domains == null)
{
return false;
}
domain = domain.ToLower();
return domains.Get(domain) != null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual SmbTransport GetDc(string domain, NtlmPasswordAuthentication auth)
{
if (Disabled)
{
return null;
}
try
{
UniAddress addr = UniAddress.GetByName(domain, true);
SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0);
DfsReferral dr = trans.GetDfsReferrals(auth, "\\" + domain, 1);
if (dr != null)
{
DfsReferral start = dr;
IOException e = null;
do
{
try
{
addr = UniAddress.GetByName(dr.Server);
return SmbTransport.GetSmbTransport(addr, 0);
}
catch (IOException ioe)
{
e = ioe;
}
dr = dr.Next;
}
while (dr != start);
throw e;
}
}
catch (IOException ioe)
{
if (Log.Level >= 3)
{
Runtime.PrintStackTrace(ioe, Log);
}
if (StrictView && ioe is SmbAuthException)
{
throw (SmbAuthException)ioe;
}
}
return null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual SmbTransport GetDc(string domain, NtlmPasswordAuthentication auth)
{
if (Disabled)
{
return null;
}
try
{
UniAddress addr = UniAddress.GetByName(domain, true);
SmbTransport trans = SmbTransport.GetSmbTransport(addr, 0);
DfsReferral dr = trans.GetDfsReferrals(auth, "\\" + domain, 1);
if (dr != null)
{
DfsReferral start = dr;
IOException e = null;
do
{
try
{
addr = UniAddress.GetByName(dr.Server);
return SmbTransport.GetSmbTransport(addr, 0);
}
catch (IOException ioe)
{
e = ioe;
}
dr = dr.Next;
}
while (dr != start);
throw e;
}
}
catch (IOException ioe)
{
if (Log.Level >= 3)
{
Runtime.PrintStackTrace(ioe, Log);
}
if (StrictView && ioe is SmbAuthException)
{
throw (SmbAuthException)ioe;
}
}
return null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual DfsReferral GetReferral(SmbTransport trans,
string domain,
string root,
string path,
NtlmPasswordAuthentication auth)
{
if (Disabled)
{
return null;
}
try
{
string p = "\\" + domain + "\\" + root;
if (path != null)
{
p += path;
}
DfsReferral dr = trans.GetDfsReferrals(auth, p, 0);
if (dr != null)
{
return dr;
}
}
catch (IOException ioe)
{
if (Log.Level >= 4)
{
Runtime.PrintStackTrace(ioe, Log);
}
if (StrictView && ioe is SmbAuthException)
{
throw (SmbAuthException)ioe;
}
}
return null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual DfsReferral GetReferral(SmbTransport trans, string domain, string
root, string path, NtlmPasswordAuthentication auth)
{
if (Disabled)
{
return null;
}
try
{
string p = "\\" + domain + "\\" + root;
if (path != null)
{
p += path;
}
DfsReferral dr = trans.GetDfsReferrals(auth, p, 0);
if (dr != null)
{
return dr;
}
}
catch (IOException ioe)
{
if (Log.Level >= 4)
{
Runtime.PrintStackTrace(ioe, Log);
}
if (StrictView && ioe is SmbAuthException)
{
throw (SmbAuthException)ioe;
}
}
return null;
}
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual DfsReferral Resolve(string domain,
string root,
string path,
NtlmPasswordAuthentication auth)
{
lock (this)
{
DfsReferral dr = null;
long now = Runtime.CurrentTimeMillis();
if (Disabled || root.Equals("IPC$"))
{
return null;
}
Hashtable domains = GetTrustedDomains(auth);
if (domains != null)
{
domain = domain.ToLower();
Hashtable roots = (Hashtable)domains.Get(domain);
if (roots != null)
{
SmbTransport trans = null;
root = root.ToLower();
CacheEntry links = (CacheEntry)roots.Get(root);
if (links != null && now > links.Expiration)
{
//Sharpen.Collections.Remove(roots, root);
/// <exception cref="SharpCifs.Smb.SmbAuthException"></exception>
public virtual DfsReferral Resolve(string domain, string root, string path, NtlmPasswordAuthentication
auth)
{
lock (this)
{
DfsReferral dr = null;
long now = Runtime.CurrentTimeMillis();
if (Disabled || root.Equals("IPC$"))
{
return null;
}
Hashtable domains = GetTrustedDomains(auth);
if (domains != null)
{
domain = domain.ToLower();
Hashtable roots = (Hashtable)domains.Get(domain);
if (roots != null)
{
SmbTransport trans = null;
root = root.ToLower();
CacheEntry links = (CacheEntry)roots.Get(root);
if (links != null && now > links.Expiration)
{
//Sharpen.Collections.Remove(roots, root);
roots.Remove(root);
links = null;
}
if (links == null)
{
if ((trans = GetDc(domain, auth)) == null)
{
return null;
}
dr = GetReferral(trans, domain, root, path, auth);
if (dr != null)
{
int len = 1 + domain.Length + 1 + root.Length;
links = new CacheEntry(0L);
DfsReferral tmp = dr;
do
{
if (path == null)
{
// TODO: fix this
links = null;
}
if (links == null)
{
if ((trans = GetDc(domain, auth)) == null)
{
return null;
}
dr = GetReferral(trans, domain, root, path, auth);
if (dr != null)
{
int len = 1 + domain.Length + 1 + root.Length;
links = new CacheEntry(0L);
DfsReferral tmp = dr;
do
{
if (path == null)
{
// TODO: fix this
//tmp.map = links.map;
tmp.Key = "\\";
}
tmp.PathConsumed -= len;
tmp = tmp.Next;
}
while (tmp != dr);
if (dr.Key != null)
{
links.Map.Put(dr.Key, dr);
}
roots.Put(root, links);
}
else
{
if (path == null)
{
roots.Put(root, FalseEntry);
}
}
}
else
{
if (links == FalseEntry)
{
links = null;
}
}
if (links != null)
{
string link = "\\";
dr = (DfsReferral)links.Map.Get(link);
if (dr != null && now > dr.Expiration)
{
//Sharpen.Collections.Remove(links.map, link);
tmp.Key = "\\";
}
tmp.PathConsumed -= len;
tmp = tmp.Next;
}
while (tmp != dr);
if (dr.Key != null)
{
links.Map.Put(dr.Key, dr);
}
roots.Put(root, links);
}
else
{
if (path == null)
{
roots.Put(root, FalseEntry);
}
}
}
else
{
if (links == FalseEntry)
{
links = null;
}
}
if (links != null)
{
string link = "\\";
dr = (DfsReferral)links.Map.Get(link);
if (dr != null && now > dr.Expiration)
{
//Sharpen.Collections.Remove(links.map, link);
links.Map.Remove(link);
dr = null;
}
if (dr == null)
{
if (trans == null)
{
if ((trans = GetDc(domain, auth)) == null)
{
return null;
}
}
dr = GetReferral(trans, domain, root, path, auth);
if (dr != null)
{
dr.PathConsumed -= 1 + domain.Length + 1 + root.Length;
dr.Link = link;
links.Map.Put(link, dr);
}
}
}
}
}
if (dr == null && path != null)
{
if (Referrals != null && now > Referrals.Expiration)
{
Referrals = null;
}
if (Referrals == null)
{
Referrals = new CacheEntry(0);
}
string key = "\\" + domain + "\\" + root;
if (path.Equals("\\") == false)
{
key += path;
}
key = key.ToLower();
//ListIterator<object> iter = new ListIterator<object>(referrals.map.Keys.GetEnumerator(), 0);
dr = null;
}
if (dr == null)
{
if (trans == null)
{
if ((trans = GetDc(domain, auth)) == null)
{
return null;
}
}
dr = GetReferral(trans, domain, root, path, auth);
if (dr != null)
{
dr.PathConsumed -= 1 + domain.Length + 1 + root.Length;
dr.Link = link;
links.Map.Put(link, dr);
}
}
}
}
}
if (dr == null && path != null)
{
if (Referrals != null && now > Referrals.Expiration)
{
Referrals = null;
}
if (Referrals == null)
{
Referrals = new CacheEntry(0);
}
string key = "\\" + domain + "\\" + root;
if (path.Equals("\\") == false)
{
key += path;
}
key = key.ToLower();
//ListIterator<object> iter = new ListIterator<object>(referrals.map.Keys.GetEnumerator(), 0);
foreach (var current in Referrals.Map.Keys)
{
string _key = (string)current;
int klen = _key.Length;
bool match = false;
if (klen == key.Length)
{
match = _key.Equals(key);
}
else
{
if (klen < key.Length)
{
match = _key.RegionMatches(false, 0, key, 0, klen) && key[klen] == '\\';
}
}
if (match)
{
dr = (DfsReferral)Referrals.Map.Get(_key);
}
}
}
return dr;
}
}
int klen = _key.Length;
bool match = false;
if (klen == key.Length)
{
match = _key.Equals(key);
}
else
{
if (klen < key.Length)
{
match = _key.RegionMatches(false, 0, key, 0, klen) && key[klen] == '\\';
}
}
if (match)
{
dr = (DfsReferral)Referrals.Map.Get(_key);
}
}
}
return dr;
}
}
internal virtual void Insert(string path, DfsReferral dr)
{
lock (this)
{
int s1;
int s2;
string server;
string share;
string key;
if (Disabled)
{
return;
}
s1 = path.IndexOf('\\', 1);
s2 = path.IndexOf('\\', s1 + 1);
server = Runtime.Substring(path, 1, s1);
share = Runtime.Substring(path, s1 + 1, s2);
key = Runtime.Substring(path, 0, dr.PathConsumed).ToLower();
int ki = key.Length;
while (ki > 1 && key[ki - 1] == '\\')
{
ki--;
}
if (ki < key.Length)
{
key = Runtime.Substring(key, 0, ki);
}
dr.PathConsumed -= 1 + server.Length + 1 + share.Length;
if (Referrals != null && (Runtime.CurrentTimeMillis() + 10000) > Referrals.Expiration)
{
Referrals = null;
}
if (Referrals == null)
{
Referrals = new CacheEntry(0);
}
Referrals.Map.Put(key, dr);
}
}
}
internal virtual void Insert(string path, DfsReferral dr)
{
lock (this)
{
int s1;
int s2;
string server;
string share;
string key;
if (Disabled)
{
return;
}
s1 = path.IndexOf('\\', 1);
s2 = path.IndexOf('\\', s1 + 1);
server = Runtime.Substring(path, 1, s1);
share = Runtime.Substring(path, s1 + 1, s2);
key = Runtime.Substring(path, 0, dr.PathConsumed).ToLower();
int ki = key.Length;
while (ki > 1 && key[ki - 1] == '\\')
{
ki--;
}
if (ki < key.Length)
{
key = Runtime.Substring(key, 0, ki);
}
dr.PathConsumed -= 1 + server.Length + 1 + share.Length;
if (Referrals != null && (Runtime.CurrentTimeMillis() + 10000) > Referrals.Expiration)
{
Referrals = null;
}
if (Referrals == null)
{
Referrals = new CacheEntry(0);
}
Referrals.Map.Put(key, dr);
}
}
}
}

View File

@ -18,55 +18,50 @@ using System.Collections.Generic;
namespace SharpCifs.Smb
{
public class DfsReferral : SmbException
{
public int PathConsumed;
public class DfsReferral : SmbException
{
public int PathConsumed;
public long Ttl;
public long Ttl;
public string Server;
public string Server;
public string Share;
public string Share;
public string Link;
public string Link;
public string Path;
public string Path;
public bool ResolveHashes;
public bool ResolveHashes;
public long Expiration;
public long Expiration;
internal DfsReferral Next;
internal DfsReferral Next;
internal IDictionary<string, DfsReferral> Map;
internal IDictionary<string, DfsReferral> Map;
internal string Key = null;
internal string Key = null;
public DfsReferral()
{
// Server
// Share
// Path relative to tree from which this referral was thrown
Next = this;
}
public DfsReferral()
{
// Server
// Share
// Path relative to tree from which this referral was thrown
Next = this;
}
internal virtual void Append(DfsReferral dr)
{
dr.Next = Next;
Next = dr;
}
internal virtual void Append(DfsReferral dr)
{
dr.Next = Next;
Next = dr;
}
public override string ToString()
{
return "DfsReferral[pathConsumed=" + PathConsumed
+ ",server=" + Server
+ ",share=" + Share
+ ",link=" + Link
+ ",path=" + Path
+ ",ttl=" + Ttl
+ ",expiration=" + Expiration
+ ",resolveHashes=" + ResolveHashes + "]";
}
}
public override string ToString()
{
return "DfsReferral[pathConsumed=" + PathConsumed + ",server=" + Server + ",share="
+ Share + ",link=" + Link + ",path=" + Path + ",ttl=" + Ttl + ",expiration=" +
Expiration + ",resolveHashes=" + ResolveHashes + "]";
}
}
}

View File

@ -16,94 +16,49 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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 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 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."
};
}
}

View File

@ -16,22 +16,22 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
public class DosFileFilter : ISmbFileFilter
{
protected internal string Wildcard;
public class DosFileFilter : ISmbFileFilter
{
protected internal string Wildcard;
protected internal int Attributes;
protected internal int Attributes;
public DosFileFilter(string wildcard, int attributes)
{
this.Wildcard = wildcard;
this.Attributes = attributes;
}
public DosFileFilter(string wildcard, int attributes)
{
this.Wildcard = wildcard;
this.Attributes = attributes;
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public virtual bool Accept(SmbFile file)
{
return (file.GetAttributes() & Attributes) != 0;
}
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public virtual bool Accept(SmbFile file)
{
return (file.GetAttributes() & Attributes) != 0;
}
}
}

View File

@ -16,18 +16,18 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
public interface IFileEntry
{
string GetName();
public interface IFileEntry
{
string GetName();
int GetType();
int GetType();
int GetAttributes();
int GetAttributes();
long CreateTime();
long CreateTime();
long LastModified();
long LastModified();
long Length();
}
long Length();
}
}

View File

@ -16,14 +16,14 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal interface IInfo
{
int GetAttributes();
internal interface IInfo
{
int GetAttributes();
long GetCreateTime();
long GetCreateTime();
long GetLastWriteTime();
long GetLastWriteTime();
long GetSize();
}
long GetSize();
}
}

View File

@ -19,109 +19,104 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class NetServerEnum2 : SmbComTransaction
{
internal const int SvTypeAll = unchecked((int)(0xFFFFFFFF));
internal class NetServerEnum2 : SmbComTransaction
{
internal const int SvTypeAll = unchecked((int)(0xFFFFFFFF));
internal const int SvTypeDomainEnum = unchecked((int)(0x80000000));
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;
internal string Domain;
internal string LastName;
internal string LastName;
internal int ServerTypes;
internal int ServerTypes;
internal NetServerEnum2(string domain, int serverTypes)
{
this.Domain = domain;
this.ServerTypes = serverTypes;
Command = SmbComTransaction;
SubCommand = NetServerEnum2;
// not really true be used by upper logic
Name = "\\PIPE\\LANMAN";
MaxParameterCount = 8;
MaxDataCount = 16384;
MaxSetupCount = unchecked(unchecked(0x00));
SetupCount = 0;
Timeout = 5000;
}
internal NetServerEnum2(string domain, int serverTypes)
{
this.Domain = domain;
this.ServerTypes = serverTypes;
Command = SmbComTransaction;
SubCommand = NetServerEnum2;
// not really true be used by upper logic
Name = "\\PIPE\\LANMAN";
MaxParameterCount = 8;
MaxDataCount = 16384;
MaxSetupCount = unchecked(unchecked(0x00));
SetupCount = 0;
Timeout = 5000;
}
internal override void Reset(int key, string lastName)
{
base.Reset();
this.LastName = lastName;
}
internal override void Reset(int key, string lastName)
{
base.Reset();
this.LastName = lastName;
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
byte[] descr;
int which = SubCommand == NetServerEnum2 ? 0 : 1;
try
{
descr = Runtime.GetBytesForString(Descr[which], "UTF-8"); //"ASCII");
}
catch (UnsupportedEncodingException)
{
return 0;
}
WriteInt2(SubCommand & unchecked(0xFF), dst, dstIndex);
dstIndex += 2;
Array.Copy(descr, 0, dst, dstIndex, descr.Length);
dstIndex += descr.Length;
WriteInt2(unchecked(0x0001), dst, dstIndex);
dstIndex += 2;
WriteInt2(MaxDataCount, dst, dstIndex);
dstIndex += 2;
WriteInt4(ServerTypes, dst, dstIndex);
dstIndex += 4;
dstIndex += WriteString(Domain.ToUpper(), dst, dstIndex, false);
if (which == 1)
{
dstIndex += WriteString(LastName.ToUpper(), dst, dstIndex, false);
}
return dstIndex - start;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
byte[] descr;
int which = SubCommand == NetServerEnum2 ? 0 : 1;
try
{
descr = Runtime.GetBytesForString(Descr[which], "UTF-8"); //"ASCII");
}
catch (UnsupportedEncodingException)
{
return 0;
}
WriteInt2(SubCommand & unchecked(0xFF), dst, dstIndex);
dstIndex += 2;
Array.Copy(descr, 0, dst, dstIndex, descr.Length);
dstIndex += descr.Length;
WriteInt2(unchecked(0x0001), dst, dstIndex);
dstIndex += 2;
WriteInt2(MaxDataCount, dst, dstIndex);
dstIndex += 2;
WriteInt4(ServerTypes, dst, dstIndex);
dstIndex += 4;
dstIndex += WriteString(Domain.ToUpper(), dst, dstIndex, false);
if (which == 1)
{
dstIndex += WriteString(LastName.ToUpper(), dst, dstIndex, false);
}
return dstIndex - start;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
return 0;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
public override string ToString()
{
return "NetServerEnum2["
+ base.ToString()
+ ",name=" + Name
+ ",serverTypes=" + (ServerTypes == SvTypeAll
? "SV_TYPE_ALL"
: "SV_TYPE_DOMAIN_ENUM") + "]";
}
}
public override string ToString()
{
return "NetServerEnum2[" + base.ToString() + ",name=" + Name + ",serverTypes="
+ (ServerTypes == SvTypeAll ? "SV_TYPE_ALL" : "SV_TYPE_DOMAIN_ENUM") + "]";
}
}
}

View File

@ -18,148 +18,140 @@ using SharpCifs.Util;
namespace SharpCifs.Smb
{
internal class NetServerEnum2Response : SmbComTransactionResponse
{
internal class ServerInfo1 : IFileEntry
{
internal string Name;
internal class NetServerEnum2Response : SmbComTransactionResponse
{
internal class ServerInfo1 : IFileEntry
{
internal string Name;
internal int VersionMajor;
internal int VersionMajor;
internal int VersionMinor;
internal int VersionMinor;
internal int Type;
internal int Type;
internal string CommentOrMasterBrowser;
internal string CommentOrMasterBrowser;
public virtual string GetName()
{
return Name;
}
public virtual string GetName()
{
return Name;
}
public new virtual int GetType()
{
return (Type & unchecked((int)(0x80000000))) != 0
? SmbFile.TypeWorkgroup
: SmbFile.TypeServer;
}
public new virtual int GetType()
{
return (Type & unchecked((int)(0x80000000))) != 0 ? SmbFile.TypeWorkgroup :
SmbFile.TypeServer;
}
public virtual int GetAttributes()
{
return SmbFile.AttrReadonly | SmbFile.AttrDirectory;
}
public virtual int GetAttributes()
{
return SmbFile.AttrReadonly | SmbFile.AttrDirectory;
}
public virtual long CreateTime()
{
return 0L;
}
public virtual long CreateTime()
{
return 0L;
}
public virtual long LastModified()
{
return 0L;
}
public virtual long LastModified()
{
return 0L;
}
public virtual long Length()
{
return 0L;
}
public virtual long Length()
{
return 0L;
}
public override string ToString()
{
return "ServerInfo1["
+ "name=" + Name
+ ",versionMajor=" + VersionMajor
+ ",versionMinor=" + VersionMinor
+ ",type=0x" + Hexdump.ToHexString(Type, 8)
+ ",commentOrMasterBrowser=" + CommentOrMasterBrowser + "]";
}
public override string ToString()
{
return "ServerInfo1[" + "name=" + Name + ",versionMajor=" + VersionMajor + ",versionMinor=" + VersionMinor + ",type=0x" + Hexdump.ToHexString
(Type, 8) + ",commentOrMasterBrowser=" + CommentOrMasterBrowser + "]";
}
internal ServerInfo1(NetServerEnum2Response enclosing)
{
this._enclosing = enclosing;
}
internal ServerInfo1(NetServerEnum2Response enclosing)
{
this._enclosing = enclosing;
}
private readonly NetServerEnum2Response _enclosing;
}
private readonly NetServerEnum2Response _enclosing;
}
private int _converter;
private int _converter;
private int _totalAvailableEntries;
private int _totalAvailableEntries;
internal string LastName;
internal string LastName;
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
Status = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_converter = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
NumEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_totalAvailableEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
return bufferIndex - start;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
int start = bufferIndex;
Status = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_converter = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
NumEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_totalAvailableEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
return bufferIndex - start;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
ServerInfo1 e = null;
Results = new ServerInfo1[NumEntries];
for (int i = 0; i < NumEntries; i++)
{
Results[i] = e = new ServerInfo1(this);
e.Name = ReadString(buffer, bufferIndex, 16, false);
bufferIndex += 16;
e.VersionMajor = buffer[bufferIndex++] & unchecked(0xFF);
e.VersionMinor = buffer[bufferIndex++] & unchecked(0xFF);
e.Type = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
int off = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
off = (off & unchecked(0xFFFF)) - _converter;
off = start + off;
e.CommentOrMasterBrowser = ReadString(buffer, off, 48, false);
if (Log.Level >= 4)
{
Log.WriteLine(e);
}
}
LastName = NumEntries == 0 ? null : e.Name;
return bufferIndex - start;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
ServerInfo1 e = null;
Results = new ServerInfo1[NumEntries];
for (int i = 0; i < NumEntries; i++)
{
Results[i] = e = new ServerInfo1(this);
e.Name = ReadString(buffer, bufferIndex, 16, false);
bufferIndex += 16;
e.VersionMajor = buffer[bufferIndex++] & unchecked(0xFF);
e.VersionMinor = buffer[bufferIndex++] & unchecked(0xFF);
e.Type = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
int off = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
off = (off & unchecked(0xFFFF)) - _converter;
off = start + off;
e.CommentOrMasterBrowser = ReadString(buffer, off, 48, false);
if (Log.Level >= 4)
{
Log.WriteLine(e);
}
}
LastName = NumEntries == 0 ? null : e.Name;
return bufferIndex - start;
}
public override string ToString()
{
return "NetServerEnum2Response["
+ base.ToString()
+ ",status=" + Status
+ ",converter=" + _converter
+ ",entriesReturned=" + NumEntries
+ ",totalAvailableEntries=" + _totalAvailableEntries
+ ",lastName=" + LastName + "]";
}
}
public override string ToString()
{
return "NetServerEnum2Response[" + base.ToString() + ",status=" + Status
+ ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries="
+ _totalAvailableEntries + ",lastName=" + LastName + "]";
}
}
}

View File

@ -19,75 +19,77 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class NetShareEnum : SmbComTransaction
{
private static readonly string Descr = "WrLeh\u0000B13BWz\u0000";
internal class NetShareEnum : SmbComTransaction
{
private static readonly string Descr = "WrLeh\u0000B13BWz\u0000";
public NetShareEnum()
{
Command = SmbComTransaction;
SubCommand = NetShareEnum;
// not really true be used by upper logic
Name = "\\PIPE\\LANMAN";
MaxParameterCount = 8;
// maxDataCount = 4096; why was this set?
MaxSetupCount = 0x00;
SetupCount = 0;
Timeout = 5000;
}
public NetShareEnum()
{
Command = SmbComTransaction;
SubCommand = NetShareEnum;
// not really true be used by upper logic
Name ="\\PIPE\\LANMAN";
MaxParameterCount = 8;
// maxDataCount = 4096; why was this set?
MaxSetupCount = 0x00;
SetupCount = 0;
Timeout = 5000;
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
byte[] descr;
try
{
//descr = Runtime.GetBytesForString(Descr, "ASCII");
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
byte[] descr;
try
{
//descr = Runtime.GetBytesForString(Descr, "ASCII");
descr = Runtime.GetBytesForString(Descr, "UTF-8");
}
catch (UnsupportedEncodingException)
{
return 0;
}
WriteInt2(NetShareEnum, dst, dstIndex);
dstIndex += 2;
Array.Copy(descr, 0, dst, dstIndex, descr.Length);
dstIndex += descr.Length;
WriteInt2(unchecked(0x0001), dst, dstIndex);
dstIndex += 2;
WriteInt2(MaxDataCount, dst, dstIndex);
dstIndex += 2;
return dstIndex - start;
}
}
catch (UnsupportedEncodingException)
{
return 0;
}
WriteInt2(NetShareEnum, dst, dstIndex);
dstIndex += 2;
Array.Copy(descr, 0, dst, dstIndex, descr.Length);
dstIndex += descr.Length;
WriteInt2(unchecked(0x0001), dst, dstIndex);
dstIndex += 2;
WriteInt2(MaxDataCount, dst, dstIndex);
dstIndex += 2;
return dstIndex - start;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
return 0;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
public override string ToString()
{
return "NetShareEnum[" + base.ToString() + "]";
}
}
public override string ToString()
{
return "NetShareEnum[" + base.ToString() + "]";
}
}
}

View File

@ -16,80 +16,79 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class NetShareEnumResponse : SmbComTransactionResponse
{
private int _converter;
internal class NetShareEnumResponse : SmbComTransactionResponse
{
private int _converter;
private int _totalAvailableEntries;
private int _totalAvailableEntries;
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
Status = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_converter = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
NumEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_totalAvailableEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
return bufferIndex - start;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
int start = bufferIndex;
Status = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_converter = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
NumEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
_totalAvailableEntries = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
return bufferIndex - start;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
SmbShareInfo e;
UseUnicode = false;
Results = new SmbShareInfo[NumEntries];
for (int i = 0; i < NumEntries; i++)
{
Results[i] = e = new SmbShareInfo();
e.NetName = ReadString(buffer, bufferIndex, 13, false);
bufferIndex += 14;
e.Type = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
int off = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
off = (off & unchecked(0xFFFF)) - _converter;
off = start + off;
e.Remark = ReadString(buffer, off, 128, false);
if (Log.Level >= 4)
{
Log.WriteLine(e);
}
}
return bufferIndex - start;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
SmbShareInfo e;
UseUnicode = false;
Results = new SmbShareInfo[NumEntries];
for (int i = 0; i < NumEntries; i++)
{
Results[i] = e = new SmbShareInfo();
e.NetName = ReadString(buffer, bufferIndex, 13, false);
bufferIndex += 14;
e.Type = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
int off = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
off = (off & unchecked(0xFFFF)) - _converter;
off = start + off;
e.Remark = ReadString(buffer, off, 128, false);
if (Log.Level >= 4)
{
Log.WriteLine(e);
}
}
return bufferIndex - start;
}
public override string ToString()
{
return "NetShareEnumResponse["
+ base.ToString()
+ ",status=" + Status
+ ",converter=" + _converter
+ ",entriesReturned=" + NumEntries
+ ",totalAvailableEntries=" + _totalAvailableEntries + "]";
}
}
public override string ToString()
{
return "NetShareEnumResponse[" + base.ToString() + ",status=" + Status
+ ",converter=" + _converter + ",entriesReturned=" + NumEntries + ",totalAvailableEntries="
+ _totalAvailableEntries + "]";
}
}
}

View File

@ -16,262 +16,187 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
public static class NtStatus
{
public const int NtStatusOk = unchecked(0x00000000);
public static class NtStatus
{
public const int NtStatusOk = unchecked(0x00000000);
public const int NtStatusUnsuccessful = unchecked((int)(0xC0000001));
public const int NtStatusUnsuccessful = unchecked((int)(0xC0000001));
public const int NtStatusNotImplemented = unchecked((int)(0xC0000002));
public const int NtStatusNotImplemented = unchecked((int)(0xC0000002));
public const int NtStatusInvalidInfoClass = unchecked((int)(0xC0000003));
public const int NtStatusInvalidInfoClass = unchecked((int)(0xC0000003));
public const int NtStatusAccessViolation = unchecked((int)(0xC0000005));
public const int NtStatusAccessViolation = unchecked((int)(0xC0000005));
public const int NtStatusInvalidHandle = unchecked((int)(0xC0000008));
public const int NtStatusInvalidHandle = unchecked((int)(0xC0000008));
public const int NtStatusInvalidParameter = unchecked((int)(0xC000000d));
public const int NtStatusInvalidParameter = unchecked((int)(0xC000000d));
public const int NtStatusNoSuchDevice = unchecked((int)(0xC000000e));
public const int NtStatusNoSuchDevice = unchecked((int)(0xC000000e));
public const int NtStatusNoSuchFile = unchecked((int)(0xC000000f));
public const int NtStatusNoSuchFile = unchecked((int)(0xC000000f));
public const int NtStatusMoreProcessingRequired = unchecked((int)(0xC0000016));
public const int NtStatusMoreProcessingRequired = unchecked((int)(0xC0000016)
);
public const int NtStatusAccessDenied = unchecked((int)(0xC0000022));
public const int NtStatusAccessDenied = unchecked((int)(0xC0000022));
public const int NtStatusBufferTooSmall = unchecked((int)(0xC0000023));
public const int NtStatusBufferTooSmall = unchecked((int)(0xC0000023));
public const int NtStatusObjectNameInvalid = unchecked((int)(0xC0000033));
public const int NtStatusObjectNameInvalid = unchecked((int)(0xC0000033));
public const int NtStatusObjectNameNotFound = unchecked((int)(0xC0000034));
public const int NtStatusObjectNameNotFound = unchecked((int)(0xC0000034));
public const int NtStatusObjectNameCollision = unchecked((int)(0xC0000035));
public const int NtStatusObjectNameCollision = unchecked((int)(0xC0000035));
public const int NtStatusPortDisconnected = unchecked((int)(0xC0000037));
public const int NtStatusPortDisconnected = unchecked((int)(0xC0000037));
public const int NtStatusObjectPathInvalid = unchecked((int)(0xC0000039));
public const int NtStatusObjectPathInvalid = unchecked((int)(0xC0000039));
public const int NtStatusObjectPathNotFound = unchecked((int)(0xC000003a));
public const int NtStatusObjectPathNotFound = unchecked((int)(0xC000003a));
public const int NtStatusObjectPathSyntaxBad = unchecked((int)(0xC000003b));
public const int NtStatusObjectPathSyntaxBad = unchecked((int)(0xC000003b));
public const int NtStatusSharingViolation = unchecked((int)(0xC0000043));
public const int NtStatusSharingViolation = unchecked((int)(0xC0000043));
public const int NtStatusDeletePending = unchecked((int)(0xC0000056));
public const int NtStatusDeletePending = unchecked((int)(0xC0000056));
public const int NtStatusNoLogonServers = unchecked((int)(0xC000005e));
public const int NtStatusNoLogonServers = unchecked((int)(0xC000005e));
public const int NtStatusUserExists = unchecked((int)(0xC0000063));
public const int NtStatusUserExists = unchecked((int)(0xC0000063));
public const int NtStatusNoSuchUser = unchecked((int)(0xC0000064));
public const int NtStatusNoSuchUser = unchecked((int)(0xC0000064));
public const int NtStatusWrongPassword = unchecked((int)(0xC000006a));
public const int NtStatusWrongPassword = unchecked((int)(0xC000006a));
public const int NtStatusLogonFailure = unchecked((int)(0xC000006d));
public const int NtStatusLogonFailure = unchecked((int)(0xC000006d));
public const int NtStatusAccountRestriction = unchecked((int)(0xC000006e));
public const int NtStatusAccountRestriction = unchecked((int)(0xC000006e));
public const int NtStatusInvalidLogonHours = unchecked((int)(0xC000006f));
public const int NtStatusInvalidLogonHours = unchecked((int)(0xC000006f));
public const int NtStatusInvalidWorkstation = unchecked((int)(0xC0000070));
public const int NtStatusInvalidWorkstation = unchecked((int)(0xC0000070));
public const int NtStatusPasswordExpired = unchecked((int)(0xC0000071));
public const int NtStatusPasswordExpired = unchecked((int)(0xC0000071));
public const int NtStatusAccountDisabled = unchecked((int)(0xC0000072));
public const int NtStatusAccountDisabled = unchecked((int)(0xC0000072));
public const int NtStatusNoneMapped = unchecked((int)(0xC0000073));
public const int NtStatusNoneMapped = unchecked((int)(0xC0000073));
public const int NtStatusInvalidSid = unchecked((int)(0xC0000078));
public const int NtStatusInvalidSid = unchecked((int)(0xC0000078));
public const int NtStatusInstanceNotAvailable = unchecked((int)(0xC00000ab));
public const int NtStatusInstanceNotAvailable = unchecked((int)(0xC00000ab));
public const int NtStatusPipeNotAvailable = unchecked((int)(0xC00000ac));
public const int NtStatusPipeNotAvailable = unchecked((int)(0xC00000ac));
public const int NtStatusInvalidPipeState = unchecked((int)(0xC00000ad));
public const int NtStatusInvalidPipeState = unchecked((int)(0xC00000ad));
public const int NtStatusPipeBusy = unchecked((int)(0xC00000ae));
public const int NtStatusPipeBusy = unchecked((int)(0xC00000ae));
public const int NtStatusPipeDisconnected = unchecked((int)(0xC00000b0));
public const int NtStatusPipeDisconnected = unchecked((int)(0xC00000b0));
public const int NtStatusPipeClosing = unchecked((int)(0xC00000b1));
public const int NtStatusPipeClosing = unchecked((int)(0xC00000b1));
public const int NtStatusPipeListening = unchecked((int)(0xC00000b3));
public const int NtStatusPipeListening = unchecked((int)(0xC00000b3));
public const int NtStatusFileIsADirectory = unchecked((int)(0xC00000ba));
public const int NtStatusFileIsADirectory = unchecked((int)(0xC00000ba));
public const int NtStatusDuplicateName = unchecked((int)(0xC00000bd));
public const int NtStatusDuplicateName = unchecked((int)(0xC00000bd));
public const int NtStatusNetworkNameDeleted = unchecked((int)(0xC00000c9));
public const int NtStatusNetworkNameDeleted = unchecked((int)(0xC00000c9));
public const int NtStatusNetworkAccessDenied = unchecked((int)(0xC00000ca));
public const int NtStatusNetworkAccessDenied = unchecked((int)(0xC00000ca));
public const int NtStatusBadNetworkName = unchecked((int)(0xC00000cc));
public const int NtStatusBadNetworkName = unchecked((int)(0xC00000cc));
public const int NtStatusRequestNotAccepted = unchecked((int)(0xC00000d0));
public const int NtStatusRequestNotAccepted = unchecked((int)(0xC00000d0));
public const int NtStatusCantAccessDomainInfo = unchecked((int)(0xC00000da));
public const int NtStatusCantAccessDomainInfo = unchecked((int)(0xC00000da));
public const int NtStatusNoSuchDomain = unchecked((int)(0xC00000df));
public const int NtStatusNoSuchDomain = unchecked((int)(0xC00000df));
public const int NtStatusNotADirectory = unchecked((int)(0xC0000103));
public const int NtStatusNotADirectory = unchecked((int)(0xC0000103));
public const int NtStatusCannotDelete = unchecked((int)(0xC0000121));
public const int NtStatusCannotDelete = unchecked((int)(0xC0000121));
public const int NtStatusInvalidComputerName = unchecked((int)(0xC0000122));
public const int NtStatusInvalidComputerName = unchecked((int)(0xC0000122));
public const int NtStatusPipeBroken = unchecked((int)(0xC000014b));
public const int NtStatusPipeBroken = unchecked((int)(0xC000014b));
public const int NtStatusNoSuchAlias = unchecked((int)(0xC0000151));
public const int NtStatusNoSuchAlias = unchecked((int)(0xC0000151));
public const int NtStatusLogonTypeNotGranted = unchecked((int)(0xC000015b));
public const int NtStatusLogonTypeNotGranted = unchecked((int)(0xC000015b));
public const int NtStatusNoTrustSamAccount = unchecked((int)(0xC000018b));
public const int NtStatusNoTrustSamAccount = unchecked((int)(0xC000018b));
public const int NtStatusTrustedDomainFailure = unchecked((int)(0xC000018c));
public const int NtStatusTrustedDomainFailure = unchecked((int)(0xC000018c));
public const int NtStatusNologonWorkstationTrustAccount = unchecked((int)(0xC0000199));
public const int NtStatusNologonWorkstationTrustAccount = unchecked((int)(0xC0000199
));
public const int NtStatusPasswordMustChange = unchecked((int)(0xC0000224));
public const int NtStatusPasswordMustChange = unchecked((int)(0xC0000224));
public const int NtStatusNotFound = unchecked((int)(0xC0000225));
public const int NtStatusNotFound = unchecked((int)(0xC0000225));
public const int NtStatusAccountLockedOut = unchecked((int)(0xC0000234));
public const int NtStatusAccountLockedOut = unchecked((int)(0xC0000234));
public const int NtStatusPathNotCovered = unchecked((int)(0xC0000257));
public const int NtStatusPathNotCovered = unchecked((int)(0xC0000257));
public const int NtStatusIoReparseTagNotHandled = unchecked((int)(0xC0000279));
public const int NtStatusIoReparseTagNotHandled = unchecked((int)(0xC0000279
));
public static int[] NtStatusCodes =
{
NtStatusOk,
NtStatusUnsuccessful,
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 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 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"
};
}
}

View File

@ -18,71 +18,71 @@ using SharpCifs.Util;
namespace SharpCifs.Smb
{
internal class NtTransQuerySecurityDesc : SmbComNtTransaction
{
internal int Fid;
internal class NtTransQuerySecurityDesc : SmbComNtTransaction
{
internal int Fid;
internal int SecurityInformation;
internal int SecurityInformation;
internal NtTransQuerySecurityDesc(int fid, int securityInformation)
{
this.Fid = fid;
this.SecurityInformation = securityInformation;
Command = SmbComNtTransact;
Function = NtTransactQuerySecurityDesc;
SetupCount = 0;
TotalDataCount = 0;
MaxParameterCount = 4;
MaxDataCount = 32768;
MaxSetupCount = unchecked(unchecked(0x00));
}
internal NtTransQuerySecurityDesc(int fid, int securityInformation)
{
this.Fid = fid;
this.SecurityInformation = securityInformation;
Command = SmbComNtTransact;
Function = NtTransactQuerySecurityDesc;
SetupCount = 0;
TotalDataCount = 0;
MaxParameterCount = 4;
MaxDataCount = 32768;
MaxSetupCount = unchecked(unchecked(0x00));
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
WriteInt2(Fid, dst, dstIndex);
dstIndex += 2;
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
WriteInt4(SecurityInformation, dst, dstIndex);
dstIndex += 4;
return dstIndex - start;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
WriteInt2(Fid, dst, dstIndex);
dstIndex += 2;
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
WriteInt4(SecurityInformation, dst, dstIndex);
dstIndex += 4;
return dstIndex - start;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
return 0;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
public override string ToString()
{
return "NtTransQuerySecurityDesc["
+ base.ToString()
+ ",fid=0x" + Hexdump.ToHexString(Fid, 4)
+ ",securityInformation=0x" + Hexdump.ToHexString(SecurityInformation, 8)
+ "]";
}
}
public override string ToString()
{
return "NtTransQuerySecurityDesc[" + base.ToString() + ",fid=0x" + Hexdump
.ToHexString(Fid, 4) + ",securityInformation=0x" + Hexdump.ToHexString(SecurityInformation
, 8) + "]";
}
}
}

View File

@ -19,58 +19,60 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class NtTransQuerySecurityDescResponse : SmbComNtTransactionResponse
{
internal SecurityDescriptor SecurityDescriptor;
internal class NtTransQuerySecurityDescResponse : SmbComNtTransactionResponse
{
internal SecurityDescriptor SecurityDescriptor;
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteSetupWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParametersWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteDataWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len)
{
return 0;
}
internal override int ReadSetupWireFormat(byte[] buffer, int bufferIndex, int len
)
{
return 0;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int len)
{
Length = ReadInt4(buffer, bufferIndex);
return 4;
}
internal override int ReadParametersWireFormat(byte[] buffer, int bufferIndex, int
len)
{
Length = ReadInt4(buffer, bufferIndex);
return 4;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
if (ErrorCode != 0)
{
return 4;
}
try
{
SecurityDescriptor = new SecurityDescriptor();
bufferIndex += SecurityDescriptor.Decode(buffer, bufferIndex, len);
}
catch (IOException ioe)
{
throw new RuntimeException(ioe.Message);
}
return bufferIndex - start;
}
internal override int ReadDataWireFormat(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
if (ErrorCode != 0)
{
return 4;
}
try
{
SecurityDescriptor = new SecurityDescriptor();
bufferIndex += SecurityDescriptor.Decode(buffer, bufferIndex, len);
}
catch (IOException ioe)
{
throw new RuntimeException(ioe.Message);
}
return bufferIndex - start;
}
public override string ToString()
{
return "NtTransQuerySecurityResponse[" + base.ToString() + "]";
}
}
public override string ToString()
{
return "NtTransQuerySecurityResponse[" + base.ToString() + "]";
}
}
}

View File

@ -16,82 +16,78 @@
// 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>
/// <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
{
private static NtlmAuthenticator _auth;
/// <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>
public abstract class NtlmAuthenticator
{
private static NtlmAuthenticator _auth;
private string _url;
private string _url;
private SmbAuthException _sae;
private SmbAuthException _sae;
private void Reset()
{
_url = null;
_sae = null;
}
private void Reset()
{
_url = null;
_sae = null;
}
/// <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>
public static void SetDefault(NtlmAuthenticator a)
{
lock (typeof(NtlmAuthenticator))
{
if (_auth != null)
{
return;
}
_auth = a;
}
}
/// <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>
public static void SetDefault(NtlmAuthenticator a)
{
lock (typeof(NtlmAuthenticator))
{
if (_auth != null)
{
return;
}
_auth = a;
}
}
protected internal string GetRequestingUrl()
{
return _url;
}
protected internal string GetRequestingUrl()
{
return _url;
}
protected internal SmbAuthException GetRequestingException()
{
return _sae;
}
protected internal SmbAuthException GetRequestingException()
{
return _sae;
}
/// <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>
public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string url,
SmbAuthException sae)
{
if (_auth == null)
{
return null;
}
lock (_auth)
{
_auth._url = url;
_auth._sae = sae;
return _auth.GetNtlmPasswordAuthentication();
}
}
/// <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>
public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string
url, SmbAuthException sae)
{
if (_auth == null)
{
return null;
}
lock (_auth)
{
_auth._url = url;
_auth._sae = sae;
return _auth.GetNtlmPasswordAuthentication();
}
}
/// <summary>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.
/// </summary>
/// <remarks>
/// 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()
{
return null;
}
}
/// <summary>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.
/// </summary>
/// <remarks>
/// 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
()
{
return null;
}
}
}

View File

@ -18,23 +18,23 @@ using SharpCifs.Util;
namespace SharpCifs.Smb
{
public sealed class NtlmChallenge
{
public byte[] Challenge;
public sealed class NtlmChallenge
{
public byte[] Challenge;
public UniAddress Dc;
public UniAddress Dc;
internal NtlmChallenge(byte[] challenge, UniAddress dc)
{
this.Challenge = challenge;
this.Dc = dc;
}
internal NtlmChallenge(byte[] challenge, UniAddress dc)
{
this.Challenge = challenge;
this.Dc = dc;
}
public override string ToString()
{
return "NtlmChallenge[challenge=0x" + Hexdump.ToHexString(Challenge, 0, Challenge.Length * 2)
+ ",dc=" + Dc + "]";
}
}
public override string ToString()
{
return "NtlmChallenge[challenge=0x" + Hexdump.ToHexString(Challenge, 0, Challenge
.Length * 2) + ",dc=" + Dc + "]";
}
}
}

View File

@ -21,200 +21,186 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
/// <summary>For initiating NTLM authentication (including NTLMv2).</summary>
/// <remarks>For initiating NTLM authentication (including NTLMv2). If you want to add NTLMv2 authentication support to something this is what you want to use. See the code for details. Note that JCIFS does not implement the acceptor side of NTLM authentication.
/// </remarks>
public class NtlmContext
{
internal NtlmPasswordAuthentication Auth;
/// <summary>For initiating NTLM authentication (including NTLMv2).</summary>
/// <remarks>For initiating NTLM authentication (including NTLMv2). If you want to add NTLMv2 authentication support to something this is what you want to use. See the code for details. Note that JCIFS does not implement the acceptor side of NTLM authentication.
/// </remarks>
public class NtlmContext
{
internal NtlmPasswordAuthentication Auth;
internal int NtlmsspFlags;
internal int NtlmsspFlags;
internal string Workstation;
internal string Workstation;
internal bool isEstablished;
internal bool isEstablished;
internal byte[] ServerChallenge;
internal byte[] ServerChallenge;
internal byte[] SigningKey;
internal byte[] SigningKey;
internal string NetbiosName = null;
internal string NetbiosName = null;
internal int State = 1;
internal int State = 1;
internal LogStream Log;
internal LogStream Log;
public NtlmContext(NtlmPasswordAuthentication auth, bool doSigning)
{
this.Auth = auth;
NtlmsspFlags = NtlmsspFlags
| NtlmFlags.NtlmsspRequestTarget
| NtlmFlags.NtlmsspNegotiateNtlm2
| NtlmFlags.NtlmsspNegotiate128;
if (doSigning)
{
NtlmsspFlags |= NtlmFlags.NtlmsspNegotiateSign
| NtlmFlags.NtlmsspNegotiateAlwaysSign
| NtlmFlags.NtlmsspNegotiateKeyExch;
}
Workstation = Type1Message.GetDefaultWorkstation();
Log = LogStream.GetInstance();
}
public NtlmContext(NtlmPasswordAuthentication auth, bool doSigning)
{
this.Auth = auth;
NtlmsspFlags = NtlmsspFlags | NtlmFlags.NtlmsspRequestTarget | NtlmFlags.NtlmsspNegotiateNtlm2
| NtlmFlags.NtlmsspNegotiate128;
if (doSigning)
{
NtlmsspFlags |= NtlmFlags.NtlmsspNegotiateSign | NtlmFlags.NtlmsspNegotiateAlwaysSign
| NtlmFlags.NtlmsspNegotiateKeyExch;
}
Workstation = Type1Message.GetDefaultWorkstation();
Log = LogStream.GetInstance();
}
public override string ToString()
{
string ret = "NtlmContext[auth=" + Auth
+ ",ntlmsspFlags=0x" + Hexdump.ToHexString(NtlmsspFlags, 8)
+ ",workstation=" + Workstation
+ ",isEstablished=" + isEstablished
+ ",state=" + State
+ ",serverChallenge=";
if (ServerChallenge == null)
{
ret += "null";
}
else
{
ret += Hexdump.ToHexString(ServerChallenge, 0, ServerChallenge.Length * 2);
}
ret += ",signingKey=";
if (SigningKey == null)
{
ret += "null";
}
else
{
ret += Hexdump.ToHexString(SigningKey, 0, SigningKey.Length * 2);
}
ret += "]";
return ret;
}
public override string ToString()
{
string ret = "NtlmContext[auth=" + Auth + ",ntlmsspFlags=0x" + Hexdump.ToHexString
(NtlmsspFlags, 8) + ",workstation=" + Workstation + ",isEstablished=" + isEstablished
+ ",state=" + State + ",serverChallenge=";
if (ServerChallenge == null)
{
ret += "null";
}
else
{
ret += Hexdump.ToHexString(ServerChallenge, 0, ServerChallenge.Length * 2);
}
ret += ",signingKey=";
if (SigningKey == null)
{
ret += "null";
}
else
{
ret += Hexdump.ToHexString(SigningKey, 0, SigningKey.Length * 2);
}
ret += "]";
return ret;
}
public virtual bool IsEstablished()
{
return isEstablished;
}
public virtual bool IsEstablished()
{
return isEstablished;
}
public virtual byte[] GetServerChallenge()
{
return ServerChallenge;
}
public virtual byte[] GetServerChallenge()
{
return ServerChallenge;
}
public virtual byte[] GetSigningKey()
{
return SigningKey;
}
public virtual byte[] GetSigningKey()
{
return SigningKey;
}
public virtual string GetNetbiosName()
{
return NetbiosName;
}
public virtual string GetNetbiosName()
{
return NetbiosName;
}
private string GetNtlmsspListItem(byte[] type2Token, int id0)
{
int ri = 58;
for (;;)
{
int id = Encdec.Dec_uint16le(type2Token, ri);
int len = Encdec.Dec_uint16le(type2Token, ri + 2);
ri += 4;
if (id == 0 || (ri + len) > type2Token.Length)
{
break;
}
if (id == id0)
{
try
{
return Runtime.GetStringForBytes(type2Token,
ri,
len,
SmbConstants.UniEncoding);
}
catch (UnsupportedEncodingException)
{
break;
}
}
ri += len;
}
return null;
}
private string GetNtlmsspListItem(byte[] type2Token, int id0)
{
int ri = 58;
for (; ; )
{
int id = Encdec.Dec_uint16le(type2Token, ri);
int len = Encdec.Dec_uint16le(type2Token, ri + 2);
ri += 4;
if (id == 0 || (ri + len) > type2Token.Length)
{
break;
}
if (id == id0)
{
try
{
return Runtime.GetStringForBytes(type2Token, ri, len, SmbConstants.UniEncoding
);
}
catch (UnsupportedEncodingException)
{
break;
}
}
ri += len;
}
return null;
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public virtual byte[] InitSecContext(byte[] token, int offset, int len)
{
switch (State)
{
case 1:
{
Type1Message msg1 = new Type1Message(NtlmsspFlags,
Auth.GetDomain(),
Workstation);
token = msg1.ToByteArray();
if (Log.Level >= 4)
{
Log.WriteLine(msg1);
if (Log.Level >= 6)
{
Hexdump.ToHexdump(Log, token, 0, token.Length);
}
}
State++;
break;
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public virtual byte[] InitSecContext(byte[] token, int offset, int len)
{
switch (State)
{
case 1:
{
Type1Message msg1 = new Type1Message(NtlmsspFlags, Auth.GetDomain(), Workstation);
token = msg1.ToByteArray();
if (Log.Level >= 4)
{
Log.WriteLine(msg1);
if (Log.Level >= 6)
{
Hexdump.ToHexdump(Log, token, 0, token.Length);
}
}
State++;
break;
}
case 2:
{
try
{
Type2Message msg2 = new Type2Message(token);
if (Log.Level >= 4)
{
Log.WriteLine(msg2);
if (Log.Level >= 6)
{
Hexdump.ToHexdump(Log, token, 0, token.Length);
}
}
ServerChallenge = msg2.GetChallenge();
NtlmsspFlags &= msg2.GetFlags();
//netbiosName = getNtlmsspListItem(token, 0x0001);
Type3Message msg3 = new Type3Message(msg2,
Auth.GetPassword(),
Auth.GetDomain(),
Auth.GetUsername(),
Workstation,
NtlmsspFlags);
token = msg3.ToByteArray();
if (Log.Level >= 4)
{
Log.WriteLine(msg3);
if (Log.Level >= 6)
{
Hexdump.ToHexdump(Log, token, 0, token.Length);
}
}
if ((NtlmsspFlags & NtlmFlags.NtlmsspNegotiateSign) != 0)
{
SigningKey = msg3.GetMasterKey();
}
isEstablished = true;
State++;
break;
}
catch (Exception e)
{
throw new SmbException(e.Message, e);
}
}
case 2:
{
try
{
Type2Message msg2 = new Type2Message(token);
if (Log.Level >= 4)
{
Log.WriteLine(msg2);
if (Log.Level >= 6)
{
Hexdump.ToHexdump(Log, token, 0, token.Length);
}
}
ServerChallenge = msg2.GetChallenge();
NtlmsspFlags &= msg2.GetFlags();
// netbiosName = getNtlmsspListItem(token, 0x0001);
Type3Message msg3 = new Type3Message(msg2, Auth.GetPassword(), Auth.GetDomain(),
Auth.GetUsername(), Workstation, NtlmsspFlags);
token = msg3.ToByteArray();
if (Log.Level >= 4)
{
Log.WriteLine(msg3);
if (Log.Level >= 6)
{
Hexdump.ToHexdump(Log, token, 0, token.Length);
}
}
if ((NtlmsspFlags & NtlmFlags.NtlmsspNegotiateSign) != 0)
{
SigningKey = msg3.GetMasterKey();
}
isEstablished = true;
State++;
break;
}
catch (Exception e)
{
throw new SmbException(e.Message, e);
}
}
default:
{
throw new SmbException("Invalid state");
}
}
return token;
}
}
default:
{
throw new SmbException("Invalid state");
}
}
return token;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -18,84 +18,84 @@ using System.IO;
namespace SharpCifs.Smb
{
public class SecurityDescriptor
{
public int Type;
public class SecurityDescriptor
{
public int Type;
public Ace[] Aces;
public Ace[] Aces;
public SecurityDescriptor()
{
}
public SecurityDescriptor()
{
}
/// <exception cref="System.IO.IOException"></exception>
public SecurityDescriptor(byte[] buffer, int bufferIndex, int len)
{
Decode(buffer, bufferIndex, len);
}
/// <exception cref="System.IO.IOException"></exception>
public SecurityDescriptor(byte[] buffer, int bufferIndex, int len)
{
Decode(buffer, bufferIndex, len);
}
/// <exception cref="System.IO.IOException"></exception>
public virtual int Decode(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
bufferIndex++;
// revision
bufferIndex++;
Type = ServerMessageBlock.ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
// offset to owner sid
bufferIndex += 4;
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
// offset to group sid
bufferIndex += 4;
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
// offset to sacl
bufferIndex += 4;
int daclOffset = ServerMessageBlock.ReadInt4(buffer, bufferIndex);
bufferIndex = start + daclOffset;
bufferIndex++;
// revision
bufferIndex++;
int size = ServerMessageBlock.ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
int numAces = ServerMessageBlock.ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
if (numAces > 4096)
{
throw new IOException("Invalid SecurityDescriptor");
}
if (daclOffset != 0)
{
Aces = new Ace[numAces];
for (int i = 0; i < numAces; i++)
{
Aces[i] = new Ace();
bufferIndex += Aces[i].Decode(buffer, bufferIndex);
}
}
else
{
Aces = null;
}
return bufferIndex - start;
}
/// <exception cref="System.IO.IOException"></exception>
public virtual int Decode(byte[] buffer, int bufferIndex, int len)
{
int start = bufferIndex;
bufferIndex++;
// revision
bufferIndex++;
Type = ServerMessageBlock.ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
// offset to owner sid
bufferIndex += 4;
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
// offset to group sid
bufferIndex += 4;
ServerMessageBlock.ReadInt4(buffer, bufferIndex);
// offset to sacl
bufferIndex += 4;
int daclOffset = ServerMessageBlock.ReadInt4(buffer, bufferIndex);
bufferIndex = start + daclOffset;
bufferIndex++;
// revision
bufferIndex++;
int size = ServerMessageBlock.ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
int numAces = ServerMessageBlock.ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
if (numAces > 4096)
{
throw new IOException("Invalid SecurityDescriptor");
}
if (daclOffset != 0)
{
Aces = new Ace[numAces];
for (int i = 0; i < numAces; i++)
{
Aces[i] = new Ace();
bufferIndex += Aces[i].Decode(buffer, bufferIndex);
}
}
else
{
Aces = null;
}
return bufferIndex - start;
}
public override string ToString()
{
string ret = "SecurityDescriptor:\n";
if (Aces != null)
{
for (int ai = 0; ai < Aces.Length; ai++)
{
ret += Aces[ai] + "\n";
}
}
else
{
ret += "NULL";
}
return ret;
}
}
public override string ToString()
{
string ret = "SecurityDescriptor:\n";
if (Aces != null)
{
for (int ai = 0; ai < Aces.Length; ai++)
{
ret += Aces[ai] + "\n";
}
}
else
{
ret += "NULL";
}
return ret;
}
}
}

View File

@ -20,253 +20,238 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
/// <summary>To filter 0 len updates and for debugging</summary>
public class SigningDigest
{
internal static LogStream Log = LogStream.GetInstance();
/// <summary>To filter 0 len updates and for debugging</summary>
public class SigningDigest
{
internal static LogStream Log = LogStream.GetInstance();
private MessageDigest _digest;
private MessageDigest _digest;
private byte[] _macSigningKey;
private byte[] _macSigningKey;
private bool _bypass;
private bool _bypass;
private int _updates;
private int _updates;
private int _signSequence;
private int _signSequence;
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public SigningDigest(byte[] macSigningKey, bool bypass)
{
try
{
_digest = MessageDigest.GetInstance("MD5");
}
catch (NoSuchAlgorithmException ex)
{
if (Log.Level > 0)
{
Runtime.PrintStackTrace(ex, Log);
}
throw new SmbException("MD5", ex);
}
this._macSigningKey = macSigningKey;
this._bypass = bypass;
_updates = 0;
_signSequence = 0;
if (Log.Level >= 5)
{
Log.WriteLine("macSigningKey:");
Hexdump.ToHexdump(Log, macSigningKey, 0, macSigningKey.Length);
}
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public SigningDigest(byte[] macSigningKey, bool bypass)
{
try
{
_digest = MessageDigest.GetInstance("MD5");
}
catch (NoSuchAlgorithmException ex)
{
if (Log.Level > 0)
{
Runtime.PrintStackTrace(ex, Log);
}
throw new SmbException("MD5", ex);
}
this._macSigningKey = macSigningKey;
this._bypass = bypass;
_updates = 0;
_signSequence = 0;
if (Log.Level >= 5)
{
Log.WriteLine("macSigningKey:");
Hexdump.ToHexdump(Log, macSigningKey, 0, macSigningKey.Length);
}
}
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public SigningDigest(SmbTransport transport, NtlmPasswordAuthentication auth)
{
try
{
_digest = MessageDigest.GetInstance("MD5");
}
catch (NoSuchAlgorithmException ex)
{
if (Log.Level > 0)
{
Runtime.PrintStackTrace(ex, Log);
}
throw new SmbException("MD5", ex);
}
try
{
/// <exception cref="SharpCifs.Smb.SmbException"></exception>
public SigningDigest(SmbTransport transport, NtlmPasswordAuthentication auth)
{
try
{
_digest = MessageDigest.GetInstance("MD5");
}
catch (NoSuchAlgorithmException ex)
{
if (Log.Level > 0)
{
Runtime.PrintStackTrace(ex, Log);
}
throw new SmbException("MD5", ex);
}
try
{
switch (SmbConstants.LmCompatibility)
{
case 0:
case 1:
case 2:
{
_macSigningKey = new byte[40];
auth.GetUserSessionKey(transport.Server.EncryptionKey,
_macSigningKey,
0);
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey),
0,
_macSigningKey,
16,
24);
break;
}
{
case 0:
case 1:
case 2:
{
_macSigningKey = new byte[40];
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey
, 16, 24);
break;
}
case 3:
case 4:
case 5:
{
_macSigningKey = new byte[16];
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
break;
}
case 3:
case 4:
case 5:
{
_macSigningKey = new byte[16];
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
break;
}
default:
{
_macSigningKey = new byte[40];
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey),
0,
_macSigningKey,
16,
24);
break;
}
}
}
catch (Exception ex)
{
throw new SmbException(string.Empty, ex);
}
if (Log.Level >= 5)
{
default:
{
_macSigningKey = new byte[40];
auth.GetUserSessionKey(transport.Server.EncryptionKey, _macSigningKey, 0);
Array.Copy(auth.GetUnicodeHash(transport.Server.EncryptionKey), 0, _macSigningKey
, 16, 24);
break;
}
}
}
catch (Exception ex)
{
throw new SmbException(string.Empty, ex);
}
if (Log.Level >= 5)
{
Log.WriteLine("LM_COMPATIBILITY=" + SmbConstants.LmCompatibility);
Hexdump.ToHexdump(Log, _macSigningKey, 0, _macSigningKey.Length);
}
}
Hexdump.ToHexdump(Log, _macSigningKey, 0, _macSigningKey.Length);
}
}
public virtual void Update(byte[] input, int offset, int len)
{
if (Log.Level >= 5)
{
Log.WriteLine("update: " + _updates + " " + offset + ":" + len);
Hexdump.ToHexdump(Log, input, offset, Math.Min(len, 256));
Log.Flush();
}
if (len == 0)
{
return;
}
_digest.Update(input, offset, len);
_updates++;
}
public virtual void Update(byte[] input, int offset, int len)
{
if (Log.Level >= 5)
{
Log.WriteLine("update: " + _updates + " " + offset + ":" + len);
Hexdump.ToHexdump(Log, input, offset, Math.Min(len, 256));
Log.Flush();
}
if (len == 0)
{
return;
}
_digest.Update(input, offset, len);
_updates++;
}
public virtual byte[] Digest()
{
byte[] b;
b = _digest.Digest();
if (Log.Level >= 5)
{
Log.WriteLine("digest: ");
Hexdump.ToHexdump(Log, b, 0, b.Length);
Log.Flush();
}
_updates = 0;
return b;
}
public virtual byte[] Digest()
{
byte[] b;
b = _digest.Digest();
if (Log.Level >= 5)
{
Log.WriteLine("digest: ");
Hexdump.ToHexdump(Log, b, 0, b.Length);
Log.Flush();
}
_updates = 0;
return b;
}
/// <summary>Performs MAC signing of the SMB.</summary>
/// <remarks>
/// Performs MAC signing of the SMB. This is done as follows.
/// The signature field of the SMB is overwritted with the sequence number;
/// The MD5 digest of the MAC signing key + the entire SMB is taken;
/// The first 8 bytes of this are placed in the signature field.
/// </remarks>
/// <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)
{
request.SignSeq = _signSequence;
if (response != null)
{
response.SignSeq = _signSequence + 1;
response.VerifyFailed = false;
}
try
{
Update(_macSigningKey, 0, _macSigningKey.Length);
/// <summary>Performs MAC signing of the SMB.</summary>
/// <remarks>
/// Performs MAC signing of the SMB. This is done as follows.
/// The signature field of the SMB is overwritted with the sequence number;
/// The MD5 digest of the MAC signing key + the entire SMB is taken;
/// The first 8 bytes of this are placed in the signature field.
/// </remarks>
/// <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)
{
request.SignSeq = _signSequence;
if (response != null)
{
response.SignSeq = _signSequence + 1;
response.VerifyFailed = false;
}
try
{
Update(_macSigningKey, 0, _macSigningKey.Length);
int index = offset + SmbConstants.SignatureOffset;
for (int i = 0; i < 8; i++)
{
data[index + i] = 0;
}
ServerMessageBlock.WriteInt4(_signSequence, data, index);
Update(data, offset, length);
Array.Copy(Digest(), 0, data, index, 8);
if (_bypass)
{
_bypass = false;
Array.Copy(Runtime.GetBytesForString("BSRSPYL "),
0,
data,
index,
8);
}
}
catch (Exception ex)
{
if (Log.Level > 0)
{
Runtime.PrintStackTrace(ex, Log);
}
}
finally
{
_signSequence += 2;
}
}
for (int i = 0; i < 8; i++)
{
data[index + i] = 0;
}
ServerMessageBlock.WriteInt4(_signSequence, data, index);
Update(data, offset, length);
Array.Copy(Digest(), 0, data, index, 8);
if (_bypass)
{
_bypass = false;
Array.Copy(Runtime.GetBytesForString("BSRSPYL "), 0, data, index,
8);
}
}
catch (Exception ex)
{
if (Log.Level > 0)
{
Runtime.PrintStackTrace(ex, Log);
}
}
finally
{
_signSequence += 2;
}
}
/// <summary>Performs MAC signature verification.</summary>
/// <remarks>
/// Performs MAC signature verification. This calculates the signature
/// of the SMB and compares it to the signature field on the SMB itself.
/// </remarks>
/// <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)
{
Update(_macSigningKey, 0, _macSigningKey.Length);
int index = offset;
/// <summary>Performs MAC signature verification.</summary>
/// <remarks>
/// Performs MAC signature verification. This calculates the signature
/// of the SMB and compares it to the signature field on the SMB itself.
/// </remarks>
/// <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
)
{
Update(_macSigningKey, 0, _macSigningKey.Length);
int index = offset;
Update(data, index, SmbConstants.SignatureOffset);
index += SmbConstants.SignatureOffset;
byte[] sequence = new byte[8];
ServerMessageBlock.WriteInt4(response.SignSeq, sequence, 0);
Update(sequence, 0, sequence.Length);
index += 8;
if (response.Command == ServerMessageBlock.SmbComReadAndx)
{
SmbComReadAndXResponse raxr = (SmbComReadAndXResponse)response;
int length = response.Length - raxr.DataLength;
byte[] sequence = new byte[8];
ServerMessageBlock.WriteInt4(response.SignSeq, sequence, 0);
Update(sequence, 0, sequence.Length);
index += 8;
if (response.Command == ServerMessageBlock.SmbComReadAndx)
{
SmbComReadAndXResponse raxr = (SmbComReadAndXResponse)response;
int length = response.Length - raxr.DataLength;
Update(data, index, length - SmbConstants.SignatureOffset - 8);
Update(raxr.B, raxr.Off, raxr.DataLength);
}
else
{
Update(raxr.B, raxr.Off, raxr.DataLength);
}
else
{
Update(data, index, response.Length - SmbConstants.SignatureOffset - 8);
}
byte[] signature = Digest();
for (int i = 0; i < 8; i++)
{
}
byte[] signature = Digest();
for (int i = 0; i < 8; i++)
{
if (signature[i] != data[offset + SmbConstants.SignatureOffset + i])
{
if (Log.Level >= 2)
{
Log.WriteLine("signature verification failure");
Hexdump.ToHexdump(Log, signature, 0, 8);
{
if (Log.Level >= 2)
{
Log.WriteLine("signature verification failure");
Hexdump.ToHexdump(Log, signature, 0, 8);
Hexdump.ToHexdump(Log, data, offset + SmbConstants.SignatureOffset, 8);
}
return response.VerifyFailed = true;
}
}
return response.VerifyFailed = false;
}
}
return response.VerifyFailed = true;
}
}
return response.VerifyFailed = false;
}
public override string ToString()
{
return "LM_COMPATIBILITY=" + SmbConstants.LmCompatibility
+ " MacSigningKey=" + Hexdump.ToHexString(_macSigningKey,
0,
_macSigningKey.Length);
}
}
public override string ToString()
{
return "LM_COMPATIBILITY=" + SmbConstants.LmCompatibility + " MacSigningKey=" + Hexdump.ToHexString
(_macSigningKey, 0, _macSigningKey.Length);
}
}
}

View File

@ -16,21 +16,21 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
/// <summary>
/// The <code>SmbAuthException</code> encapsulates the variety of
/// authentication related error codes returned by an SMB server.
/// </summary>
/// <remarks>
/// The <code>SmbAuthException</code> encapsulates the variety of
/// authentication related error codes returned by an SMB server.
/// <p>
/// See <a href="../../../authhandler.html">jCIFS Exceptions and NtlmAuthenticator</a> for more information about <code>SmbAuthException</code>.
/// </remarks>
public class SmbAuthException : SmbException
{
internal SmbAuthException(int errcode) : base(errcode, null)
{
}
}
/// <summary>
/// The <code>SmbAuthException</code> encapsulates the variety of
/// authentication related error codes returned by an SMB server.
/// </summary>
/// <remarks>
/// The <code>SmbAuthException</code> encapsulates the variety of
/// authentication related error codes returned by an SMB server.
/// <p>
/// See <a href="../../../authhandler.html">jCIFS Exceptions and NtlmAuthenticator</a> for more information about <code>SmbAuthException</code>.
/// </remarks>
public class SmbAuthException : SmbException
{
internal SmbAuthException(int errcode) : base(errcode, null)
{
}
}
}

View File

@ -17,31 +17,31 @@
namespace SharpCifs.Smb
{
internal class SmbComBlankResponse : ServerMessageBlock
{
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
{
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComBlankResponse[" + base.ToString() + "]";
}
}
public override string ToString()
{
return "SmbComBlankResponse[" + base.ToString() + "]";
}
}
}

View File

@ -16,49 +16,47 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComClose : ServerMessageBlock
{
private int _fid;
internal class SmbComClose : ServerMessageBlock
{
private int _fid;
private long _lastWriteTime;
private long _lastWriteTime;
internal SmbComClose(int fid, long lastWriteTime)
{
this._fid = fid;
this._lastWriteTime = lastWriteTime;
Command = SmbComClose;
}
internal SmbComClose(int fid, long lastWriteTime)
{
this._fid = fid;
this._lastWriteTime = lastWriteTime;
Command = SmbComClose;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
WriteInt2(_fid, dst, dstIndex);
dstIndex += 2;
WriteUTime(_lastWriteTime, dst, dstIndex);
return 6;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
WriteInt2(_fid, dst, dstIndex);
dstIndex += 2;
WriteUTime(_lastWriteTime, dst, dstIndex);
return 6;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComClose["
+ base.ToString()
+ ",fid=" + _fid
+ ",lastWriteTime=" + _lastWriteTime + "]";
}
}
public override string ToString()
{
return "SmbComClose[" + base.ToString() + ",fid=" + _fid + ",lastWriteTime="
+ _lastWriteTime + "]";
}
}
}

View File

@ -16,43 +16,42 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComCreateDirectory : ServerMessageBlock
{
internal SmbComCreateDirectory(string directoryName)
{
Path = directoryName;
Command = SmbComCreateDirectory;
}
internal class SmbComCreateDirectory : ServerMessageBlock
{
internal SmbComCreateDirectory(string directoryName)
{
Path = directoryName;
Command = SmbComCreateDirectory;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x04));
dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x04));
dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComCreateDirectory["
+ base.ToString()
+ ",directoryName=" + Path + "]";
}
}
public override string ToString()
{
return "SmbComCreateDirectory[" + base.ToString() + ",directoryName="
+ Path + "]";
}
}
}

View File

@ -18,49 +18,46 @@ using SharpCifs.Util;
namespace SharpCifs.Smb
{
internal class SmbComDelete : ServerMessageBlock
{
private int _searchAttributes;
internal class SmbComDelete : ServerMessageBlock
{
private int _searchAttributes;
internal SmbComDelete(string fileName)
{
Path = fileName;
Command = SmbComDelete;
_searchAttributes = SmbConstants.AttrHidden
| SmbConstants.AttrHidden
| SmbConstants.AttrSystem;
}
internal SmbComDelete(string fileName)
{
Path = fileName;
Command = SmbComDelete;
_searchAttributes = SmbConstants.AttrHidden | SmbConstants.AttrHidden | SmbConstants.AttrSystem;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
WriteInt2(_searchAttributes, dst, dstIndex);
return 2;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
WriteInt2(_searchAttributes, dst, dstIndex);
return 2;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x04));
dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x04));
dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComDelete["
+ base.ToString()
+ ",searchAttributes=0x" + Hexdump.ToHexString(_searchAttributes, 4)
+ ",fileName=" + Path + "]";
}
}
public override string ToString()
{
return "SmbComDelete[" + base.ToString() + ",searchAttributes=0x" + Hexdump
.ToHexString(_searchAttributes, 4) + ",fileName=" + Path + "]";
}
}
}

View File

@ -16,42 +16,42 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComDeleteDirectory : ServerMessageBlock
{
internal SmbComDeleteDirectory(string directoryName)
{
Path = directoryName;
Command = SmbComDeleteDirectory;
}
internal class SmbComDeleteDirectory : ServerMessageBlock
{
internal SmbComDeleteDirectory(string directoryName)
{
Path = directoryName;
Command = SmbComDeleteDirectory;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x04));
dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x04));
dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComDeleteDirectory["
+ base.ToString()
+ ",directoryName=" + Path + "]";
}
}
public override string ToString()
{
return "SmbComDeleteDirectory[" + base.ToString() + ",directoryName="
+ Path + "]";
}
}
}

View File

@ -16,42 +16,41 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComFindClose2 : ServerMessageBlock
{
private int _sid;
internal class SmbComFindClose2 : ServerMessageBlock
{
private int _sid;
internal SmbComFindClose2(int sid)
{
this._sid = sid;
Command = SmbComFindClose2;
}
internal SmbComFindClose2(int sid)
{
this._sid = sid;
Command = SmbComFindClose2;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
WriteInt2(_sid, dst, dstIndex);
return 2;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
WriteInt2(_sid, dst, dstIndex);
return 2;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComFindClose2["
+ base.ToString()
+ ",sid=" + _sid + "]";
}
}
public override string ToString()
{
return "SmbComFindClose2[" + base.ToString() + ",sid=" + _sid + "]";
}
}
}

View File

@ -16,36 +16,37 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComLogoffAndX : AndXServerMessageBlock
{
internal SmbComLogoffAndX(ServerMessageBlock andx) : base(andx)
{
Command = SmbComLogoffAndx;
}
internal class SmbComLogoffAndX : AndXServerMessageBlock
{
internal SmbComLogoffAndX(ServerMessageBlock andx) : base(andx)
{
Command = SmbComLogoffAndx;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComLogoffAndX[" + base.ToString() + "]";
}
}
public override string ToString()
{
return "SmbComLogoffAndX[" + base.ToString() + "]";
}
}
}

View File

@ -18,187 +18,176 @@ using SharpCifs.Util;
namespace SharpCifs.Smb
{
internal class SmbComNtCreateAndX : AndXServerMessageBlock
{
internal const int FileSupersede = unchecked(0x0);
internal class SmbComNtCreateAndX : AndXServerMessageBlock
{
internal const int FileSupersede = unchecked(0x0);
internal const int FileOpen = unchecked(0x1);
internal const int FileOpen = unchecked(0x1);
internal const int FileCreate = unchecked(0x2);
internal const int FileCreate = unchecked(0x2);
internal const int FileOpenIf = unchecked(0x3);
internal const int FileOpenIf = unchecked(0x3);
internal const int FileOverwrite = unchecked(0x4);
internal const int FileOverwrite = unchecked(0x4);
internal const int FileOverwriteIf = unchecked(0x5);
internal const int FileOverwriteIf = unchecked(0x5);
internal const int FileWriteThrough = unchecked(0x00000002);
internal const int FileWriteThrough = unchecked(0x00000002);
internal const int FileSequentialOnly = unchecked(0x00000004);
internal const int FileSequentialOnly = unchecked(0x00000004);
internal const int FileSynchronousIoAlert = unchecked(0x00000010);
internal const int FileSynchronousIoAlert = unchecked(0x00000010);
internal const int FileSynchronousIoNonalert = unchecked(0x00000020);
internal const int FileSynchronousIoNonalert = unchecked(0x00000020);
internal const int SecurityContextTracking = unchecked(0x01);
internal const int SecurityContextTracking = unchecked(0x01);
internal const int SecurityEffectiveOnly = unchecked(0x02);
internal const int SecurityEffectiveOnly = unchecked(0x02);
private int _rootDirectoryFid;
private int _rootDirectoryFid;
private int _extFileAttributes;
private int _extFileAttributes;
private int _shareAccess;
private int _shareAccess;
private int _createDisposition;
private int _createDisposition;
private int _createOptions;
private int _createOptions;
private int _impersonationLevel;
private int _impersonationLevel;
private long _allocationSize;
private long _allocationSize;
private byte _securityFlags;
private byte _securityFlags;
private int _namelenIndex;
private int _namelenIndex;
internal int Flags0;
internal int Flags0;
internal int DesiredAccess;
internal int DesiredAccess;
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
// create options
// security flags
Path = name;
Command = SmbComNtCreateAndx;
DesiredAccess = access;
DesiredAccess |= SmbConstants.FileReadData
| SmbConstants.FileReadEa
| SmbConstants.FileReadAttributes;
// extFileAttributes
this._extFileAttributes = extFileAttributes;
// shareAccess
this._shareAccess = shareAccess;
// createDisposition
if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc)
{
// truncate the file
if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
{
// create it if necessary
_createDisposition = FileOverwriteIf;
}
else
{
_createDisposition = FileOverwrite;
}
}
else
{
// don't truncate the file
if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
{
// create it if necessary
if ((flags & SmbFile.OExcl) == SmbFile.OExcl)
{
// fail if already exists
_createDisposition = FileCreate;
}
else
{
_createDisposition = FileOpenIf;
}
}
else
{
_createDisposition = FileOpen;
}
}
if ((createOptions & unchecked(0x0001)) == 0)
{
this._createOptions = createOptions | unchecked(0x0040);
}
else
{
this._createOptions = createOptions;
}
_impersonationLevel = unchecked(0x02);
// As seen on NT :~)
_securityFlags = unchecked(unchecked(0x03));
}
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
// create options
// security flags
Path = name;
Command = SmbComNtCreateAndx;
DesiredAccess = access;
DesiredAccess |= SmbConstants.FileReadData | SmbConstants.FileReadEa | SmbConstants.FileReadAttributes;
// extFileAttributes
this._extFileAttributes = extFileAttributes;
// shareAccess
this._shareAccess = shareAccess;
// createDisposition
if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc)
{
// truncate the file
if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
{
// create it if necessary
_createDisposition = FileOverwriteIf;
}
else
{
_createDisposition = FileOverwrite;
}
}
else
{
// don't truncate the file
if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
{
// create it if necessary
if ((flags & SmbFile.OExcl) == SmbFile.OExcl)
{
// fail if already exists
_createDisposition = FileCreate;
}
else
{
_createDisposition = FileOpenIf;
}
}
else
{
_createDisposition = FileOpen;
}
}
if ((createOptions & unchecked(0x0001)) == 0)
{
this._createOptions = createOptions | unchecked(0x0040);
}
else
{
this._createOptions = createOptions;
}
_impersonationLevel = unchecked(0x02);
// As seen on NT :~)
_securityFlags = unchecked(unchecked(0x03));
}
// SECURITY_CONTEXT_TRACKING | SECURITY_EFFECTIVE_ONLY
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x00));
// name length without counting null termination
_namelenIndex = dstIndex;
dstIndex += 2;
WriteInt4(Flags0, dst, dstIndex);
dstIndex += 4;
WriteInt4(_rootDirectoryFid, dst, dstIndex);
dstIndex += 4;
WriteInt4(DesiredAccess, dst, dstIndex);
dstIndex += 4;
WriteInt8(_allocationSize, dst, dstIndex);
dstIndex += 8;
WriteInt4(_extFileAttributes, dst, dstIndex);
dstIndex += 4;
WriteInt4(_shareAccess, dst, dstIndex);
dstIndex += 4;
WriteInt4(_createDisposition, dst, dstIndex);
dstIndex += 4;
WriteInt4(_createOptions, dst, dstIndex);
dstIndex += 4;
WriteInt4(_impersonationLevel, dst, dstIndex);
dstIndex += 4;
dst[dstIndex++] = _securityFlags;
return dstIndex - start;
}
// SECURITY_CONTEXT_TRACKING | SECURITY_EFFECTIVE_ONLY
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x00));
// name length without counting null termination
_namelenIndex = dstIndex;
dstIndex += 2;
WriteInt4(Flags0, dst, dstIndex);
dstIndex += 4;
WriteInt4(_rootDirectoryFid, dst, dstIndex);
dstIndex += 4;
WriteInt4(DesiredAccess, dst, dstIndex);
dstIndex += 4;
WriteInt8(_allocationSize, dst, dstIndex);
dstIndex += 8;
WriteInt4(_extFileAttributes, dst, dstIndex);
dstIndex += 4;
WriteInt4(_shareAccess, dst, dstIndex);
dstIndex += 4;
WriteInt4(_createDisposition, dst, dstIndex);
dstIndex += 4;
WriteInt4(_createOptions, dst, dstIndex);
dstIndex += 4;
WriteInt4(_impersonationLevel, dst, dstIndex);
dstIndex += 4;
dst[dstIndex++] = _securityFlags;
return dstIndex - start;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int n;
n = WriteString(Path, dst, dstIndex);
WriteInt2((UseUnicode ? Path.Length * 2 : n), dst, _namelenIndex);
return n;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int n;
n = WriteString(Path, dst, dstIndex);
WriteInt2((UseUnicode ? Path.Length * 2 : n), dst, _namelenIndex);
return n;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
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 + "]";
}
}
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 + "]";
}
}
}

View File

@ -19,104 +19,98 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class SmbComNtCreateAndXResponse : AndXServerMessageBlock
{
internal const int ExclusiveOplockGranted = 1;
internal class SmbComNtCreateAndXResponse : AndXServerMessageBlock
{
internal const int ExclusiveOplockGranted = 1;
internal const int BatchOplockGranted = 2;
internal const int BatchOplockGranted = 2;
internal const int LevelIiOplockGranted = 3;
internal const int LevelIiOplockGranted = 3;
internal byte OplockLevel;
internal byte OplockLevel;
internal int Fid;
internal int Fid;
internal int CreateAction;
internal int CreateAction;
internal int ExtFileAttributes;
internal int ExtFileAttributes;
internal int FileType;
internal int FileType;
internal int DeviceState;
internal int DeviceState;
internal long CreationTime;
internal long CreationTime;
internal long LastAccessTime;
internal long LastAccessTime;
internal long LastWriteTime;
internal long LastWriteTime;
internal long ChangeTime;
internal long ChangeTime;
internal long AllocationSize;
internal long AllocationSize;
internal long EndOfFile;
internal long EndOfFile;
internal bool Directory;
internal bool Directory;
internal bool IsExtended;
internal bool IsExtended;
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
OplockLevel = buffer[bufferIndex++];
Fid = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
CreateAction = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
CreationTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
LastAccessTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
LastWriteTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
ChangeTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
ExtFileAttributes = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
AllocationSize = ReadInt8(buffer, bufferIndex);
bufferIndex += 8;
EndOfFile = ReadInt8(buffer, bufferIndex);
bufferIndex += 8;
FileType = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
DeviceState = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Directory = (buffer[bufferIndex++] & unchecked(0xFF)) > 0;
return bufferIndex - start;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
int start = bufferIndex;
OplockLevel = buffer[bufferIndex++];
Fid = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
CreateAction = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
CreationTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
LastAccessTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
LastWriteTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
ChangeTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
ExtFileAttributes = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
AllocationSize = ReadInt8(buffer, bufferIndex);
bufferIndex += 8;
EndOfFile = ReadInt8(buffer, bufferIndex);
bufferIndex += 8;
FileType = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
DeviceState = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Directory = (buffer[bufferIndex++] & unchecked(0xFF)) > 0;
return bufferIndex - start;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
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
+ ",directory=" + Directory + "]";
}
}
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
+ ",directory=" + Directory + "]";
}
}
}

View File

@ -19,53 +19,52 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class SmbComNegotiate : ServerMessageBlock
{
private const string Dialects = "\u0002NT LM 0.12\u0000";
internal class SmbComNegotiate : ServerMessageBlock
{
private const string Dialects = "\u0002NT LM 0.12\u0000";
public SmbComNegotiate()
{
Command = SmbComNegotiate;
public SmbComNegotiate()
{
Command = SmbComNegotiate;
Flags2 = SmbConstants.DefaultFlags2;
}
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
byte[] dialects;
try
{
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
byte[] dialects;
try
{
//dialects = Runtime.GetBytesForString(Dialects, "ASCII");
dialects = Runtime.GetBytesForString(Dialects, "UTF-8");
}
catch (UnsupportedEncodingException)
{
return 0;
}
Array.Copy(dialects, 0, dst, dstIndex, dialects.Length);
return dialects.Length;
}
}
catch (UnsupportedEncodingException)
{
return 0;
}
Array.Copy(dialects, 0, dst, dstIndex, dialects.Length);
return dialects.Length;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
public override string ToString()
{
return "SmbComNegotiate["
+ base.ToString()
+ ",wordCount=" + WordCount
+ ",dialects=NT LM 0.12]";
}
}
public override string ToString()
{
return "SmbComNegotiate[" + base.ToString() + ",wordCount=" + WordCount
+ ",dialects=NT LM 0.12]";
}
}
}

View File

@ -20,160 +20,145 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class SmbComNegotiateResponse : ServerMessageBlock
{
internal int DialectIndex;
internal class SmbComNegotiateResponse : ServerMessageBlock
{
internal int DialectIndex;
internal SmbTransport.ServerData Server;
internal SmbTransport.ServerData Server;
internal SmbComNegotiateResponse(SmbTransport.ServerData server)
{
this.Server = server;
}
internal SmbComNegotiateResponse(SmbTransport.ServerData server)
{
this.Server = server;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
DialectIndex = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
if (DialectIndex > 10)
{
return bufferIndex - start;
}
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.MaxMpxCount = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Server.MaxNumberVcs = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Server.MaxBufferSize = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.MaxRawSize = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.SessionKey = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.Capabilities = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.ServerTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
Server.ServerTimeZone = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Server.EncryptionKeyLength = buffer[bufferIndex++] & unchecked(0xFF);
return bufferIndex - start;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
int start = bufferIndex;
DialectIndex = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
if (DialectIndex > 10)
{
return bufferIndex - start;
}
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.MaxMpxCount = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Server.MaxNumberVcs = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Server.MaxBufferSize = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.MaxRawSize = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.SessionKey = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.Capabilities = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
Server.ServerTime = ReadTime(buffer, bufferIndex);
bufferIndex += 8;
Server.ServerTimeZone = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Server.EncryptionKeyLength = buffer[bufferIndex++] & unchecked(0xFF);
return bufferIndex - start;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == 0)
{
Server.EncryptionKey = new byte[Server.EncryptionKeyLength];
Array.Copy(buffer,
bufferIndex,
Server.EncryptionKey,
0,
Server.EncryptionKeyLength);
bufferIndex += Server.EncryptionKeyLength;
if (ByteCount > Server.EncryptionKeyLength)
{
int len = 0;
// TODO: we can use new string routine here
try
{
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == 0)
{
Server.EncryptionKey = new byte[Server.EncryptionKeyLength];
Array.Copy(buffer, bufferIndex, Server.EncryptionKey, 0, Server.EncryptionKeyLength
);
bufferIndex += Server.EncryptionKeyLength;
if (ByteCount > Server.EncryptionKeyLength)
{
int len = 0;
// TODO: we can use new string routine here
try
{
if ((Flags2 & SmbConstants.Flags2Unicode) == SmbConstants.Flags2Unicode)
{
while (buffer[bufferIndex + len] != unchecked(unchecked(0x00))
|| buffer[bufferIndex + len + 1] != unchecked(unchecked(0x00)))
{
len += 2;
if (len > 256)
{
throw new RuntimeException("zero termination not found");
}
}
Server.OemDomainName = Runtime.GetStringForBytes(buffer,
bufferIndex,
len,
SmbConstants.UniEncoding);
}
else
{
while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)))
{
len++;
if (len > 256)
{
throw new RuntimeException("zero termination not found");
}
}
Server.OemDomainName = Runtime.GetStringForBytes(buffer,
bufferIndex,
len,
SmbConstants.OemEncoding);
}
}
catch (UnsupportedEncodingException uee)
{
if (Log.Level > 1)
{
Runtime.PrintStackTrace(uee, Log);
}
}
bufferIndex += len;
}
else
{
Server.OemDomainName = "";
}
}
else
{
Server.Guid = new byte[16];
Array.Copy(buffer, bufferIndex, Server.Guid, 0, 16);
Server.OemDomainName = "";
}
// ignore SPNEGO token for now ...
return bufferIndex - start;
}
{
while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)) || buffer
[bufferIndex + len + 1] != unchecked(unchecked(0x00)))
{
len += 2;
if (len > 256)
{
throw new RuntimeException("zero termination not found");
}
}
Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len
, SmbConstants.UniEncoding);
}
else
{
while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)))
{
len++;
if (len > 256)
{
throw new RuntimeException("zero termination not found");
}
}
Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len
, SmbConstants.OemEncoding);
}
}
catch (UnsupportedEncodingException uee)
{
if (Log.Level > 1)
{
Runtime.PrintStackTrace(uee, Log);
}
}
bufferIndex += len;
}
else
{
Server.OemDomainName = "";
}
}
else
{
Server.Guid = new byte[16];
Array.Copy(buffer, bufferIndex, Server.Guid, 0, 16);
Server.OemDomainName = "";
}
// ignore SPNEGO token for now ...
return bufferIndex - start;
}
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 + "]";
}
}
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 + "]";
}
}
}

View File

@ -16,78 +16,78 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal abstract class SmbComNtTransaction : SmbComTransaction
{
private const int NttPrimarySetupOffset = 69;
internal abstract class SmbComNtTransaction : SmbComTransaction
{
private const int NttPrimarySetupOffset = 69;
private const int NttSecondaryParameterOffset = 51;
private const int NttSecondaryParameterOffset = 51;
internal const int NtTransactQuerySecurityDesc = 6;
internal const int NtTransactQuerySecurityDesc = 6;
internal int Function;
internal int Function;
public SmbComNtTransaction()
{
// relative to headerStart
primarySetupOffset = NttPrimarySetupOffset;
secondaryParameterOffset = NttSecondaryParameterOffset;
}
public SmbComNtTransaction()
{
// relative to headerStart
primarySetupOffset = NttPrimarySetupOffset;
secondaryParameterOffset = NttSecondaryParameterOffset;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
if (Command != SmbComNtTransactSecondary)
{
dst[dstIndex++] = MaxSetupCount;
}
else
{
dst[dstIndex++] = unchecked(unchecked(0x00));
}
// Reserved
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
WriteInt4(TotalParameterCount, dst, dstIndex);
dstIndex += 4;
WriteInt4(TotalDataCount, dst, dstIndex);
dstIndex += 4;
if (Command != SmbComNtTransactSecondary)
{
WriteInt4(MaxParameterCount, dst, dstIndex);
dstIndex += 4;
WriteInt4(MaxDataCount, dst, dstIndex);
dstIndex += 4;
}
WriteInt4(ParameterCount, dst, dstIndex);
dstIndex += 4;
WriteInt4((ParameterCount == 0 ? 0 : ParameterOffset), dst, dstIndex);
dstIndex += 4;
if (Command == SmbComNtTransactSecondary)
{
WriteInt4(ParameterDisplacement, dst, dstIndex);
dstIndex += 4;
}
WriteInt4(DataCount, dst, dstIndex);
dstIndex += 4;
WriteInt4((DataCount == 0 ? 0 : DataOffset), dst, dstIndex);
dstIndex += 4;
if (Command == SmbComNtTransactSecondary)
{
WriteInt4(DataDisplacement, dst, dstIndex);
dstIndex += 4;
dst[dstIndex++] = unchecked(unchecked(0x00));
}
else
{
// Reserved1
dst[dstIndex++] = unchecked((byte)SetupCount);
WriteInt2(Function, dst, dstIndex);
dstIndex += 2;
dstIndex += WriteSetupWireFormat(dst, dstIndex);
}
return dstIndex - start;
}
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
if (Command != SmbComNtTransactSecondary)
{
dst[dstIndex++] = MaxSetupCount;
}
else
{
dst[dstIndex++] = unchecked(unchecked(0x00));
}
// Reserved
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
dst[dstIndex++] = unchecked(unchecked(0x00));
// Reserved
WriteInt4(TotalParameterCount, dst, dstIndex);
dstIndex += 4;
WriteInt4(TotalDataCount, dst, dstIndex);
dstIndex += 4;
if (Command != SmbComNtTransactSecondary)
{
WriteInt4(MaxParameterCount, dst, dstIndex);
dstIndex += 4;
WriteInt4(MaxDataCount, dst, dstIndex);
dstIndex += 4;
}
WriteInt4(ParameterCount, dst, dstIndex);
dstIndex += 4;
WriteInt4((ParameterCount == 0 ? 0 : ParameterOffset), dst, dstIndex);
dstIndex += 4;
if (Command == SmbComNtTransactSecondary)
{
WriteInt4(ParameterDisplacement, dst, dstIndex);
dstIndex += 4;
}
WriteInt4(DataCount, dst, dstIndex);
dstIndex += 4;
WriteInt4((DataCount == 0 ? 0 : DataOffset), dst, dstIndex);
dstIndex += 4;
if (Command == SmbComNtTransactSecondary)
{
WriteInt4(DataDisplacement, dst, dstIndex);
dstIndex += 4;
dst[dstIndex++] = unchecked(unchecked(0x00));
}
else
{
// Reserved1
dst[dstIndex++] = unchecked((byte)SetupCount);
WriteInt2(Function, dst, dstIndex);
dstIndex += 2;
dstIndex += WriteSetupWireFormat(dst, dstIndex);
}
return dstIndex - start;
}
}
}

View File

@ -16,47 +16,48 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal abstract class SmbComNtTransactionResponse : SmbComTransactionResponse
{
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
buffer[bufferIndex++] = unchecked(unchecked(0x00));
// Reserved
buffer[bufferIndex++] = unchecked(unchecked(0x00));
// Reserved
buffer[bufferIndex++] = unchecked(unchecked(0x00));
// Reserved
TotalParameterCount = ReadInt4(buffer, bufferIndex);
if (BufDataStart == 0)
{
BufDataStart = TotalParameterCount;
}
bufferIndex += 4;
TotalDataCount = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
ParameterCount = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
ParameterOffset = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
ParameterDisplacement = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
DataCount = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
DataOffset = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
DataDisplacement = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
SetupCount = buffer[bufferIndex] & unchecked(0xFF);
bufferIndex += 2;
if (SetupCount != 0)
{
if (Log.Level >= 3)
{
Log.WriteLine("setupCount is not zero: " + SetupCount);
}
}
return bufferIndex - start;
}
}
internal abstract class SmbComNtTransactionResponse : SmbComTransactionResponse
{
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
int start = bufferIndex;
buffer[bufferIndex++] = unchecked(unchecked(0x00));
// Reserved
buffer[bufferIndex++] = unchecked(unchecked(0x00));
// Reserved
buffer[bufferIndex++] = unchecked(unchecked(0x00));
// Reserved
TotalParameterCount = ReadInt4(buffer, bufferIndex);
if (BufDataStart == 0)
{
BufDataStart = TotalParameterCount;
}
bufferIndex += 4;
TotalDataCount = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
ParameterCount = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
ParameterOffset = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
ParameterDisplacement = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
DataCount = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
DataOffset = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
DataDisplacement = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
SetupCount = buffer[bufferIndex] & unchecked(0xFF);
bufferIndex += 2;
if (SetupCount != 0)
{
if (Log.Level >= 3)
{
Log.WriteLine("setupCount is not zero: " + SetupCount);
}
}
return bufferIndex - start;
}
}
}

View File

@ -19,179 +19,172 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb
{
internal class SmbComOpenAndX : AndXServerMessageBlock
{
private const int FlagsReturnAdditionalInfo = 0x01;
internal class SmbComOpenAndX : AndXServerMessageBlock
{
private const int FlagsReturnAdditionalInfo = 0x01;
private const int FlagsRequestOplock = 0x02;
private const int FlagsRequestOplock = 0x02;
private const int FlagsRequestBatchOplock = 0x04;
private const int FlagsRequestBatchOplock = 0x04;
private const int SharingCompatibility = 0x00;
private const int SharingCompatibility = 0x00;
private const int SharingDenyReadWriteExecute = 0x10;
private const int SharingDenyReadWriteExecute = 0x10;
private const int SharingDenyWrite = 0x20;
private const int SharingDenyWrite = 0x20;
private const int SharingDenyReadExecute = 0x30;
private const int SharingDenyReadExecute = 0x30;
private const int SharingDenyNone = 0x40;
private const int SharingDenyNone = 0x40;
private const int DoNotCache = 0x1000;
private const int DoNotCache = 0x1000;
private const int WriteThrough = 0x4000;
private const int WriteThrough = 0x4000;
private const int OpenFnCreate = 0x10;
private const int OpenFnCreate = 0x10;
private const int OpenFnFailIfExists = 0x00;
private const int OpenFnFailIfExists = 0x00;
private const int OpenFnOpen = 0x01;
private const int OpenFnOpen = 0x01;
private const int OpenFnTrunc = 0x02;
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;
internal int flags;
internal int DesiredAccess;
internal int DesiredAccess;
internal int SearchAttributes;
internal int SearchAttributes;
internal int FileAttributes;
internal int FileAttributes;
internal int CreationTime;
internal int CreationTime;
internal int OpenFunction;
internal int OpenFunction;
internal int AllocationSize;
internal int AllocationSize;
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
// bit 12
// bit 14
// flags is NOT the same as flags member
Path = fileName;
Command = SmbComOpenAndx;
DesiredAccess = access & 0x3;
if (DesiredAccess == 0x3)
{
DesiredAccess = 0x2;
}
DesiredAccess |= SharingDenyNone;
DesiredAccess &= ~0x1;
// Win98 doesn't like GENERIC_READ ?! -- get Access Denied.
// searchAttributes
SearchAttributes = SmbConstants.AttrDirectory
| SmbConstants.AttrHidden
| SmbConstants.AttrSystem;
// fileAttributes
FileAttributes = 0;
// openFunction
if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc)
{
// truncate the file
if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
{
// create it if necessary
OpenFunction = OpenFnTrunc | OpenFnCreate;
}
else
{
OpenFunction = OpenFnTrunc;
}
}
else
{
// don't truncate the file
if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
{
// create it if necessary
if ((flags & SmbFile.OExcl) == SmbFile.OExcl)
{
// fail if already exists
OpenFunction = OpenFnCreate | OpenFnFailIfExists;
}
else
{
OpenFunction = OpenFnCreate | OpenFnOpen;
}
}
else
{
OpenFunction = OpenFnOpen;
}
}
}
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
// bit 12
// bit 14
// flags is NOT the same as flags member
Path = fileName;
Command = SmbComOpenAndx;
DesiredAccess = access & 0x3;
if (DesiredAccess == 0x3)
{
DesiredAccess = 0x2;
}
DesiredAccess |= SharingDenyNone;
DesiredAccess &= ~0x1;
// Win98 doesn't like GENERIC_READ ?! -- get Access Denied.
// searchAttributes
SearchAttributes = SmbConstants.AttrDirectory | SmbConstants.AttrHidden | SmbConstants.AttrSystem;
// fileAttributes
FileAttributes = 0;
// openFunction
if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc)
{
// truncate the file
if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
{
// create it if necessary
OpenFunction = OpenFnTrunc | OpenFnCreate;
}
else
{
OpenFunction = OpenFnTrunc;
}
}
else
{
// don't truncate the file
if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
{
// create it if necessary
if ((flags & SmbFile.OExcl) == SmbFile.OExcl)
{
// fail if already exists
OpenFunction = OpenFnCreate | OpenFnFailIfExists;
}
else
{
OpenFunction = OpenFnCreate | OpenFnOpen;
}
}
else
{
OpenFunction = OpenFnOpen;
}
}
}
internal override int GetBatchLimit(byte command)
{
return command == SmbComReadAndx ? BatchLimit : 0;
}
internal override int GetBatchLimit(byte command)
{
return command == SmbComReadAndx ? BatchLimit : 0;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
WriteInt2(flags, dst, dstIndex);
dstIndex += 2;
WriteInt2(DesiredAccess, dst, dstIndex);
dstIndex += 2;
WriteInt2(SearchAttributes, dst, dstIndex);
dstIndex += 2;
WriteInt2(FileAttributes, dst, dstIndex);
dstIndex += 2;
CreationTime = 0;
WriteInt4(CreationTime, dst, dstIndex);
dstIndex += 4;
WriteInt2(OpenFunction, dst, dstIndex);
dstIndex += 2;
WriteInt4(AllocationSize, dst, dstIndex);
dstIndex += 4;
for (int i = 0; i < 8; i++)
{
dst[dstIndex++] = 0x00;
}
return dstIndex - start;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
WriteInt2(flags, dst, dstIndex);
dstIndex += 2;
WriteInt2(DesiredAccess, dst, dstIndex);
dstIndex += 2;
WriteInt2(SearchAttributes, dst, dstIndex);
dstIndex += 2;
WriteInt2(FileAttributes, dst, dstIndex);
dstIndex += 2;
CreationTime = 0;
WriteInt4(CreationTime, dst, dstIndex);
dstIndex += 4;
WriteInt2(OpenFunction, dst, dstIndex);
dstIndex += 2;
WriteInt4(AllocationSize, dst, dstIndex);
dstIndex += 4;
for (int i = 0; i < 8; i++)
{
dst[dstIndex++] = 0x00;
}
return dstIndex - start;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
if (UseUnicode)
{
dst[dstIndex++] = (byte)('\0');
}
dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
int start = dstIndex;
if (UseUnicode)
{
dst[dstIndex++] = (byte)('\0');
}
dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
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 + "]";
}
}
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 + "]";
}
}
}

View File

@ -16,78 +16,72 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb
{
internal class SmbComOpenAndXResponse : AndXServerMessageBlock
{
internal int Fid;
internal class SmbComOpenAndXResponse : AndXServerMessageBlock
{
internal int Fid;
internal int FileAttributes;
internal int FileAttributes;
internal int DataSize;
internal int DataSize;
internal int GrantedAccess;
internal int GrantedAccess;
internal int FileType;
internal int FileType;
internal int DeviceState;
internal int DeviceState;
internal int Action;
internal int Action;
internal int ServerFid;
internal int ServerFid;
internal long LastWriteTime;
internal long LastWriteTime;
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{
return 0;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
{
int start = bufferIndex;
Fid = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
FileAttributes = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
LastWriteTime = ReadUTime(buffer, bufferIndex);
bufferIndex += 4;
DataSize = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
GrantedAccess = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
FileType = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
DeviceState = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Action = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
ServerFid = ReadInt4(buffer, bufferIndex);
bufferIndex += 6;
return bufferIndex - start;
}
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex
)
{
int start = bufferIndex;
Fid = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
FileAttributes = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
LastWriteTime = ReadUTime(buffer, bufferIndex);
bufferIndex += 4;
DataSize = ReadInt4(buffer, bufferIndex);
bufferIndex += 4;
GrantedAccess = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
FileType = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
DeviceState = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
Action = ReadInt2(buffer, bufferIndex);
bufferIndex += 2;
ServerFid = ReadInt4(buffer, bufferIndex);
bufferIndex += 6;
return bufferIndex - start;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{
return 0;
}
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 + "]";
}
}
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 + "]";
}
}
}

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