Merge pull request #2716 from MediaBrowser/dev

Dev
This commit is contained in:
Luke 2017-06-21 10:52:09 -04:00 committed by GitHub
commit d67c5388dc
233 changed files with 25617 additions and 24652 deletions

View File

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

View File

@ -20,103 +20,105 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Dcerpc namespace SharpCifs.Dcerpc
{ {
public class DcerpcBinding public class DcerpcBinding
{ {
private static Hashtable _interfaces; private static Hashtable _interfaces;
static DcerpcBinding() static DcerpcBinding()
{ {
_interfaces = new Hashtable(); _interfaces = new Hashtable();
_interfaces.Put("srvsvc", Srvsvc.GetSyntax()); _interfaces.Put("srvsvc", Srvsvc.GetSyntax());
_interfaces.Put("lsarpc", Lsarpc.GetSyntax()); _interfaces.Put("lsarpc", Lsarpc.GetSyntax());
_interfaces.Put("samr", Samr.GetSyntax()); _interfaces.Put("samr", Samr.GetSyntax());
_interfaces.Put("netdfs", Netdfs.GetSyntax()); _interfaces.Put("netdfs", Netdfs.GetSyntax());
} }
public static void AddInterface(string name, string syntax) public static void AddInterface(string name, string syntax)
{ {
_interfaces.Put(name, 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) internal DcerpcBinding(string proto, string server)
{ {
this.Proto = proto; this.Proto = proto;
this.Server = server; this.Server = server;
} }
/// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception> /// <exception cref="SharpCifs.Dcerpc.DcerpcException"></exception>
internal virtual void SetOption(string key, object val) internal virtual void SetOption(string key, object val)
{ {
if (key.Equals("endpoint")) if (key.Equals("endpoint"))
{ {
Endpoint = val.ToString().ToLower(); Endpoint = val.ToString().ToLower();
if (Endpoint.StartsWith("\\pipe\\")) if (Endpoint.StartsWith("\\pipe\\"))
{ {
string iface = (string)_interfaces.Get(Runtime.Substring(Endpoint, 6)); string iface = (string)_interfaces.Get(Runtime.Substring(Endpoint, 6));
if (iface != null) if (iface != null)
{ {
int c; int c;
int p; int p;
c = iface.IndexOf(':'); c = iface.IndexOf(':');
p = iface.IndexOf('.', c + 1); p = iface.IndexOf('.', c + 1);
Uuid = new Uuid(Runtime.Substring(iface, 0, c)); Uuid = new Uuid(Runtime.Substring(iface, 0, c));
Major = Convert.ToInt32(Runtime.Substring(iface, c + 1, p)); Major = Convert.ToInt32(Runtime.Substring(iface, c + 1, p));
Minor = Convert.ToInt32(Runtime.Substring(iface, p + 1)); Minor = Convert.ToInt32(Runtime.Substring(iface, p + 1));
return; return;
} }
} }
throw new DcerpcException("Bad endpoint: " + Endpoint); throw new DcerpcException("Bad endpoint: " + Endpoint);
} }
if (Options == null) if (Options == null)
{ {
Options = new Hashtable(); Options = new Hashtable();
} }
Options.Put(key, val); Options.Put(key, val);
} }
internal virtual object GetOption(string key) internal virtual object GetOption(string key)
{ {
if (key.Equals("endpoint")) if (key.Equals("endpoint"))
{ {
return Endpoint; return Endpoint;
} }
if (Options != null) if (Options != null)
{ {
return Options.Get(key); 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; 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,25 +16,24 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc namespace SharpCifs.Dcerpc
{ {
public static class DcerpcConstants public static class DcerpcConstants
{ {
public static Uuid DcerpcUuidSyntaxNdr = new Uuid("8a885d04-1ceb-11c9-9fe8-08002b104860" public static Uuid DcerpcUuidSyntaxNdr = new Uuid("8a885d04-1ceb-11c9-9fe8-08002b104860");
);
public static int DcerpcFirstFrag = unchecked(0x01); public static int DcerpcFirstFrag = unchecked(0x01);
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,33 +16,49 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Dcerpc namespace SharpCifs.Dcerpc
{ {
public static class DcerpcError public static class DcerpcError
{ {
public static int DcerpcFaultOther = unchecked(0x00000001); 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 public static int[] DcerpcFaultCodes = {
, DcerpcFaultCantPerform, DcerpcFaultNdr, DcerpcFaultInvalidTag, DcerpcFaultContextMismatch DcerpcFaultOther,
, DcerpcFaultOpRngError, DcerpcFaultUnkIf, DcerpcFaultProtoError }; DcerpcFaultAccessDenied,
DcerpcFaultCantPerform,
DcerpcFaultNdr,
DcerpcFaultInvalidTag,
DcerpcFaultContextMismatch,
DcerpcFaultOpRngError,
DcerpcFaultUnkIf,
DcerpcFaultProtoError
};
public static string[] DcerpcFaultMessages = { "DCERPC_FAULT_OTHER" public static string[] DcerpcFaultMessages =
, "DCERPC_FAULT_ACCESS_DENIED", "DCERPC_FAULT_CANT_PERFORM", "DCERPC_FAULT_NDR", {
"DCERPC_FAULT_INVALID_TAG", "DCERPC_FAULT_CONTEXT_MISMATCH", "DCERPC_FAULT_OP_RNG_ERROR" "DCERPC_FAULT_OTHER",
, "DCERPC_FAULT_UNK_IF", "DCERPC_FAULT_PROTO_ERROR" }; "DCERPC_FAULT_ACCESS_DENIED",
} "DCERPC_FAULT_CANT_PERFORM",
"DCERPC_FAULT_NDR",
"DCERPC_FAULT_INVALID_TAG",
"DCERPC_FAULT_CONTEXT_MISMATCH",
"DCERPC_FAULT_OP_RNG_ERROR",
"DCERPC_FAULT_UNK_IF",
"DCERPC_FAULT_PROTO_ERROR"
};
}
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,17 +18,17 @@ using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc namespace SharpCifs.Dcerpc.Msrpc
{ {
internal class LsarSidArrayX : Lsarpc.LsarSidArray internal class LsarSidArrayX : Lsarpc.LsarSidArray
{ {
internal LsarSidArrayX(Sid[] sids) internal LsarSidArrayX(Sid[] sids)
{ {
NumSids = sids.Length; NumSids = sids.Length;
this.Sids = new Lsarpc.LsarSidPtr[sids.Length]; this.Sids = new Lsarpc.LsarSidPtr[sids.Length];
for (int si = 0; si < sids.Length; si++) for (int si = 0; si < sids.Length; si++)
{ {
this.Sids[si] = new Lsarpc.LsarSidPtr(); this.Sids[si] = new Lsarpc.LsarSidPtr();
this.Sids[si].Sid = sids[si]; 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 namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcDfsRootEnum : Netdfs.NetrDfsEnumEx public class MsrpcDfsRootEnum : Netdfs.NetrDfsEnumEx
{ {
public MsrpcDfsRootEnum(string server) : base(server, 200, unchecked(0xFFFF), new Netdfs.DfsEnumStruct(), new NdrLong(0)) public MsrpcDfsRootEnum(string server) : base(server, 200, unchecked(0xFFFF), new Netdfs.DfsEnumStruct(), new NdrLong(0))
{ {
Info.Level = Level; Info.Level = Level;
Info.E = new Netdfs.DfsEnumArray200(); Info.E = new Netdfs.DfsEnumArray200();
Ptype = 0; Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
} }
public virtual IFileEntry[] GetEntries() public virtual IFileEntry[] GetEntries()
{ {
Netdfs.DfsEnumArray200 a200 = (Netdfs.DfsEnumArray200)Info.E; Netdfs.DfsEnumArray200 a200 = (Netdfs.DfsEnumArray200)Info.E;
SmbShareInfo[] entries = new SmbShareInfo[a200.Count]; SmbShareInfo[] entries = new SmbShareInfo[a200.Count];
for (int i = 0; i < a200.Count; i++) for (int i = 0; i < a200.Count; i++)
{ {
entries[i] = new SmbShareInfo(a200.S[i].DfsName, 0, null); entries[i] = new SmbShareInfo(a200.S[i].DfsName, 0, null);
} }
return entries; return entries;
} }
} }
} }

View File

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

View File

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

View File

@ -18,17 +18,21 @@ using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcLookupSids : Lsarpc.LsarLookupSids public class MsrpcLookupSids : Lsarpc.LsarLookupSids
{ {
internal Sid[] sids; internal Sid[] sids;
public MsrpcLookupSids(LsaPolicyHandle policyHandle, Sid[] sids) : base(policyHandle public MsrpcLookupSids(LsaPolicyHandle policyHandle, Sid[] sids)
, new LsarSidArrayX(sids), new Lsarpc.LsarRefDomainList(), new Lsarpc.LsarTransNameArray : base(policyHandle,
(), 1, sids.Length) new LsarSidArrayX(sids),
{ new Lsarpc.LsarRefDomainList(),
this.sids = sids; new Lsarpc.LsarTransNameArray(),
Ptype = 0; 1,
sids.Length)
{
this.sids = sids;
Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,26 +18,26 @@ using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc namespace SharpCifs.Dcerpc.Msrpc
{ {
public class MsrpcShareGetInfo : Srvsvc.ShareGetInfo public class MsrpcShareGetInfo : Srvsvc.ShareGetInfo
{ {
public MsrpcShareGetInfo(string server, string sharename) : base(server, sharename public MsrpcShareGetInfo(string server, string sharename)
, 502, new Srvsvc.ShareInfo502()) : base(server, sharename, 502, new Srvsvc.ShareInfo502())
{ {
Ptype = 0; Ptype = 0;
Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag; Flags = DcerpcConstants.DcerpcFirstFrag | DcerpcConstants.DcerpcLastFrag;
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public virtual Ace[] GetSecurity() public virtual Ace[] GetSecurity()
{ {
Srvsvc.ShareInfo502 info502 = (Srvsvc.ShareInfo502)Info; Srvsvc.ShareInfo502 info502 = (Srvsvc.ShareInfo502)Info;
if (info502.SecurityDescriptor != null) if (info502.SecurityDescriptor != null)
{ {
SecurityDescriptor sd; SecurityDescriptor sd;
sd = new SecurityDescriptor(info502.SecurityDescriptor, 0, info502.SdSize); sd = new SecurityDescriptor(info502.SecurityDescriptor, 0, info502.SdSize);
return sd.Aces; return sd.Aces;
} }
return null; 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,23 +18,25 @@ using SharpCifs.Smb;
namespace SharpCifs.Dcerpc.Msrpc namespace SharpCifs.Dcerpc.Msrpc
{ {
public class SamrAliasHandle : Rpc.PolicyHandle public class SamrAliasHandle : Rpc.PolicyHandle
{ {
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public SamrAliasHandle(DcerpcHandle handle, SamrDomainHandle domainHandle, int access public SamrAliasHandle(DcerpcHandle handle,
, int rid) SamrDomainHandle domainHandle,
{ int access,
MsrpcSamrOpenAlias rpc = new MsrpcSamrOpenAlias(domainHandle, access, rid, this); int rid)
handle.Sendrecv(rpc); {
if (rpc.Retval != 0) MsrpcSamrOpenAlias rpc = new MsrpcSamrOpenAlias(domainHandle, access, rid, this);
{ handle.Sendrecv(rpc);
throw new SmbException(rpc.Retval, false); if (rpc.Retval != 0)
} {
} throw new SmbException(rpc.Retval, false);
}
}
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
public virtual void Close() public virtual void Close()
{ {
} }
} }
} }

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -20,429 +20,474 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Netbios namespace SharpCifs.Netbios
{ {
internal abstract class NameServicePacket internal abstract class NameServicePacket
{ {
internal const int Query = 0; 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 // opcode
// rcode // rcode
// type/class // type/class
// header field offsets // header field offsets
internal static void WriteInt2(int val, byte[] dst, int dstIndex) internal static void WriteInt2(int val, byte[] dst, int dstIndex)
{ {
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF))); dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF))); dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
} }
internal static void WriteInt4(int val, byte[] dst, int dstIndex) internal static void WriteInt4(int val, byte[] dst, int dstIndex)
{ {
dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF))); dst[dstIndex++] = unchecked((byte)((val >> 24) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF))); dst[dstIndex++] = unchecked((byte)((val >> 16) & unchecked(0xFF)));
dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF))); dst[dstIndex++] = unchecked((byte)((val >> 8) & unchecked(0xFF)));
dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF))); dst[dstIndex] = unchecked((byte)(val & unchecked(0xFF)));
} }
internal static int ReadInt2(byte[] src, int srcIndex) internal static int ReadInt2(byte[] src, int srcIndex)
{ {
return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked( return ((src[srcIndex] & unchecked(0xFF)) << 8) + (src[srcIndex + 1] & unchecked(
0xFF)); 0xFF));
} }
internal static int ReadInt4(byte[] src, int srcIndex) internal static int ReadInt4(byte[] src, int srcIndex)
{ {
return ((src[srcIndex] & unchecked(0xFF)) << 24) + ((src[srcIndex + 1] & unchecked( return ((src[srcIndex] & unchecked(0xFF)) << 24)
0xFF)) << 16) + ((src[srcIndex + 2] & unchecked(0xFF)) << 8) + (src + ((src[srcIndex + 1] & unchecked(0xFF)) << 16)
[srcIndex + 3] & unchecked(0xFF)); + ((src[srcIndex + 2] & unchecked(0xFF)) << 8)
} + (src[srcIndex + 3] & unchecked(0xFF));
}
internal static int ReadNameTrnId(byte[] src, int srcIndex) internal static int ReadNameTrnId(byte[] src, int srcIndex)
{ {
return ReadInt2(src, 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 Name RecordName;
internal int QuestionType; internal int QuestionType;
internal int QuestionClass; internal int QuestionClass;
internal int RecordType; internal int RecordType;
internal int RecordClass; internal int RecordClass;
internal int Ttl; internal int Ttl;
internal int RDataLength; internal int RDataLength;
internal IPAddress Addr; internal IPAddress Addr;
public NameServicePacket() public NameServicePacket()
{ {
IsRecurDesired = true; IsRecurDesired = true;
IsBroadcast = true; IsBroadcast = true;
QuestionCount = 1; QuestionCount = 1;
QuestionClass = In; QuestionClass = In;
} }
internal virtual int WriteWireFormat(byte[] dst, int dstIndex) internal virtual int WriteWireFormat(byte[] dst, int dstIndex)
{ {
int start = dstIndex; int start = dstIndex;
dstIndex += WriteHeaderWireFormat(dst, dstIndex); dstIndex += WriteHeaderWireFormat(dst, dstIndex);
dstIndex += WriteBodyWireFormat(dst, dstIndex); dstIndex += WriteBodyWireFormat(dst, dstIndex);
return dstIndex - start; return dstIndex - start;
} }
internal virtual int ReadWireFormat(byte[] src, int srcIndex) internal virtual int ReadWireFormat(byte[] src, int srcIndex)
{ {
int start = srcIndex; int start = srcIndex;
srcIndex += ReadHeaderWireFormat(src, srcIndex); srcIndex += ReadHeaderWireFormat(src, srcIndex);
srcIndex += ReadBodyWireFormat(src, srcIndex); srcIndex += ReadBodyWireFormat(src, srcIndex);
return srcIndex - start; return srcIndex - start;
} }
internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex) internal virtual int WriteHeaderWireFormat(byte[] dst, int dstIndex)
{ {
int start = dstIndex; int start = dstIndex;
WriteInt2(NameTrnId, dst, dstIndex); WriteInt2(NameTrnId, dst, dstIndex);
dst[dstIndex + OpcodeOffset] = unchecked((byte)((IsResponse ? unchecked(0x80) : unchecked(0x00)) + ((OpCode << 3) & unchecked(0x78)) + (IsAuthAnswer dst[dstIndex + OpcodeOffset] = unchecked(
? unchecked(0x04) : unchecked(0x00)) + (IsTruncated ? unchecked(0x02) : unchecked(0x00)) + (IsRecurDesired ? unchecked(0x01) (byte)(
: unchecked(0x00)))); (IsResponse
dst[dstIndex + OpcodeOffset + 1] = unchecked((byte)((IsRecurAvailable ? unchecked( ? unchecked(0x80)
0x80) : unchecked(0x00)) + (IsBroadcast ? unchecked(0x10) : : unchecked(0x00))
unchecked(0x00)) + (ResultCode & unchecked(0x0F)))); + ((OpCode << 3) & unchecked(0x78))
WriteInt2(QuestionCount, dst, start + QuestionOffset); + (IsAuthAnswer
WriteInt2(AnswerCount, dst, start + AnswerOffset); ? unchecked(0x04)
WriteInt2(AuthorityCount, dst, start + AuthorityOffset); : unchecked(0x00))
WriteInt2(AdditionalCount, dst, start + AdditionalOffset); + (IsTruncated
return HeaderLength; ? unchecked(0x02)
} : unchecked(0x00))
+ (IsRecurDesired
internal virtual int ReadHeaderWireFormat(byte[] src, int srcIndex) ? unchecked(0x01)
{ : unchecked(0x00))
NameTrnId = ReadInt2(src, srcIndex); )
IsResponse = ((src[srcIndex + OpcodeOffset] & unchecked(0x80)) == 0) ? false );
: true; dst[dstIndex + OpcodeOffset + 1] = unchecked(
OpCode = (src[srcIndex + OpcodeOffset] & unchecked(0x78)) >> 3; (byte)(
IsAuthAnswer = ((src[srcIndex + OpcodeOffset] & unchecked(0x04)) == 0) ? (IsRecurAvailable
false : true; ? unchecked(0x80)
IsTruncated = ((src[srcIndex + OpcodeOffset] & unchecked(0x02)) == 0) ? false : unchecked(0x00))
: true; + (IsBroadcast
IsRecurDesired = ((src[srcIndex + OpcodeOffset] & unchecked(0x01)) == 0) ? ? unchecked(0x10)
false : true; : unchecked(0x00))
IsRecurAvailable = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x80)) + (ResultCode & unchecked(0x0F))
== 0) ? false : true; )
IsBroadcast = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x10)) == 0) );
? false : true; WriteInt2(QuestionCount, dst, start + QuestionOffset);
ResultCode = src[srcIndex + OpcodeOffset + 1] & unchecked(0x0F); WriteInt2(AnswerCount, dst, start + AnswerOffset);
QuestionCount = ReadInt2(src, srcIndex + QuestionOffset); WriteInt2(AuthorityCount, dst, start + AuthorityOffset);
AnswerCount = ReadInt2(src, srcIndex + AnswerOffset); WriteInt2(AdditionalCount, dst, start + AdditionalOffset);
AuthorityCount = ReadInt2(src, srcIndex + AuthorityOffset); return HeaderLength;
AdditionalCount = ReadInt2(src, srcIndex + AdditionalOffset); }
return HeaderLength;
} internal virtual int ReadHeaderWireFormat(byte[] src, int srcIndex)
{
internal virtual int WriteQuestionSectionWireFormat(byte[] dst, int dstIndex) NameTrnId = ReadInt2(src, srcIndex);
{
int start = dstIndex; IsResponse = ((src[srcIndex + OpcodeOffset] & unchecked(0x80)) == 0)
dstIndex += QuestionName.WriteWireFormat(dst, dstIndex); ? false
WriteInt2(QuestionType, dst, dstIndex); : true;
dstIndex += 2; OpCode = (src[srcIndex + OpcodeOffset] & unchecked(0x78)) >> 3;
WriteInt2(QuestionClass, dst, dstIndex); IsAuthAnswer = ((src[srcIndex + OpcodeOffset] & unchecked(0x04)) == 0)
dstIndex += 2; ? false
return dstIndex - start; : true;
} IsTruncated = ((src[srcIndex + OpcodeOffset] & unchecked(0x02)) == 0)
? false
internal virtual int ReadQuestionSectionWireFormat(byte[] src, int srcIndex) : true;
{ IsRecurDesired = ((src[srcIndex + OpcodeOffset] & unchecked(0x01)) == 0)
int start = srcIndex; ? false
srcIndex += QuestionName.ReadWireFormat(src, srcIndex); : true;
QuestionType = ReadInt2(src, srcIndex); IsRecurAvailable = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x80)) == 0)
srcIndex += 2; ? false
QuestionClass = ReadInt2(src, srcIndex); : true;
srcIndex += 2; IsBroadcast = ((src[srcIndex + OpcodeOffset + 1] & unchecked(0x10)) == 0)
return srcIndex - start; ? false
} : true;
ResultCode = src[srcIndex + OpcodeOffset + 1] & unchecked(0x0F);
internal virtual int WriteResourceRecordWireFormat(byte[] dst, int dstIndex) QuestionCount = ReadInt2(src, srcIndex + QuestionOffset);
{ AnswerCount = ReadInt2(src, srcIndex + AnswerOffset);
int start = dstIndex; AuthorityCount = ReadInt2(src, srcIndex + AuthorityOffset);
if (RecordName == QuestionName) AdditionalCount = ReadInt2(src, srcIndex + AdditionalOffset);
{ return HeaderLength;
dst[dstIndex++] = unchecked(unchecked(0xC0)); }
// label string pointer to
dst[dstIndex++] = unchecked(unchecked(0x0C)); internal virtual int WriteQuestionSectionWireFormat(byte[] dst, int dstIndex)
} {
else int start = dstIndex;
{ dstIndex += QuestionName.WriteWireFormat(dst, dstIndex);
// questionName (offset 12) WriteInt2(QuestionType, dst, dstIndex);
dstIndex += RecordName.WriteWireFormat(dst, dstIndex); dstIndex += 2;
} WriteInt2(QuestionClass, dst, dstIndex);
WriteInt2(RecordType, dst, dstIndex); dstIndex += 2;
dstIndex += 2; return dstIndex - start;
WriteInt2(RecordClass, dst, dstIndex); }
dstIndex += 2;
WriteInt4(Ttl, dst, dstIndex); internal virtual int ReadQuestionSectionWireFormat(byte[] src, int srcIndex)
dstIndex += 4; {
RDataLength = WriteRDataWireFormat(dst, dstIndex + 2); int start = srcIndex;
WriteInt2(RDataLength, dst, dstIndex); srcIndex += QuestionName.ReadWireFormat(src, srcIndex);
dstIndex += 2 + RDataLength; QuestionType = ReadInt2(src, srcIndex);
return dstIndex - start; srcIndex += 2;
} QuestionClass = ReadInt2(src, srcIndex);
srcIndex += 2;
internal virtual int ReadResourceRecordWireFormat(byte[] src, int srcIndex) return srcIndex - start;
{ }
int start = srcIndex;
int end; internal virtual int WriteResourceRecordWireFormat(byte[] dst, int dstIndex)
if ((src[srcIndex] & unchecked(0xC0)) == unchecked(0xC0)) {
{ int start = dstIndex;
RecordName = QuestionName; if (RecordName == QuestionName)
// label string pointer to questionName {
srcIndex += 2; dst[dstIndex++] = unchecked(unchecked(0xC0));
} // label string pointer to
else dst[dstIndex++] = unchecked(unchecked(0x0C));
{ }
srcIndex += RecordName.ReadWireFormat(src, srcIndex); else
} {
RecordType = ReadInt2(src, srcIndex); // questionName (offset 12)
srcIndex += 2; dstIndex += RecordName.WriteWireFormat(dst, dstIndex);
RecordClass = ReadInt2(src, srcIndex); }
srcIndex += 2; WriteInt2(RecordType, dst, dstIndex);
Ttl = ReadInt4(src, srcIndex); dstIndex += 2;
srcIndex += 4; WriteInt2(RecordClass, dst, dstIndex);
RDataLength = ReadInt2(src, srcIndex); dstIndex += 2;
srcIndex += 2; WriteInt4(Ttl, dst, dstIndex);
AddrEntry = new NbtAddress[RDataLength / 6]; dstIndex += 4;
end = srcIndex + RDataLength; RDataLength = WriteRDataWireFormat(dst, dstIndex + 2);
for (AddrIndex = 0; srcIndex < end; AddrIndex++) WriteInt2(RDataLength, dst, dstIndex);
{ dstIndex += 2 + RDataLength;
srcIndex += ReadRDataWireFormat(src, srcIndex); return dstIndex - start;
} }
return srcIndex - start;
} internal virtual int ReadResourceRecordWireFormat(byte[] src, int srcIndex)
{
internal abstract int WriteBodyWireFormat(byte[] dst, int dstIndex); int start = srcIndex;
int end;
internal abstract int ReadBodyWireFormat(byte[] src, int srcIndex); if ((src[srcIndex] & unchecked(0xC0)) == unchecked(0xC0))
{
internal abstract int WriteRDataWireFormat(byte[] dst, int dstIndex); RecordName = QuestionName;
// label string pointer to questionName
internal abstract int ReadRDataWireFormat(byte[] src, int srcIndex); srcIndex += 2;
}
public override string ToString() else
{ {
string opCodeString; srcIndex += RecordName.ReadWireFormat(src, srcIndex);
string resultCodeString; }
string questionTypeString; RecordType = ReadInt2(src, srcIndex);
string recordTypeString; srcIndex += 2;
RecordClass = ReadInt2(src, srcIndex);
switch (OpCode) srcIndex += 2;
{ Ttl = ReadInt4(src, srcIndex);
case Query: srcIndex += 4;
{ RDataLength = ReadInt2(src, srcIndex);
opCodeString = "QUERY"; srcIndex += 2;
break; AddrEntry = new NbtAddress[RDataLength / 6];
} end = srcIndex + RDataLength;
for (AddrIndex = 0; srcIndex < end; AddrIndex++)
case Wack: {
{ srcIndex += ReadRDataWireFormat(src, srcIndex);
opCodeString = "WACK"; }
break; return srcIndex - start;
} }
default: internal abstract int WriteBodyWireFormat(byte[] dst, int dstIndex);
{
opCodeString = Extensions.ToString(OpCode); internal abstract int ReadBodyWireFormat(byte[] src, int srcIndex);
break;
} internal abstract int WriteRDataWireFormat(byte[] dst, int dstIndex);
}
switch (ResultCode) internal abstract int ReadRDataWireFormat(byte[] src, int srcIndex);
{
case FmtErr: public override string ToString()
{ {
resultCodeString = "FMT_ERR"; string opCodeString;
break; string resultCodeString;
} string questionTypeString;
string recordTypeString;
case SrvErr:
{ switch (OpCode)
resultCodeString = "SRV_ERR"; {
break; case Query:
} {
opCodeString = "QUERY";
case ImpErr: break;
{ }
resultCodeString = "IMP_ERR";
break; case Wack:
} {
opCodeString = "WACK";
case RfsErr: break;
{ }
resultCodeString = "RFS_ERR";
break; default:
} {
opCodeString = Extensions.ToString(OpCode);
case ActErr: break;
{ }
resultCodeString = "ACT_ERR"; }
break; switch (ResultCode)
} {
case FmtErr:
case CftErr: {
{ resultCodeString = "FMT_ERR";
resultCodeString = "CFT_ERR"; break;
break; }
}
case SrvErr:
default: {
{ resultCodeString = "SRV_ERR";
resultCodeString = "0x" + Hexdump.ToHexString(ResultCode, 1); break;
break; }
}
} case ImpErr:
switch (QuestionType) {
{ resultCodeString = "IMP_ERR";
case Nb: break;
{ }
questionTypeString = "NB";
break; case RfsErr:
} {
resultCodeString = "RFS_ERR";
case Nbstat: break;
{ }
questionTypeString = "NBSTAT";
break; case ActErr:
} {
resultCodeString = "ACT_ERR";
default: break;
{ }
questionTypeString = "0x" + Hexdump.ToHexString(QuestionType, 4);
break; case CftErr:
} {
} resultCodeString = "CFT_ERR";
switch (RecordType) break;
{ }
case A:
{ default:
recordTypeString = "A"; {
break; resultCodeString = "0x" + Hexdump.ToHexString(ResultCode, 1);
} break;
}
case Ns: }
{ switch (QuestionType)
recordTypeString = "NS"; {
break; case Nb:
} {
questionTypeString = "NB";
case Null: break;
{ }
recordTypeString = "NULL";
break; case Nbstat:
} {
questionTypeString = "NBSTAT";
case Nb: break;
{ }
recordTypeString = "NB";
break; default:
} {
questionTypeString = "0x" + Hexdump.ToHexString(QuestionType, 4);
case Nbstat: break;
{ }
recordTypeString = "NBSTAT"; }
break; switch (RecordType)
} {
case A:
default: {
{ recordTypeString = "A";
recordTypeString = "0x" + Hexdump.ToHexString(RecordType, 4); break;
break; }
}
} case Ns:
return "nameTrnId=" + NameTrnId + ",isResponse=" + IsResponse + ",opCode=" {
+ opCodeString + ",isAuthAnswer=" + IsAuthAnswer + ",isTruncated=" + IsTruncated recordTypeString = "NS";
+ ",isRecurAvailable=" + IsRecurAvailable + ",isRecurDesired=" + IsRecurDesired break;
+ ",isBroadcast=" + IsBroadcast + ",resultCode=" + ResultCode + ",questionCount=" }
+ QuestionCount + ",answerCount=" + AnswerCount + ",authorityCount=" + AuthorityCount
+ ",additionalCount=" + AdditionalCount + ",questionName=" + QuestionName + ",questionType=" case Null:
+ questionTypeString + ",questionClass=" + (QuestionClass == In ? "IN" : "0x" + {
Hexdump.ToHexString(QuestionClass, 4)) + ",recordName=" + RecordName + ",recordType=" recordTypeString = "NULL";
+ recordTypeString + ",recordClass=" + (RecordClass == In ? "IN" : "0x" + Hexdump break;
.ToHexString(RecordClass, 4)) + ",ttl=" + Ttl + ",rDataLength=" + RDataLength; }
}
} 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,146 +19,147 @@ using System.IO;
namespace SharpCifs.Netbios namespace SharpCifs.Netbios
{ {
public class NbtException : IOException public class NbtException : IOException
{ {
public const int Success = 0; 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 // error classes
// name service error codes // name service error codes
// session service error codes // session service error codes
public static string GetErrorString(int errorClass, int errorCode) public static string GetErrorString(int errorClass, int errorCode)
{ {
string result = string.Empty; string result = string.Empty;
switch (errorClass) switch (errorClass)
{ {
case Success: case Success:
{ {
result += "SUCCESS"; result += "SUCCESS";
break; break;
} }
case ErrNamSrvc: case ErrNamSrvc:
{ {
result += "ERR_NAM_SRVC/"; result += "ERR_NAM_SRVC/";
switch (errorCode) switch (errorCode)
{ {
case FmtErr: case FmtErr:
{ {
result += "FMT_ERR: Format Error"; result += "FMT_ERR: Format Error";
goto default; goto default;
} }
default: default:
{ {
result += "Unknown error code: " + errorCode; result += "Unknown error code: " + errorCode;
break; break;
} }
} }
break; break;
} }
case ErrSsnSrvc: case ErrSsnSrvc:
{ {
result += "ERR_SSN_SRVC/"; result += "ERR_SSN_SRVC/";
switch (errorCode) switch (errorCode)
{ {
case ConnectionRefused: case ConnectionRefused:
{ {
result += "Connection refused"; result += "Connection refused";
break; break;
} }
case NotListeningCalled: case NotListeningCalled:
{ {
result += "Not listening on called name"; result += "Not listening on called name";
break; break;
} }
case NotListeningCalling: case NotListeningCalling:
{ {
result += "Not listening for calling name"; result += "Not listening for calling name";
break; break;
} }
case CalledNotPresent: case CalledNotPresent:
{ {
result += "Called name not present"; result += "Called name not present";
break; break;
} }
case NoResources: case NoResources:
{ {
result += "Called name present, but insufficient resources"; result += "Called name present, but insufficient resources";
break; break;
} }
case Unspecified: case Unspecified:
{ {
result += "Unspecified error"; result += "Unspecified error";
break; break;
} }
default: default:
{ {
result += "Unknown error code: " + errorCode; result += "Unknown error code: " + errorCode;
break; break;
} }
} }
break; break;
} }
default: default:
{ {
result += "unknown error class: " + errorClass; result += "unknown error class: " + errorClass;
break; break;
} }
} }
return result; return result;
} }
public NbtException(int errorClass, int errorCode) : base(GetErrorString(errorClass public NbtException(int errorClass, int errorCode) : base(GetErrorString(errorClass
, errorCode)) , errorCode))
{ {
this.ErrorClass = errorClass; this.ErrorClass = errorClass;
this.ErrorCode = errorCode; this.ErrorCode = errorCode;
} }
public override string ToString() public override string ToString()
{ {
return "errorClass=" + ErrorClass + ",errorCode=" + ErrorCode + ",errorString=" return "errorClass=" + ErrorClass
+ GetErrorString(ErrorClass, ErrorCode); + ",errorCode=" + ErrorCode
} + ",errorString=" + GetErrorString(ErrorClass, ErrorCode);
} }
}
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,123 +18,137 @@ using System;
namespace SharpCifs.Ntlmssp namespace SharpCifs.Ntlmssp
{ {
/// <summary>Abstract superclass for all NTLMSSP messages.</summary> /// <summary>Abstract superclass for all NTLMSSP messages.</summary>
/// <remarks>Abstract superclass for all NTLMSSP messages.</remarks> /// <remarks>Abstract superclass for all NTLMSSP messages.</remarks>
public abstract class NtlmMessage : NtlmFlags public abstract class NtlmMessage : NtlmFlags
{ {
/// <summary>The NTLMSSP "preamble".</summary> /// <summary>The NTLMSSP "preamble".</summary>
/// <remarks>The NTLMSSP "preamble".</remarks> /// <remarks>The NTLMSSP "preamble".</remarks>
protected internal static readonly byte[] NtlmsspSignature = { unchecked( protected internal static readonly byte[] NtlmsspSignature =
(byte)('N')), unchecked((byte)('T')), unchecked((byte)('L')), {
unchecked((byte)('M')), unchecked((byte)('S')), unchecked((byte unchecked((byte)('N')),
)('S')), unchecked((byte)('P')), unchecked(0) }; unchecked((byte)('T')),
unchecked((byte)('L')),
unchecked((byte)('M')),
unchecked((byte)('S')),
unchecked((byte)('S')),
unchecked((byte)('P')),
unchecked(0)
};
private static readonly string OemEncoding = Config.DefaultOemEncoding; private static readonly string OemEncoding = Config.DefaultOemEncoding;
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> /// <summary>Returns the flags currently in use for this message.</summary>
/// <remarks>Returns the flags currently in use for this message.</remarks> /// <remarks>Returns the flags currently in use for this message.</remarks>
/// <returns> /// <returns>
/// An <code>int</code> containing the flags in use for this /// An <code>int</code> containing the flags in use for this
/// message. /// message.
/// </returns> /// </returns>
public virtual int GetFlags() public virtual int GetFlags()
{ {
return _flags; return _flags;
} }
/// <summary>Sets the flags for this message.</summary> /// <summary>Sets the flags for this message.</summary>
/// <remarks>Sets the flags for this message.</remarks> /// <remarks>Sets the flags for this message.</remarks>
/// <param name="flags">The flags for this message.</param> /// <param name="flags">The flags for this message.</param>
public virtual void SetFlags(int flags) public virtual void SetFlags(int flags)
{ {
this._flags = flags; this._flags = flags;
} }
/// <summary>Returns the status of the specified flag.</summary> /// <summary>Returns the status of the specified flag.</summary>
/// <remarks>Returns the status of the specified flag.</remarks> /// <remarks>Returns the status of the specified flag.</remarks>
/// <param name="flag">The flag to test (i.e., <code>NTLMSSP_NEGOTIATE_OEM</code>).</param> /// <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> /// <returns>A <code>boolean</code> indicating whether the flag is set.</returns>
public virtual bool GetFlag(int flag) public virtual bool GetFlag(int flag)
{ {
return (GetFlags() & flag) != 0; return (GetFlags() & flag) != 0;
} }
/// <summary>Sets or clears the specified flag.</summary> /// <summary>Sets or clears the specified flag.</summary>
/// <remarks>Sets or clears the specified flag.</remarks> /// <remarks>Sets or clears the specified flag.</remarks>
/// <param name="flag"> /// <param name="flag">
/// The flag to set/clear (i.e., /// The flag to set/clear (i.e.,
/// <code>NTLMSSP_NEGOTIATE_OEM</code>). /// <code>NTLMSSP_NEGOTIATE_OEM</code>).
/// </param> /// </param>
/// <param name="value"> /// <param name="value">
/// Indicates whether to set (<code>true</code>) or /// Indicates whether to set (<code>true</code>) or
/// clear (<code>false</code>) the specified flag. /// clear (<code>false</code>) the specified flag.
/// </param> /// </param>
public virtual void SetFlag(int flag, bool value) public virtual void SetFlag(int flag, bool value)
{ {
SetFlags(value ? (GetFlags() | flag) : (GetFlags() & (unchecked((int)(0xffffffff) SetFlags(value
) ^ flag))); ? (GetFlags() | flag)
} : (GetFlags() & (unchecked((int)(0xffffffff)) ^ flag)));
}
internal static int ReadULong(byte[] src, int index) internal static int ReadULong(byte[] src, int index)
{ {
return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8) | ((src[index + 2] & unchecked(0xff)) << 16) | ((src[index return (src[index] & unchecked(0xff))
+ 3] & unchecked(0xff)) << 24); | ((src[index + 1] & unchecked(0xff)) << 8)
} | ((src[index + 2] & unchecked(0xff)) << 16)
| ((src[index + 3] & unchecked(0xff)) << 24);
}
internal static int ReadUShort(byte[] src, int index) internal static int ReadUShort(byte[] src, int index)
{ {
return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8); return (src[index] & unchecked(0xff)) | ((src[index + 1] & unchecked(0xff)) << 8);
} }
internal static byte[] ReadSecurityBuffer(byte[] src, int index) internal static byte[] ReadSecurityBuffer(byte[] src, int index)
{ {
int length = ReadUShort(src, index); int length = ReadUShort(src, index);
int offset = ReadULong(src, index + 4); int offset = ReadULong(src, index + 4);
byte[] buffer = new byte[length]; byte[] buffer = new byte[length];
Array.Copy(src, offset, buffer, 0, length); Array.Copy(src, offset, buffer, 0, length);
return buffer; return buffer;
} }
internal static void WriteULong(byte[] dest, int offset, int value) internal static void WriteULong(byte[] dest, int offset, int value)
{ {
dest[offset] = unchecked((byte)(value & unchecked(0xff))); 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 + 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 WriteSecurityBuffer(byte[] dest, int offset, int bodyOffset, internal static void WriteUShort(byte[] dest, int offset, int value)
byte[] src) {
{ dest[offset] = unchecked((byte)(value & unchecked(0xff)));
int length = (src != null) ? src.Length : 0; dest[offset + 1] = unchecked((byte)(value >> 8 & unchecked(0xff)));
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() internal static void WriteSecurityBuffer(byte[] dest,
{ int offset,
return OemEncoding; 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);
}
/// <summary>Returns the raw byte representation of this message.</summary> internal static string GetOemEncoding()
/// <remarks>Returns the raw byte representation of this message.</remarks> {
/// <returns>A <code>byte[]</code> containing the raw message material.</returns> return OemEncoding;
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,228 +22,230 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Ntlmssp namespace SharpCifs.Ntlmssp
{ {
/// <summary>Represents an NTLMSSP Type-1 message.</summary> /// <summary>Represents an NTLMSSP Type-1 message.</summary>
/// <remarks>Represents an NTLMSSP Type-1 message.</remarks> /// <remarks>Represents an NTLMSSP Type-1 message.</remarks>
public class Type1Message : NtlmMessage public class Type1Message : NtlmMessage
{ {
private static readonly int DefaultFlags; 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() static Type1Message()
{ {
DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode" DefaultFlags = NtlmsspNegotiateNtlm | (Config.GetBoolean("jcifs.smb.client.useUnicode", true)
, true) ? NtlmsspNegotiateUnicode : NtlmsspNegotiateOem); ? NtlmsspNegotiateUnicode
DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null); : NtlmsspNegotiateOem);
string defaultWorkstation = null; DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", null);
try string defaultWorkstation = null;
{ try
defaultWorkstation = NbtAddress.GetLocalHost().GetHostName(); {
} defaultWorkstation = NbtAddress.GetLocalHost().GetHostName();
catch (UnknownHostException) }
{ catch (UnknownHostException)
} {
DefaultWorkstation = defaultWorkstation; }
} DefaultWorkstation = defaultWorkstation;
}
/// <summary> /// <summary>
/// Creates a Type-1 message using default values from the current /// Creates a Type-1 message using default values from the current
/// environment. /// environment.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Creates a Type-1 message using default values from the current /// Creates a Type-1 message using default values from the current
/// environment. /// environment.
/// </remarks> /// </remarks>
public Type1Message() : this(GetDefaultFlags(), GetDefaultDomain(), GetDefaultWorkstation public Type1Message() : this(GetDefaultFlags(),
()) GetDefaultDomain(),
{ GetDefaultWorkstation())
} {
}
/// <summary>Creates a Type-1 message with the specified parameters.</summary> /// <summary>Creates a Type-1 message with the specified parameters.</summary>
/// <remarks>Creates a Type-1 message with the specified parameters.</remarks> /// <remarks>Creates a Type-1 message with the specified parameters.</remarks>
/// <param name="flags">The flags to apply to this message.</param> /// <param name="flags">The flags to apply to this message.</param>
/// <param name="suppliedDomain">The supplied authentication domain.</param> /// <param name="suppliedDomain">The supplied authentication domain.</param>
/// <param name="suppliedWorkstation">The supplied workstation name.</param> /// <param name="suppliedWorkstation">The supplied workstation name.</param>
public Type1Message(int flags, string suppliedDomain, string suppliedWorkstation) public Type1Message(int flags, string suppliedDomain, string suppliedWorkstation)
{ {
SetFlags(GetDefaultFlags() | flags); SetFlags(GetDefaultFlags() | flags);
SetSuppliedDomain(suppliedDomain); SetSuppliedDomain(suppliedDomain);
if (suppliedWorkstation == null) if (suppliedWorkstation == null)
{ {
suppliedWorkstation = GetDefaultWorkstation(); suppliedWorkstation = GetDefaultWorkstation();
} }
SetSuppliedWorkstation(suppliedWorkstation); SetSuppliedWorkstation(suppliedWorkstation);
} }
/// <summary>Creates a Type-1 message using the given raw Type-1 material.</summary> /// <summary>Creates a Type-1 message using the given raw Type-1 material.</summary>
/// <remarks>Creates a Type-1 message using the given raw Type-1 material.</remarks> /// <remarks>Creates a Type-1 message using the given raw Type-1 material.</remarks>
/// <param name="material">The raw Type-1 material used to construct this message.</param> /// <param name="material">The raw Type-1 material used to construct this message.</param>
/// <exception cref="System.IO.IOException">If an error occurs while parsing the material. /// <exception cref="System.IO.IOException">
/// </exception> /// If an error occurs while parsing the material.
public Type1Message(byte[] material) /// </exception>
{ public Type1Message(byte[] material)
Parse(material); {
} Parse(material);
}
/// <summary>Returns the supplied authentication domain.</summary> /// <summary>Returns the supplied authentication domain.</summary>
/// <remarks>Returns the supplied authentication domain.</remarks> /// <remarks>Returns the supplied authentication domain.</remarks>
/// <returns>A <code>String</code> containing the supplied domain.</returns> /// <returns>A <code>String</code> containing the supplied domain.</returns>
public virtual string GetSuppliedDomain() public virtual string GetSuppliedDomain()
{ {
return _suppliedDomain; return _suppliedDomain;
} }
/// <summary>Sets the supplied authentication domain for this message.</summary> /// <summary>Sets the supplied authentication domain for this message.</summary>
/// <remarks>Sets the supplied authentication domain for this message.</remarks> /// <remarks>Sets the supplied authentication domain for this message.</remarks>
/// <param name="suppliedDomain">The supplied domain for this message.</param> /// <param name="suppliedDomain">The supplied domain for this message.</param>
public virtual void SetSuppliedDomain(string suppliedDomain) public virtual void SetSuppliedDomain(string suppliedDomain)
{ {
this._suppliedDomain = suppliedDomain; this._suppliedDomain = suppliedDomain;
} }
/// <summary>Returns the supplied workstation name.</summary> /// <summary>Returns the supplied workstation name.</summary>
/// <remarks>Returns the supplied workstation name.</remarks> /// <remarks>Returns the supplied workstation name.</remarks>
/// <returns>A <code>String</code> containing the supplied workstation name.</returns> /// <returns>A <code>String</code> containing the supplied workstation name.</returns>
public virtual string GetSuppliedWorkstation() public virtual string GetSuppliedWorkstation()
{ {
return _suppliedWorkstation; return _suppliedWorkstation;
} }
/// <summary>Sets the supplied workstation name for this message.</summary> /// <summary>Sets the supplied workstation name for this message.</summary>
/// <remarks>Sets the supplied workstation name for this message.</remarks> /// <remarks>Sets the supplied workstation name for this message.</remarks>
/// <param name="suppliedWorkstation">The supplied workstation for this message.</param> /// <param name="suppliedWorkstation">The supplied workstation for this message.</param>
public virtual void SetSuppliedWorkstation(string suppliedWorkstation) public virtual void SetSuppliedWorkstation(string suppliedWorkstation)
{ {
this._suppliedWorkstation = suppliedWorkstation; this._suppliedWorkstation = suppliedWorkstation;
} }
public override byte[] ToByteArray() public override byte[] ToByteArray()
{ {
try try
{ {
string suppliedDomain = GetSuppliedDomain(); string suppliedDomain = GetSuppliedDomain();
string suppliedWorkstation = GetSuppliedWorkstation(); string suppliedWorkstation = GetSuppliedWorkstation();
int flags = GetFlags(); int flags = GetFlags();
bool hostInfo = false; bool hostInfo = false;
byte[] domain = new byte[0]; byte[] domain = new byte[0];
if (!string.IsNullOrEmpty(suppliedDomain)) if (!string.IsNullOrEmpty(suppliedDomain))
{ {
hostInfo = true; hostInfo = true;
flags |= NtlmsspNegotiateOemDomainSupplied; flags |= NtlmsspNegotiateOemDomainSupplied;
domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(), GetOemEncoding domain = Runtime.GetBytesForString(suppliedDomain.ToUpper(),
()); GetOemEncoding());
} }
else else
{ {
flags &= (NtlmsspNegotiateOemDomainSupplied ^ unchecked((int)(0xffffffff))); flags &= (NtlmsspNegotiateOemDomainSupplied ^ unchecked((int)(0xffffffff)));
} }
byte[] workstation = new byte[0]; byte[] workstation = new byte[0];
if (!string.IsNullOrEmpty(suppliedWorkstation)) if (!string.IsNullOrEmpty(suppliedWorkstation))
{ {
hostInfo = true; hostInfo = true;
flags |= NtlmsspNegotiateOemWorkstationSupplied; flags |= NtlmsspNegotiateOemWorkstationSupplied;
workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(), GetOemEncoding workstation = Runtime.GetBytesForString(suppliedWorkstation.ToUpper(),
()); GetOemEncoding());
} }
else else
{ {
flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff flags &= (NtlmsspNegotiateOemWorkstationSupplied ^ unchecked((int)(0xffffffff)));
))); }
} byte[] type1 = new byte[hostInfo
byte[] type1 = new byte[hostInfo ? (32 + domain.Length + workstation.Length) : 16 ? (32 + domain.Length + workstation.Length)
]; : 16];
Array.Copy(NtlmsspSignature, 0, type1, 0, 8); Array.Copy(NtlmsspSignature, 0, type1, 0, 8);
WriteULong(type1, 8, 1); WriteULong(type1, 8, 1);
WriteULong(type1, 12, flags); WriteULong(type1, 12, flags);
if (hostInfo) if (hostInfo)
{ {
WriteSecurityBuffer(type1, 16, 32, domain); WriteSecurityBuffer(type1, 16, 32, domain);
WriteSecurityBuffer(type1, 24, 32 + domain.Length, workstation); WriteSecurityBuffer(type1, 24, 32 + domain.Length, workstation);
} }
return type1; return type1;
} }
catch (IOException ex) catch (IOException ex)
{ {
throw new InvalidOperationException(ex.Message); throw new InvalidOperationException(ex.Message);
} }
} }
public override string ToString() public override string ToString()
{ {
string suppliedDomain = GetSuppliedDomain(); string suppliedDomain = GetSuppliedDomain();
string suppliedWorkstation = GetSuppliedWorkstation(); string suppliedWorkstation = GetSuppliedWorkstation();
return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null" return "Type1Message[suppliedDomain=" + (suppliedDomain ?? "null")
) + ",suppliedWorkstation=" + (suppliedWorkstation ?? "null" + ",suppliedWorkstation=" + (suppliedWorkstation ?? "null")
) + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]"; + ",flags=0x" + Hexdump.ToHexString(GetFlags(), 8) + "]";
} }
/// <summary> /// <summary>
/// Returns the default flags for a generic Type-1 message in the /// Returns the default flags for a generic Type-1 message in the
/// current environment. /// current environment.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Returns the default flags for a generic Type-1 message in the /// Returns the default flags for a generic Type-1 message in the
/// current environment. /// current environment.
/// </remarks> /// </remarks>
/// <returns>An <code>int</code> containing the default flags.</returns> /// <returns>An <code>int</code> containing the default flags.</returns>
public static int GetDefaultFlags() public static int GetDefaultFlags()
{ {
return DefaultFlags; return DefaultFlags;
} }
/// <summary>Returns the default domain from the current environment.</summary> /// <summary>Returns the default domain from the current environment.</summary>
/// <remarks>Returns the default domain from the current environment.</remarks> /// <remarks>Returns the default domain from the current environment.</remarks>
/// <returns>A <code>String</code> containing the default domain.</returns> /// <returns>A <code>String</code> containing the default domain.</returns>
public static string GetDefaultDomain() public static string GetDefaultDomain()
{ {
return DefaultDomain; return DefaultDomain;
} }
/// <summary>Returns the default workstation from the current environment.</summary> /// <summary>Returns the default workstation from the current environment.</summary>
/// <remarks>Returns the default workstation from the current environment.</remarks> /// <remarks>Returns the default workstation from the current environment.</remarks>
/// <returns>A <code>String</code> containing the default workstation.</returns> /// <returns>A <code>String</code> containing the default workstation.</returns>
public static string GetDefaultWorkstation() public static string GetDefaultWorkstation()
{ {
return DefaultWorkstation; return DefaultWorkstation;
} }
/// <exception cref="System.IO.IOException"></exception> /// <exception cref="System.IO.IOException"></exception>
private void Parse(byte[] material) private void Parse(byte[] material)
{ {
for (int i = 0; i < 8; i++) for (int i = 0; i < 8; i++)
{ {
if (material[i] != NtlmsspSignature[i]) if (material[i] != NtlmsspSignature[i])
{ {
throw new IOException("Not an NTLMSSP message."); throw new IOException("Not an NTLMSSP message.");
} }
} }
if (ReadULong(material, 8) != 1) if (ReadULong(material, 8) != 1)
{ {
throw new IOException("Not a Type 1 message."); throw new IOException("Not a Type 1 message.");
} }
int flags = ReadULong(material, 12); int flags = ReadULong(material, 12);
string suppliedDomain = null; string suppliedDomain = null;
if ((flags & NtlmsspNegotiateOemDomainSupplied) != 0) if ((flags & NtlmsspNegotiateOemDomainSupplied) != 0)
{ {
byte[] domain = ReadSecurityBuffer(material, 16); byte[] domain = ReadSecurityBuffer(material, 16);
suppliedDomain = Runtime.GetStringForBytes(domain, GetOemEncoding()); suppliedDomain = Runtime.GetStringForBytes(domain, GetOemEncoding());
} }
string suppliedWorkstation = null; string suppliedWorkstation = null;
if ((flags & NtlmsspNegotiateOemWorkstationSupplied) != 0) if ((flags & NtlmsspNegotiateOemWorkstationSupplied) != 0)
{ {
byte[] workstation = ReadSecurityBuffer(material, 24); byte[] workstation = ReadSecurityBuffer(material, 24);
suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding suppliedWorkstation = Runtime.GetStringForBytes(workstation, GetOemEncoding());
()); }
} SetFlags(flags);
SetFlags(flags); SetSuppliedDomain(suppliedDomain);
SetSuppliedDomain(suppliedDomain); SetSuppliedWorkstation(suppliedWorkstation);
SetSuppliedWorkstation(suppliedWorkstation); }
} }
}
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,50 +18,55 @@ using System.Collections.Generic;
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
public class DfsReferral : SmbException
{
public int PathConsumed;
public long Ttl; public class DfsReferral : SmbException
{
public int PathConsumed;
public string Server; public long Ttl;
public string Share; public string Server;
public string Link; public string Share;
public string Path; public string Link;
public bool ResolveHashes; public string Path;
public long Expiration; public bool ResolveHashes;
internal DfsReferral Next; public long Expiration;
internal IDictionary<string, DfsReferral> Map; internal DfsReferral Next;
internal string Key = null; internal IDictionary<string, DfsReferral> Map;
public DfsReferral() internal string Key = null;
{
// Server
// Share
// Path relative to tree from which this referral was thrown
Next = this;
}
internal virtual void Append(DfsReferral dr) public DfsReferral()
{ {
dr.Next = Next; // Server
Next = dr; // Share
} // Path relative to tree from which this referral was thrown
Next = this;
}
public override string ToString() internal virtual void Append(DfsReferral dr)
{ {
return "DfsReferral[pathConsumed=" + PathConsumed + ",server=" + Server + ",share=" dr.Next = Next;
+ Share + ",link=" + Link + ",path=" + Path + ",ttl=" + Ttl + ",expiration=" + Next = dr;
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,49 +16,94 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
public static class DosError public static class DosError
{ {
public static int[][] DosErrorCodes = { new[] { unchecked(0x00000000), unchecked(0x00000000) }, new[] { unchecked(0x00010001), unchecked((int)(0xc0000002)) }, new[] { unchecked(0x00010002), unchecked( public static int[][] DosErrorCodes =
(int)(0xc0000002)) }, new[] { unchecked(0x00020001), unchecked((int)( {
0xc000000f)) }, new[] { unchecked(0x00020002), unchecked((int)(0xc000006a new[] { unchecked(0x00000000), unchecked(0x00000000) },
)) }, new[] { unchecked(0x00030001), unchecked((int)(0xc000003a)) }, new[] { unchecked(0x00010001), unchecked((int)(0xc0000002)) },
new[] { unchecked(0x00030002), unchecked((int)(0xc00000cb)) }, new[] { unchecked(0x00040002), unchecked((int)(0xc00000ca)) }, new[] { unchecked( new[] { unchecked(0x00010002), unchecked((int)(0xc0000002)) },
0x00050001), unchecked((int)(0xc0000022)) }, new[] { unchecked(0x00050002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x00060001), unchecked((int)(0xc0000008)) }, new[] { unchecked(0x00060002), unchecked( new[] { unchecked(0x00020001), unchecked((int)(0xc000000f)) },
(int)(0xc00000cc)) }, new[] { unchecked(0x00080001), unchecked((int)( new[] { unchecked(0x00020002), unchecked((int)(0xc000006a)) },
0xc000009a)) }, new[] { unchecked(0x00130003), unchecked((int)(0xc00000a2 new[] { unchecked(0x00030001), unchecked((int)(0xc000003a)) },
)) }, new[] { unchecked(0x00150003), unchecked((int)(0xc0000013)) }, new[] { unchecked(0x00030002), unchecked((int)(0xc00000cb)) },
new[] { unchecked(0x001f0001), unchecked((int)(0xc0000001)) }, new[] { unchecked(0x001f0003), unchecked((int)(0xc0000001)) }, new[] { unchecked( new[] { unchecked(0x00040002), unchecked((int)(0xc00000ca)) },
0x00200001), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00200003), unchecked((int)(0xc0000043)) }, new[] { unchecked(0x00210003), unchecked((int)(0xc0000054)) }, new[] { unchecked(0x00270003), unchecked( new[] { unchecked(0x00050001), unchecked((int)(0xc0000022)) },
(int)(0xc000007f)) }, new[] { unchecked(0x00340001), unchecked((int)( new[] { unchecked(0x00050002), unchecked((int)(0xc000000d)) },
0xC00000bd)) }, new[] { unchecked(0x00430001), unchecked((int)(0xc00000cc new[] { unchecked(0x00060001), unchecked((int)(0xc0000008)) },
)) }, new[] { unchecked(0x00470001), unchecked((int)(0xC00000d0)) }, new[] { unchecked(0x00060002), unchecked((int)(0xc00000cc)) },
new[] { unchecked(0x00500001), unchecked((int)(0xc0000035)) }, new[] { unchecked(0x00570001), unchecked((int)(0xc0000003)) }, new[] { unchecked( new[] { unchecked(0x00080001), unchecked((int)(0xc000009a)) },
0x005a0002), unchecked((int)(0xc00000ce)) }, new[] { unchecked(0x005b0002), unchecked((int)(0xc000000d)) }, new[] { unchecked(0x006d0001), unchecked((int)(0xC000014b)) }, new[] { unchecked(0x007b0001), unchecked( new[] { unchecked(0x00130003), unchecked((int)(0xc00000a2)) },
(int)(0xc0000033)) }, new[] { unchecked(0x00910001), unchecked((int)( new[] { unchecked(0x00150003), unchecked((int)(0xc0000013)) },
0xC0000101)) }, new[] { unchecked(0x00b70001), unchecked((int)(0xc0000035 new[] { unchecked(0x001f0001), unchecked((int)(0xc0000001)) },
)) }, new[] { unchecked(0x00e70001), unchecked((int)(0xc00000ab)) }, new[] { unchecked(0x001f0003), unchecked((int)(0xc0000001)) },
new[] { unchecked(0x00e80001), unchecked((int)(0xc00000b1)) }, new[] { unchecked(0x00e90001), unchecked((int)(0xc00000b0)) }, new[] { unchecked( new[] { unchecked(0x00200001), unchecked((int)(0xc0000043)) },
0x00ea0001), unchecked((int)(0xc0000016)) }, new[] { unchecked(0x08bf0002), unchecked((int)(0xC0000193)) }, new[] { unchecked(0x08c00002), unchecked((int)(0xC0000070)) }, new[] { unchecked(0x08c10002), unchecked( new[] { unchecked(0x00200003), unchecked((int)(0xc0000043)) },
(int)(0xC000006f)) }, new[] { unchecked(0x08c20002), unchecked((int)( new[] { unchecked(0x00210003), unchecked((int)(0xc0000054)) },
0xC0000071)) } }; new[] { unchecked(0x00270003), unchecked((int)(0xc000007f)) },
new[] { unchecked(0x00340001), unchecked((int)(0xC00000bd)) },
new[] { unchecked(0x00430001), unchecked((int)(0xc00000cc)) },
new[] { unchecked(0x00470001), unchecked((int)(0xC00000d0)) },
new[] { unchecked(0x00500001), unchecked((int)(0xc0000035)) },
new[] { unchecked(0x00570001), unchecked((int)(0xc0000003)) },
new[] { unchecked(0x005a0002), unchecked((int)(0xc00000ce)) },
new[] { unchecked(0x005b0002), unchecked((int)(0xc000000d)) },
new[] { unchecked(0x006d0001), unchecked((int)(0xC000014b)) },
new[] { unchecked(0x007b0001), unchecked((int)(0xc0000033)) },
new[] { unchecked(0x00910001), unchecked((int)(0xC0000101)) },
new[] { unchecked(0x00b70001), unchecked((int)(0xc0000035)) },
new[] { unchecked(0x00e70001), unchecked((int)(0xc00000ab)) },
new[] { unchecked(0x00e80001), unchecked((int)(0xc00000b1)) },
new[] { unchecked(0x00e90001), unchecked((int)(0xc00000b0)) },
new[] { unchecked(0x00ea0001), unchecked((int)(0xc0000016)) },
new[] { unchecked(0x08bf0002), unchecked((int)(0xC0000193)) },
new[] { unchecked(0x08c00002), unchecked((int)(0xC0000070)) },
new[] { unchecked(0x08c10002), unchecked((int)(0xC000006f)) },
new[] { unchecked(0x08c20002), unchecked((int)(0xC0000071)) }
};
public static string[] DosErrorMessages = { "The operation completed successfully." public static string[] DosErrorMessages =
, "Incorrect function.", "Incorrect function.", "The system cannot find the file specified." {
, "Bad password.", "The system cannot find the path specified.", "reserved", "The client does not have the necessary access rights to perform the requested function." "The operation completed successfully.",
, "Access is denied.", "The TID specified was invalid.", "The handle is invalid." "Incorrect function.",
, "The network name cannot be found.", "Not enough storage is available to process this command." "Incorrect function.",
, "The media is write protected.", "The device is not ready.", "A device attached to the system is not functioning." "The system cannot find the file specified.",
, "A device attached to the system is not functioning.", "The process cannot access the file because it is being used by another process." "Bad password.",
, "The process cannot access the file because it is being used by another process." "The system cannot find the path specified.",
, "The process cannot access the file because another process has locked a portion of the file." "reserved",
, "The disk is full.", "A duplicate name exists on the network.", "The network name cannot be found." "The client does not have the necessary access rights to perform the requested function.",
, "ERRnomoreconn.", "The file exists.", "The parameter is incorrect.", "Too many Uids active on this session." "Access is denied.",
, "The Uid is not known as a valid user identifier on this session.", "The pipe has been ended." "The TID specified was invalid.",
, "The filename, directory name, or volume label syntax is incorrect.", "The directory is not empty." "The handle is invalid.",
, "Cannot create a file when that file already exists.", "All pipe instances are busy." "The network name cannot be found.",
, "The pipe is being closed.", "No process is on the other end of the pipe.", "More data is available." "Not enough storage is available to process this command.",
, "This user account has expired.", "The user is not allowed to log on from this workstation." "The media is write protected.",
, "The user is not allowed to log on at this time.", "The password of this user has expired." "The device is not ready.",
}; "A device attached to the system is not functioning.",
} "A device attached to the system is not functioning.",
"The process cannot access the file because it is being used by another process.",
"The process cannot access the file because it is being used by another process.",
"The process cannot access the file because another process has locked a portion of the file.",
"The disk is full.",
"A duplicate name exists on the network.",
"The network name cannot be found.",
"ERRnomoreconn.",
"The file exists.",
"The parameter is incorrect.",
"Too many Uids active on this session.",
"The Uid is not known as a valid user identifier on this session.",
"The pipe has been ended.",
"The filename, directory name, or volume label syntax is incorrect.",
"The directory is not empty.",
"Cannot create a file when that file already exists.",
"All pipe instances are busy.",
"The pipe is being closed.",
"No process is on the other end of the pipe.",
"More data is available.",
"This user account has expired.",
"The user is not allowed to log on from this workstation.",
"The user is not allowed to log on at this time.",
"The password of this user has expired."
};
}
} }

View File

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

View File

@ -16,18 +16,18 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
public interface IFileEntry public interface IFileEntry
{ {
string GetName(); 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 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
internal interface IInfo internal interface IInfo
{ {
int GetAttributes(); int GetAttributes();
long GetCreateTime(); long GetCreateTime();
long GetLastWriteTime(); long GetLastWriteTime();
long GetSize(); long GetSize();
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -16,78 +16,82 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
/// <summary>This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials. /// <summary>
/// </summary> /// This class can be extended by applications that wish to trap authentication related exceptions and automatically retry the exceptional operation with different credentials.
/// <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. /// </summary>
/// </remarks> /// <remarks>
public abstract class NtlmAuthenticator /// 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>
private static NtlmAuthenticator _auth; public abstract class NtlmAuthenticator
{
private static NtlmAuthenticator _auth;
private string _url; private string _url;
private SmbAuthException _sae; private SmbAuthException _sae;
private void Reset() private void Reset()
{ {
_url = null; _url = null;
_sae = null; _sae = null;
} }
/// <summary>Set the default <tt>NtlmAuthenticator</tt>.</summary> /// <summary>Set the default <tt>NtlmAuthenticator</tt>.</summary>
/// <remarks>Set the default <tt>NtlmAuthenticator</tt>. Once the default authenticator is set it cannot be changed. Calling this metho again will have no effect. /// <remarks>
/// </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.
public static void SetDefault(NtlmAuthenticator a) /// </remarks>
{ public static void SetDefault(NtlmAuthenticator a)
lock (typeof(NtlmAuthenticator)) {
{ lock (typeof(NtlmAuthenticator))
if (_auth != null) {
{ if (_auth != null)
return; {
} return;
_auth = a; }
} _auth = a;
} }
}
protected internal string GetRequestingUrl() protected internal string GetRequestingUrl()
{ {
return _url; return _url;
} }
protected internal SmbAuthException GetRequestingException() protected internal SmbAuthException GetRequestingException()
{ {
return _sae; return _sae;
} }
/// <summary>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials. /// <summary>
/// </summary> /// Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
/// <remarks>Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials. /// </summary>
/// </remarks> /// <remarks>
public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string /// Used internally by jCIFS when an <tt>SmbAuthException</tt> is trapped to retrieve new user credentials.
url, SmbAuthException sae) /// </remarks>
{ public static NtlmPasswordAuthentication RequestNtlmPasswordAuthentication(string url,
if (_auth == null) SmbAuthException sae)
{ {
return null; if (_auth == null)
} {
lock (_auth) return null;
{ }
_auth._url = url; lock (_auth)
_auth._sae = sae; {
return _auth.GetNtlmPasswordAuthentication(); _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>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> /// </summary>
/// <remarks> /// <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. /// An application extending this class must provide an implementation for this method that returns new user credentials try try when accessing SMB resources described by the <tt>getRequestingURL</tt> and <tt>getRequestingException</tt> methods.
/// If this method returns <tt>null</tt> the <tt>SmbAuthException</tt> that triggered the authenticator check will simply be rethrown. The default implementation returns <tt>null</tt>. /// If this method returns <tt>null</tt> the <tt>SmbAuthException</tt> that triggered the authenticator check will simply be rethrown. The default implementation returns <tt>null</tt>.
/// </remarks> /// </remarks>
protected internal virtual NtlmPasswordAuthentication GetNtlmPasswordAuthentication protected internal virtual NtlmPasswordAuthentication GetNtlmPasswordAuthentication()
() {
{ return null;
return null; }
} }
}
} }

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,176 +18,187 @@ using SharpCifs.Util;
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
internal class SmbComNtCreateAndX : AndXServerMessageBlock internal class SmbComNtCreateAndX : AndXServerMessageBlock
{ {
internal const int FileSupersede = unchecked(0x0); 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, internal SmbComNtCreateAndX(string name,
int extFileAttributes, int createOptions, ServerMessageBlock andx) : base(andx) int flags,
{ int access,
// share access specified in SmbFile int shareAccess,
// create disposition int extFileAttributes,
// create options int createOptions,
// security flags ServerMessageBlock andx) : base(andx)
Path = name; {
Command = SmbComNtCreateAndx; // share access specified in SmbFile
DesiredAccess = access; // create disposition
DesiredAccess |= SmbConstants.FileReadData | SmbConstants.FileReadEa | SmbConstants.FileReadAttributes; // create options
// extFileAttributes // security flags
this._extFileAttributes = extFileAttributes; Path = name;
// shareAccess Command = SmbComNtCreateAndx;
this._shareAccess = shareAccess; DesiredAccess = access;
// createDisposition DesiredAccess |= SmbConstants.FileReadData
if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc) | SmbConstants.FileReadEa
{ | SmbConstants.FileReadAttributes;
// truncate the file // extFileAttributes
if ((flags & SmbFile.OCreat) == SmbFile.OCreat) this._extFileAttributes = extFileAttributes;
{ // shareAccess
// create it if necessary this._shareAccess = shareAccess;
_createDisposition = FileOverwriteIf; // createDisposition
} if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc)
else {
{ // truncate the file
_createDisposition = FileOverwrite; if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
} {
} // create it if necessary
else _createDisposition = FileOverwriteIf;
{ }
// don't truncate the file else
if ((flags & SmbFile.OCreat) == SmbFile.OCreat) {
{ _createDisposition = FileOverwrite;
// create it if necessary }
if ((flags & SmbFile.OExcl) == SmbFile.OExcl) }
{ else
// fail if already exists {
_createDisposition = FileCreate; // don't truncate the file
} if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
else {
{ // create it if necessary
_createDisposition = FileOpenIf; if ((flags & SmbFile.OExcl) == SmbFile.OExcl)
} {
} // fail if already exists
else _createDisposition = FileCreate;
{ }
_createDisposition = FileOpen; else
} {
} _createDisposition = FileOpenIf;
if ((createOptions & unchecked(0x0001)) == 0) }
{ }
this._createOptions = createOptions | unchecked(0x0040); else
} {
else _createDisposition = FileOpen;
{ }
this._createOptions = createOptions; }
} if ((createOptions & unchecked(0x0001)) == 0)
_impersonationLevel = unchecked(0x02); {
// As seen on NT :~) this._createOptions = createOptions | unchecked(0x0040);
_securityFlags = unchecked(unchecked(0x03)); }
} else
{
this._createOptions = createOptions;
}
_impersonationLevel = unchecked(0x02);
// As seen on NT :~)
_securityFlags = unchecked(unchecked(0x03));
}
// SECURITY_CONTEXT_TRACKING | SECURITY_EFFECTIVE_ONLY // SECURITY_CONTEXT_TRACKING | SECURITY_EFFECTIVE_ONLY
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{ {
int start = dstIndex; int start = dstIndex;
dst[dstIndex++] = unchecked(unchecked(0x00)); dst[dstIndex++] = unchecked(unchecked(0x00));
// name length without counting null termination // name length without counting null termination
_namelenIndex = dstIndex; _namelenIndex = dstIndex;
dstIndex += 2; dstIndex += 2;
WriteInt4(Flags0, dst, dstIndex); WriteInt4(Flags0, dst, dstIndex);
dstIndex += 4; dstIndex += 4;
WriteInt4(_rootDirectoryFid, dst, dstIndex); WriteInt4(_rootDirectoryFid, dst, dstIndex);
dstIndex += 4; dstIndex += 4;
WriteInt4(DesiredAccess, dst, dstIndex); WriteInt4(DesiredAccess, dst, dstIndex);
dstIndex += 4; dstIndex += 4;
WriteInt8(_allocationSize, dst, dstIndex); WriteInt8(_allocationSize, dst, dstIndex);
dstIndex += 8; dstIndex += 8;
WriteInt4(_extFileAttributes, dst, dstIndex); WriteInt4(_extFileAttributes, dst, dstIndex);
dstIndex += 4; dstIndex += 4;
WriteInt4(_shareAccess, dst, dstIndex); WriteInt4(_shareAccess, dst, dstIndex);
dstIndex += 4; dstIndex += 4;
WriteInt4(_createDisposition, dst, dstIndex); WriteInt4(_createDisposition, dst, dstIndex);
dstIndex += 4; dstIndex += 4;
WriteInt4(_createOptions, dst, dstIndex); WriteInt4(_createOptions, dst, dstIndex);
dstIndex += 4; dstIndex += 4;
WriteInt4(_impersonationLevel, dst, dstIndex); WriteInt4(_impersonationLevel, dst, dstIndex);
dstIndex += 4; dstIndex += 4;
dst[dstIndex++] = _securityFlags; dst[dstIndex++] = _securityFlags;
return dstIndex - start; return dstIndex - start;
} }
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{ {
int n; int n;
n = WriteString(Path, dst, dstIndex); n = WriteString(Path, dst, dstIndex);
WriteInt2((UseUnicode ? Path.Length * 2 : n), dst, _namelenIndex); WriteInt2((UseUnicode ? Path.Length * 2 : n), dst, _namelenIndex);
return n; return n;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
) {
{ return 0;
return 0; }
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{ {
return 0; return 0;
} }
public override string ToString() public override string ToString()
{ {
return "SmbComNTCreateAndX[" + base.ToString() + ",flags=0x" + Hexdump return "SmbComNTCreateAndX["
.ToHexString(Flags0, 2) + ",rootDirectoryFid=" + _rootDirectoryFid + ",desiredAccess=0x" + base.ToString()
+ Hexdump.ToHexString(DesiredAccess, 4) + ",allocationSize=" + _allocationSize + + ",flags=0x" + Hexdump.ToHexString(Flags0, 2)
",extFileAttributes=0x" + Hexdump.ToHexString(_extFileAttributes, 4) + ",shareAccess=0x" + ",rootDirectoryFid=" + _rootDirectoryFid
+ Hexdump.ToHexString(_shareAccess, 4) + ",createDisposition=0x" + Hexdump.ToHexString + ",desiredAccess=0x" + Hexdump.ToHexString(DesiredAccess, 4)
(_createDisposition, 4) + ",createOptions=0x" + Hexdump.ToHexString(_createOptions + ",allocationSize=" + _allocationSize
, 8) + ",impersonationLevel=0x" + Hexdump.ToHexString(_impersonationLevel, 4) + ",securityFlags=0x" + ",extFileAttributes=0x" + Hexdump.ToHexString(_extFileAttributes, 4)
+ Hexdump.ToHexString(_securityFlags, 2) + ",name=" + Path + "]"; + ",shareAccess=0x" + Hexdump.ToHexString(_shareAccess, 4)
} + ",createDisposition=0x" + Hexdump.ToHexString(_createDisposition, 4)
} + ",createOptions=0x" + Hexdump.ToHexString(_createOptions, 8)
+ ",impersonationLevel=0x" + Hexdump.ToHexString(_impersonationLevel, 4)
+ ",securityFlags=0x" + Hexdump.ToHexString(_securityFlags, 2)
+ ",name=" + Path + "]";
}
}
} }

View File

@ -19,98 +19,104 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
internal class SmbComNtCreateAndXResponse : AndXServerMessageBlock internal class SmbComNtCreateAndXResponse : AndXServerMessageBlock
{ {
internal const int ExclusiveOplockGranted = 1; 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) internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{ {
return 0; return 0;
} }
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{ {
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
) {
{ int start = bufferIndex;
int start = bufferIndex; OplockLevel = buffer[bufferIndex++];
OplockLevel = buffer[bufferIndex++]; Fid = ReadInt2(buffer, bufferIndex);
Fid = ReadInt2(buffer, bufferIndex); bufferIndex += 2;
bufferIndex += 2; CreateAction = ReadInt4(buffer, bufferIndex);
CreateAction = ReadInt4(buffer, bufferIndex); bufferIndex += 4;
bufferIndex += 4; CreationTime = ReadTime(buffer, bufferIndex);
CreationTime = ReadTime(buffer, bufferIndex); bufferIndex += 8;
bufferIndex += 8; LastAccessTime = ReadTime(buffer, bufferIndex);
LastAccessTime = ReadTime(buffer, bufferIndex); bufferIndex += 8;
bufferIndex += 8; LastWriteTime = ReadTime(buffer, bufferIndex);
LastWriteTime = ReadTime(buffer, bufferIndex); bufferIndex += 8;
bufferIndex += 8; ChangeTime = ReadTime(buffer, bufferIndex);
ChangeTime = ReadTime(buffer, bufferIndex); bufferIndex += 8;
bufferIndex += 8; ExtFileAttributes = ReadInt4(buffer, bufferIndex);
ExtFileAttributes = ReadInt4(buffer, bufferIndex); bufferIndex += 4;
bufferIndex += 4; AllocationSize = ReadInt8(buffer, bufferIndex);
AllocationSize = ReadInt8(buffer, bufferIndex); bufferIndex += 8;
bufferIndex += 8; EndOfFile = ReadInt8(buffer, bufferIndex);
EndOfFile = ReadInt8(buffer, bufferIndex); bufferIndex += 8;
bufferIndex += 8; FileType = ReadInt2(buffer, bufferIndex);
FileType = ReadInt2(buffer, bufferIndex); bufferIndex += 2;
bufferIndex += 2; DeviceState = ReadInt2(buffer, bufferIndex);
DeviceState = ReadInt2(buffer, bufferIndex); bufferIndex += 2;
bufferIndex += 2; Directory = (buffer[bufferIndex++] & unchecked(0xFF)) > 0;
Directory = (buffer[bufferIndex++] & unchecked(0xFF)) > 0; return bufferIndex - start;
return bufferIndex - start; }
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{ {
return 0; return 0;
} }
public override string ToString() public override string ToString()
{ {
return "SmbComNTCreateAndXResponse[" + base.ToString() + ",oplockLevel=" return "SmbComNTCreateAndXResponse["
+ OplockLevel + ",fid=" + Fid + ",createAction=0x" + Hexdump.ToHexString(CreateAction + base.ToString()
, 4) + ",creationTime=" + Extensions.CreateDate(CreationTime) + ",lastAccessTime=" + ",oplockLevel=" + OplockLevel
+ Extensions.CreateDate(LastAccessTime) + ",lastWriteTime=" + Extensions.CreateDate + ",fid=" + Fid
(LastWriteTime) + ",changeTime=" + Extensions.CreateDate(ChangeTime) + ",extFileAttributes=0x" + ",createAction=0x" + Hexdump.ToHexString(CreateAction, 4)
+ Hexdump.ToHexString(ExtFileAttributes, 4) + ",allocationSize=" + AllocationSize + ",creationTime=" + Extensions.CreateDate(CreationTime)
+ ",endOfFile=" + EndOfFile + ",fileType=" + FileType + ",deviceState=" + DeviceState + ",lastAccessTime=" + Extensions.CreateDate(LastAccessTime)
+ ",directory=" + Directory + "]"; + ",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,52 +19,53 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
internal class SmbComNegotiate : ServerMessageBlock internal class SmbComNegotiate : ServerMessageBlock
{ {
private const string Dialects = "\u0002NT LM 0.12\u0000"; private const string Dialects = "\u0002NT LM 0.12\u0000";
public SmbComNegotiate() public SmbComNegotiate()
{ {
Command = SmbComNegotiate; Command = SmbComNegotiate;
Flags2 = SmbConstants.DefaultFlags2; Flags2 = SmbConstants.DefaultFlags2;
} }
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{ {
return 0; return 0;
} }
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{ {
byte[] dialects; byte[] dialects;
try try
{ {
//dialects = Runtime.GetBytesForString(Dialects, "ASCII"); //dialects = Runtime.GetBytesForString(Dialects, "ASCII");
dialects = Runtime.GetBytesForString(Dialects, "UTF-8"); dialects = Runtime.GetBytesForString(Dialects, "UTF-8");
} }
catch (UnsupportedEncodingException) catch (UnsupportedEncodingException)
{ {
return 0; return 0;
} }
Array.Copy(dialects, 0, dst, dstIndex, dialects.Length); Array.Copy(dialects, 0, dst, dstIndex, dialects.Length);
return dialects.Length; return dialects.Length;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
) {
{ return 0;
return 0; }
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{ {
return 0; return 0;
} }
public override string ToString() public override string ToString()
{ {
return "SmbComNegotiate[" + base.ToString() + ",wordCount=" + WordCount return "SmbComNegotiate["
+ ",dialects=NT LM 0.12]"; + base.ToString()
} + ",wordCount=" + WordCount
} + ",dialects=NT LM 0.12]";
}
}
} }

View File

@ -20,145 +20,160 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
internal class SmbComNegotiateResponse : ServerMessageBlock internal class SmbComNegotiateResponse : ServerMessageBlock
{ {
internal int DialectIndex; internal int DialectIndex;
internal SmbTransport.ServerData Server; internal SmbTransport.ServerData Server;
internal SmbComNegotiateResponse(SmbTransport.ServerData server) internal SmbComNegotiateResponse(SmbTransport.ServerData server)
{ {
this.Server = server; this.Server = server;
} }
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{ {
return 0; return 0;
} }
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{ {
return 0; return 0;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
) {
{ int start = bufferIndex;
int start = bufferIndex; DialectIndex = ReadInt2(buffer, bufferIndex);
DialectIndex = ReadInt2(buffer, bufferIndex); bufferIndex += 2;
bufferIndex += 2; if (DialectIndex > 10)
if (DialectIndex > 10) {
{ return bufferIndex - start;
return bufferIndex - start; }
} Server.SecurityMode = buffer[bufferIndex++] & unchecked(0xFF);
Server.SecurityMode = buffer[bufferIndex++] & unchecked(0xFF); Server.Security = Server.SecurityMode & unchecked(0x01);
Server.Security = Server.SecurityMode & unchecked(0x01); Server.EncryptedPasswords
Server.EncryptedPasswords = (Server.SecurityMode & unchecked(0x02)) == unchecked( = (Server.SecurityMode & unchecked(0x02)) == unchecked(0x02);
0x02); Server.SignaturesEnabled
Server.SignaturesEnabled = (Server.SecurityMode & unchecked(0x04)) == unchecked( = (Server.SecurityMode & unchecked(0x04)) == unchecked(0x04);
0x04); Server.SignaturesRequired
Server.SignaturesRequired = (Server.SecurityMode & unchecked(0x08)) == unchecked( = (Server.SecurityMode & unchecked(0x08)) == unchecked(0x08);
0x08); Server.MaxMpxCount = ReadInt2(buffer, bufferIndex);
Server.MaxMpxCount = ReadInt2(buffer, bufferIndex); bufferIndex += 2;
bufferIndex += 2; Server.MaxNumberVcs = ReadInt2(buffer, bufferIndex);
Server.MaxNumberVcs = ReadInt2(buffer, bufferIndex); bufferIndex += 2;
bufferIndex += 2; Server.MaxBufferSize = ReadInt4(buffer, bufferIndex);
Server.MaxBufferSize = ReadInt4(buffer, bufferIndex); bufferIndex += 4;
bufferIndex += 4; Server.MaxRawSize = ReadInt4(buffer, bufferIndex);
Server.MaxRawSize = ReadInt4(buffer, bufferIndex); bufferIndex += 4;
bufferIndex += 4; Server.SessionKey = ReadInt4(buffer, bufferIndex);
Server.SessionKey = ReadInt4(buffer, bufferIndex); bufferIndex += 4;
bufferIndex += 4; Server.Capabilities = ReadInt4(buffer, bufferIndex);
Server.Capabilities = ReadInt4(buffer, bufferIndex); bufferIndex += 4;
bufferIndex += 4; Server.ServerTime = ReadTime(buffer, bufferIndex);
Server.ServerTime = ReadTime(buffer, bufferIndex); bufferIndex += 8;
bufferIndex += 8; Server.ServerTimeZone = ReadInt2(buffer, bufferIndex);
Server.ServerTimeZone = ReadInt2(buffer, bufferIndex); bufferIndex += 2;
bufferIndex += 2; Server.EncryptionKeyLength = buffer[bufferIndex++] & unchecked(0xFF);
Server.EncryptionKeyLength = buffer[bufferIndex++] & unchecked(0xFF); return bufferIndex - start;
return bufferIndex - start; }
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{ {
int start = bufferIndex; int start = bufferIndex;
if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == 0) if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == 0)
{ {
Server.EncryptionKey = new byte[Server.EncryptionKeyLength]; Server.EncryptionKey = new byte[Server.EncryptionKeyLength];
Array.Copy(buffer, bufferIndex, Server.EncryptionKey, 0, Server.EncryptionKeyLength Array.Copy(buffer,
); bufferIndex,
bufferIndex += Server.EncryptionKeyLength; Server.EncryptionKey,
if (ByteCount > Server.EncryptionKeyLength) 0,
{ Server.EncryptionKeyLength);
int len = 0; bufferIndex += Server.EncryptionKeyLength;
// TODO: we can use new string routine here if (ByteCount > Server.EncryptionKeyLength)
try {
{ int len = 0;
// TODO: we can use new string routine here
try
{
if ((Flags2 & SmbConstants.Flags2Unicode) == SmbConstants.Flags2Unicode) if ((Flags2 & SmbConstants.Flags2Unicode) == SmbConstants.Flags2Unicode)
{ {
while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)) || buffer while (buffer[bufferIndex + len] != unchecked(unchecked(0x00))
[bufferIndex + len + 1] != unchecked(unchecked(0x00))) || buffer[bufferIndex + len + 1] != unchecked(unchecked(0x00)))
{ {
len += 2; len += 2;
if (len > 256) if (len > 256)
{ {
throw new RuntimeException("zero termination not found"); throw new RuntimeException("zero termination not found");
} }
} }
Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len Server.OemDomainName = Runtime.GetStringForBytes(buffer,
, SmbConstants.UniEncoding); bufferIndex,
} len,
else SmbConstants.UniEncoding);
{ }
while (buffer[bufferIndex + len] != unchecked(unchecked(0x00))) else
{ {
len++; while (buffer[bufferIndex + len] != unchecked(unchecked(0x00)))
if (len > 256) {
{ len++;
throw new RuntimeException("zero termination not found"); if (len > 256)
} {
} throw new RuntimeException("zero termination not found");
Server.OemDomainName = Runtime.GetStringForBytes(buffer, bufferIndex, len }
, SmbConstants.OemEncoding); }
} Server.OemDomainName = Runtime.GetStringForBytes(buffer,
} bufferIndex,
catch (UnsupportedEncodingException uee) len,
{ SmbConstants.OemEncoding);
if (Log.Level > 1) }
{ }
Runtime.PrintStackTrace(uee, Log); catch (UnsupportedEncodingException uee)
} {
} if (Log.Level > 1)
bufferIndex += len; {
} Runtime.PrintStackTrace(uee, Log);
else }
{ }
Server.OemDomainName = ""; bufferIndex += len;
} }
} else
else {
{ Server.OemDomainName = "";
Server.Guid = new byte[16]; }
Array.Copy(buffer, bufferIndex, Server.Guid, 0, 16); }
Server.OemDomainName = ""; else
} {
// ignore SPNEGO token for now ... Server.Guid = new byte[16];
return bufferIndex - start; Array.Copy(buffer, bufferIndex, Server.Guid, 0, 16);
} Server.OemDomainName = "";
}
// ignore SPNEGO token for now ...
return bufferIndex - start;
}
public override string ToString() public override string ToString()
{ {
return "SmbComNegotiateResponse[" + base.ToString() + ",wordCount=" + return "SmbComNegotiateResponse["
WordCount + ",dialectIndex=" + DialectIndex + ",securityMode=0x" + Hexdump.ToHexString + base.ToString()
(Server.SecurityMode, 1) + ",security=" + (Server.Security == SmbConstants.SecurityShare ? "share" + ",wordCount=" + WordCount
: "user") + ",encryptedPasswords=" + Server.EncryptedPasswords + ",maxMpxCount=" + ",dialectIndex=" + DialectIndex
+ Server.MaxMpxCount + ",maxNumberVcs=" + Server.MaxNumberVcs + ",maxBufferSize=" + ",securityMode=0x" + Hexdump.ToHexString(Server.SecurityMode, 1)
+ Server.MaxBufferSize + ",maxRawSize=" + Server.MaxRawSize + ",sessionKey=0x" + ",security=" + (Server.Security == SmbConstants.SecurityShare
+ Hexdump.ToHexString(Server.SessionKey, 8) + ",capabilities=0x" + Hexdump.ToHexString ? "share"
(Server.Capabilities, 8) + ",serverTime=" + Extensions.CreateDate(Server : "user")
.ServerTime) + ",serverTimeZone=" + Server.ServerTimeZone + ",encryptionKeyLength=" + ",encryptedPasswords=" + Server.EncryptedPasswords
+ Server.EncryptionKeyLength + ",byteCount=" + ByteCount + ",oemDomainName=" + + ",maxMpxCount=" + Server.MaxMpxCount
Server.OemDomainName + "]"; + ",maxNumberVcs=" + Server.MaxNumberVcs
} + ",maxBufferSize=" + Server.MaxBufferSize
} + ",maxRawSize=" + Server.MaxRawSize
+ ",sessionKey=0x" + Hexdump.ToHexString(Server.SessionKey, 8)
+ ",capabilities=0x" + Hexdump.ToHexString(Server.Capabilities, 8)
+ ",serverTime=" + Extensions.CreateDate(Server.ServerTime)
+ ",serverTimeZone=" + Server.ServerTimeZone
+ ",encryptionKeyLength=" + Server.EncryptionKeyLength
+ ",byteCount=" + ByteCount
+ ",oemDomainName=" + Server.OemDomainName + "]";
}
}
} }

View File

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

View File

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

View File

@ -19,172 +19,179 @@ using SharpCifs.Util.Sharpen;
namespace SharpCifs.Smb namespace SharpCifs.Smb
{ {
internal class SmbComOpenAndX : AndXServerMessageBlock internal class SmbComOpenAndX : AndXServerMessageBlock
{ {
private const int FlagsReturnAdditionalInfo = 0x01; 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" private static readonly int BatchLimit
, 1); = 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 internal SmbComOpenAndX(string fileName,
andx) : base(andx) int access,
{ int flags,
// flags (not the same as flags constructor argument) ServerMessageBlock andx) : base(andx)
// Access Mode Encoding for desiredAccess {
// bit 12 // flags (not the same as flags constructor argument)
// bit 14 // Access Mode Encoding for desiredAccess
// flags is NOT the same as flags member // bit 12
Path = fileName; // bit 14
Command = SmbComOpenAndx; // flags is NOT the same as flags member
DesiredAccess = access & 0x3; Path = fileName;
if (DesiredAccess == 0x3) Command = SmbComOpenAndx;
{ DesiredAccess = access & 0x3;
DesiredAccess = 0x2; if (DesiredAccess == 0x3)
} {
DesiredAccess |= SharingDenyNone; DesiredAccess = 0x2;
DesiredAccess &= ~0x1; }
// Win98 doesn't like GENERIC_READ ?! -- get Access Denied. DesiredAccess |= SharingDenyNone;
// searchAttributes DesiredAccess &= ~0x1;
SearchAttributes = SmbConstants.AttrDirectory | SmbConstants.AttrHidden | SmbConstants.AttrSystem; // Win98 doesn't like GENERIC_READ ?! -- get Access Denied.
// fileAttributes // searchAttributes
FileAttributes = 0; SearchAttributes = SmbConstants.AttrDirectory
// openFunction | SmbConstants.AttrHidden
if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc) | SmbConstants.AttrSystem;
{ // fileAttributes
// truncate the file FileAttributes = 0;
if ((flags & SmbFile.OCreat) == SmbFile.OCreat) // openFunction
{ if ((flags & SmbFile.OTrunc) == SmbFile.OTrunc)
// create it if necessary {
OpenFunction = OpenFnTrunc | OpenFnCreate; // truncate the file
} if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
else {
{ // create it if necessary
OpenFunction = OpenFnTrunc; OpenFunction = OpenFnTrunc | OpenFnCreate;
} }
} else
else {
{ OpenFunction = OpenFnTrunc;
// don't truncate the file }
if ((flags & SmbFile.OCreat) == SmbFile.OCreat) }
{ else
// create it if necessary {
if ((flags & SmbFile.OExcl) == SmbFile.OExcl) // don't truncate the file
{ if ((flags & SmbFile.OCreat) == SmbFile.OCreat)
// fail if already exists {
OpenFunction = OpenFnCreate | OpenFnFailIfExists; // create it if necessary
} if ((flags & SmbFile.OExcl) == SmbFile.OExcl)
else {
{ // fail if already exists
OpenFunction = OpenFnCreate | OpenFnOpen; OpenFunction = OpenFnCreate | OpenFnFailIfExists;
} }
} else
else {
{ OpenFunction = OpenFnCreate | OpenFnOpen;
OpenFunction = OpenFnOpen; }
} }
} else
} {
OpenFunction = OpenFnOpen;
}
}
}
internal override int GetBatchLimit(byte command) internal override int GetBatchLimit(byte command)
{ {
return command == SmbComReadAndx ? BatchLimit : 0; return command == SmbComReadAndx ? BatchLimit : 0;
} }
internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex) internal override int WriteParameterWordsWireFormat(byte[] dst, int dstIndex)
{ {
int start = dstIndex; int start = dstIndex;
WriteInt2(flags, dst, dstIndex); WriteInt2(flags, dst, dstIndex);
dstIndex += 2; dstIndex += 2;
WriteInt2(DesiredAccess, dst, dstIndex); WriteInt2(DesiredAccess, dst, dstIndex);
dstIndex += 2; dstIndex += 2;
WriteInt2(SearchAttributes, dst, dstIndex); WriteInt2(SearchAttributes, dst, dstIndex);
dstIndex += 2; dstIndex += 2;
WriteInt2(FileAttributes, dst, dstIndex); WriteInt2(FileAttributes, dst, dstIndex);
dstIndex += 2; dstIndex += 2;
CreationTime = 0; CreationTime = 0;
WriteInt4(CreationTime, dst, dstIndex); WriteInt4(CreationTime, dst, dstIndex);
dstIndex += 4; dstIndex += 4;
WriteInt2(OpenFunction, dst, dstIndex); WriteInt2(OpenFunction, dst, dstIndex);
dstIndex += 2; dstIndex += 2;
WriteInt4(AllocationSize, dst, dstIndex); WriteInt4(AllocationSize, dst, dstIndex);
dstIndex += 4; dstIndex += 4;
for (int i = 0; i < 8; i++) for (int i = 0; i < 8; i++)
{ {
dst[dstIndex++] = 0x00; dst[dstIndex++] = 0x00;
} }
return dstIndex - start; return dstIndex - start;
} }
internal override int WriteBytesWireFormat(byte[] dst, int dstIndex) internal override int WriteBytesWireFormat(byte[] dst, int dstIndex)
{ {
int start = dstIndex; int start = dstIndex;
if (UseUnicode) if (UseUnicode)
{ {
dst[dstIndex++] = (byte)('\0'); dst[dstIndex++] = (byte)('\0');
} }
dstIndex += WriteString(Path, dst, dstIndex); dstIndex += WriteString(Path, dst, dstIndex);
return dstIndex - start; return dstIndex - start;
} }
internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex internal override int ReadParameterWordsWireFormat(byte[] buffer, int bufferIndex)
) {
{ return 0;
return 0; }
}
internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex) internal override int ReadBytesWireFormat(byte[] buffer, int bufferIndex)
{ {
return 0; return 0;
} }
public override string ToString() public override string ToString()
{ {
return "SmbComOpenAndX[" + base.ToString() + ",flags=0x" + Hexdump.ToHexString return "SmbComOpenAndX["
(flags, 2) + ",desiredAccess=0x" + Hexdump.ToHexString(DesiredAccess, 4) + ",searchAttributes=0x" + base.ToString()
+ Hexdump.ToHexString(SearchAttributes, 4) + ",fileAttributes=0x" + Hexdump.ToHexString + ",flags=0x" + Hexdump.ToHexString(flags, 2)
(FileAttributes, 4) + ",creationTime=" + Extensions.CreateDate(CreationTime + ",desiredAccess=0x" + Hexdump.ToHexString(DesiredAccess, 4)
) + ",openFunction=0x" + Hexdump.ToHexString(OpenFunction, 2) + ",allocationSize=" + ",searchAttributes=0x" + Hexdump.ToHexString(SearchAttributes, 4)
+ AllocationSize + ",fileName=" + Path + "]"; + ",fileAttributes=0x" + Hexdump.ToHexString(FileAttributes, 4)
} + ",creationTime=" + Extensions.CreateDate(CreationTime)
} + ",openFunction=0x" + Hexdump.ToHexString(OpenFunction, 2)
+ ",allocationSize=" + AllocationSize
+ ",fileName=" + Path + "]";
}
}
} }

View File

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

View File

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

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