SmbTransport.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. // This code is derived from jcifs smb client library <jcifs at samba dot org>
  2. // Ported by J. Arturo <webmaster at komodosoft dot net>
  3. //
  4. // This library is free software; you can redistribute it and/or
  5. // modify it under the terms of the GNU Lesser General Public
  6. // License as published by the Free Software Foundation; either
  7. // version 2.1 of the License, or (at your option) any later version.
  8. //
  9. // This library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. // Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public
  15. // License along with this library; if not, write to the Free Software
  16. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. using System;
  18. using System.Collections.Generic;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Net;
  22. using System.Net.Sockets;
  23. using SharpCifs.Netbios;
  24. using SharpCifs.Util;
  25. using SharpCifs.Util.Sharpen;
  26. using SharpCifs.Util.Transport;
  27. namespace SharpCifs.Smb
  28. {
  29. public class SmbTransport : Transport
  30. {
  31. internal static readonly byte[] Buf = new byte[0xFFFF];
  32. internal static readonly SmbComNegotiate NegotiateRequest = new SmbComNegotiate(
  33. );
  34. internal static LogStream LogStatic = LogStream.GetInstance();
  35. internal static Hashtable DfsRoots = null;
  36. internal static SmbTransport GetSmbTransport(UniAddress address, int port
  37. )
  38. {
  39. lock (typeof(SmbTransport))
  40. {
  41. return GetSmbTransport(address, port, SmbConstants.Laddr, SmbConstants.Lport, null);
  42. }
  43. }
  44. internal static SmbTransport GetSmbTransport(UniAddress address, int port
  45. , IPAddress localAddr, int localPort, string hostName)
  46. {
  47. lock (typeof(SmbTransport))
  48. {
  49. SmbTransport conn;
  50. lock (SmbConstants.Connections)
  51. {
  52. if (SmbConstants.SsnLimit != 1)
  53. {
  54. conn =
  55. SmbConstants.Connections.FirstOrDefault(
  56. c =>
  57. c.Matches(address, port, localAddr, localPort, hostName) &&
  58. (SmbConstants.SsnLimit ==
  59. 0 || c.Sessions.Count < SmbConstants.SsnLimit));
  60. if (conn != null)
  61. {
  62. return conn;
  63. }
  64. }
  65. conn = new SmbTransport(address, port, localAddr, localPort);
  66. SmbConstants.Connections.Insert(0, conn);
  67. }
  68. return conn;
  69. }
  70. }
  71. internal class ServerData
  72. {
  73. internal byte Flags;
  74. internal int Flags2;
  75. internal int MaxMpxCount;
  76. internal int MaxBufferSize;
  77. internal int SessionKey;
  78. internal int Capabilities;
  79. internal string OemDomainName;
  80. internal int SecurityMode;
  81. internal int Security;
  82. internal bool EncryptedPasswords;
  83. internal bool SignaturesEnabled;
  84. internal bool SignaturesRequired;
  85. internal int MaxNumberVcs;
  86. internal int MaxRawSize;
  87. internal long ServerTime;
  88. internal int ServerTimeZone;
  89. internal int EncryptionKeyLength;
  90. internal byte[] EncryptionKey;
  91. internal byte[] Guid;
  92. internal ServerData(SmbTransport enclosing)
  93. {
  94. this._enclosing = enclosing;
  95. }
  96. private readonly SmbTransport _enclosing;
  97. }
  98. internal IPAddress LocalAddr;
  99. internal int LocalPort;
  100. internal UniAddress Address;
  101. internal SocketEx Socket;
  102. internal int Port;
  103. internal int Mid;
  104. internal OutputStream Out;
  105. internal InputStream In;
  106. internal byte[] Sbuf = new byte[512];
  107. internal SmbComBlankResponse Key = new SmbComBlankResponse();
  108. internal long SessionExpiration = Runtime.CurrentTimeMillis() + SmbConstants.SoTimeout;
  109. internal List<object> Referrals = new List<object>();
  110. internal SigningDigest Digest;
  111. internal List<SmbSession> Sessions = new List<SmbSession>();
  112. internal ServerData Server;
  113. internal int Flags2 = SmbConstants.Flags2;
  114. internal int MaxMpxCount = SmbConstants.MaxMpxCount;
  115. internal int SndBufSize = SmbConstants.SndBufSize;
  116. internal int RcvBufSize = SmbConstants.RcvBufSize;
  117. internal int Capabilities = SmbConstants.Capabilities;
  118. internal int SessionKey = 0x00000000;
  119. internal bool UseUnicode = SmbConstants.UseUnicode;
  120. internal string TconHostName;
  121. internal SmbTransport(UniAddress address, int port, IPAddress localAddr, int localPort
  122. )
  123. {
  124. Server = new ServerData(this);
  125. this.Address = address;
  126. this.Port = port;
  127. this.LocalAddr = localAddr;
  128. this.LocalPort = localPort;
  129. }
  130. internal virtual SmbSession GetSmbSession()
  131. {
  132. lock (this)
  133. {
  134. return GetSmbSession(new NtlmPasswordAuthentication(null, null, null));
  135. }
  136. }
  137. internal virtual SmbSession GetSmbSession(NtlmPasswordAuthentication auth)
  138. {
  139. lock (this)
  140. {
  141. SmbSession ssn;
  142. long now;
  143. ssn = Sessions.FirstOrDefault(s => s.Matches(auth));
  144. if (ssn != null)
  145. {
  146. ssn.Auth = auth;
  147. return ssn;
  148. }
  149. if (SmbConstants.SoTimeout > 0 && SessionExpiration < (now = Runtime.CurrentTimeMillis()))
  150. {
  151. SessionExpiration = now + SmbConstants.SoTimeout;
  152. foreach (var session in Sessions.Where(s => s.Expiration < now))
  153. {
  154. session.Logoff(false);
  155. }
  156. }
  157. ssn = new SmbSession(Address, Port, LocalAddr, LocalPort, auth);
  158. ssn.transport = this;
  159. Sessions.Add(ssn);
  160. return ssn;
  161. }
  162. }
  163. internal virtual bool Matches(UniAddress address, int port, IPAddress localAddr,
  164. int localPort, string hostName)
  165. {
  166. if (hostName == null)
  167. {
  168. hostName = address.GetHostName();
  169. }
  170. return (TconHostName == null || Runtime.EqualsIgnoreCase(hostName, TconHostName)) && address.Equals(this.Address) && (port == -1 || port == this.Port
  171. || (port == 445 && this.Port == 139)) && (localAddr == this.LocalAddr || (localAddr
  172. != null && localAddr.Equals(this.LocalAddr))) && localPort == this.LocalPort;
  173. }
  174. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  175. internal virtual bool HasCapability(int cap)
  176. {
  177. try
  178. {
  179. Connect(SmbConstants.ResponseTimeout);
  180. }
  181. catch (IOException ioe)
  182. {
  183. throw new SmbException(ioe.Message, ioe);
  184. }
  185. return (Capabilities & cap) == cap;
  186. }
  187. internal virtual bool IsSignatureSetupRequired(NtlmPasswordAuthentication auth)
  188. {
  189. return (Flags2 & SmbConstants.Flags2SecuritySignatures) != 0 && Digest ==
  190. null && auth != NtlmPasswordAuthentication.Null && NtlmPasswordAuthentication.Null
  191. .Equals(auth) == false;
  192. }
  193. /// <exception cref="System.IO.IOException"></exception>
  194. internal virtual void Ssn139()
  195. {
  196. Name calledName = new Name(Address.FirstCalledName(), 0x20, null
  197. );
  198. do
  199. {
  200. Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  201. if (LocalAddr != null)
  202. {
  203. Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort));
  204. }
  205. Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()), 139), SmbConstants.ConnTimeout);
  206. Socket.SoTimeOut = SmbConstants.SoTimeout;
  207. Out = Socket.GetOutputStream();
  208. In = Socket.GetInputStream();
  209. SessionServicePacket ssp = new SessionRequestPacket(calledName, NbtAddress.GetLocalName
  210. ());
  211. Out.Write(Sbuf, 0, ssp.WriteWireFormat(Sbuf, 0));
  212. if (Readn(In, Sbuf, 0, 4) < 4)
  213. {
  214. try
  215. {
  216. //Socket.`Close` method deleted
  217. //Socket.Close();
  218. Socket.Dispose();
  219. }
  220. catch (IOException)
  221. {
  222. }
  223. throw new SmbException("EOF during NetBIOS session request");
  224. }
  225. switch (Sbuf[0] & 0xFF)
  226. {
  227. case SessionServicePacket.PositiveSessionResponse:
  228. {
  229. if (Log.Level >= 4)
  230. {
  231. Log.WriteLine("session established ok with " + Address);
  232. }
  233. return;
  234. }
  235. case SessionServicePacket.NegativeSessionResponse:
  236. {
  237. int errorCode = In.Read() & 0xFF;
  238. switch (errorCode)
  239. {
  240. case NbtException.CalledNotPresent:
  241. case NbtException.NotListeningCalled:
  242. {
  243. //Socket.`Close` method deleted
  244. //Socket.Close();
  245. Socket.Dispose();
  246. break;
  247. }
  248. default:
  249. {
  250. Disconnect(true);
  251. throw new NbtException(NbtException.ErrSsnSrvc, errorCode);
  252. }
  253. }
  254. break;
  255. }
  256. case -1:
  257. {
  258. Disconnect(true);
  259. throw new NbtException(NbtException.ErrSsnSrvc, NbtException.ConnectionRefused
  260. );
  261. }
  262. default:
  263. {
  264. Disconnect(true);
  265. throw new NbtException(NbtException.ErrSsnSrvc, 0);
  266. }
  267. }
  268. }
  269. while ((calledName.name = Address.NextCalledName()) != null);
  270. throw new IOException("Failed to establish session with " + Address);
  271. }
  272. /// <exception cref="System.IO.IOException"></exception>
  273. private void Negotiate(int port, ServerMessageBlock resp)
  274. {
  275. lock (Sbuf)
  276. {
  277. if (port == 139)
  278. {
  279. Ssn139();
  280. }
  281. else
  282. {
  283. if (port == -1)
  284. {
  285. port = SmbConstants.DefaultPort;
  286. }
  287. // 445
  288. Socket = new SocketEx(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  289. if (LocalAddr != null)
  290. {
  291. Socket.Bind2(new IPEndPoint(LocalAddr, LocalPort));
  292. }
  293. Socket.Connect(new IPEndPoint(IPAddress.Parse(Address.GetHostAddress()), port), SmbConstants.ConnTimeout);
  294. Socket.SoTimeOut = SmbConstants.SoTimeout;
  295. Out = Socket.GetOutputStream();
  296. In = Socket.GetInputStream();
  297. }
  298. if (++Mid == 32000)
  299. {
  300. Mid = 1;
  301. }
  302. NegotiateRequest.Mid = Mid;
  303. int n = NegotiateRequest.Encode(Sbuf, 4);
  304. Encdec.Enc_uint32be(n & 0xFFFF, Sbuf, 0);
  305. if (Log.Level >= 4)
  306. {
  307. Log.WriteLine(NegotiateRequest);
  308. if (Log.Level >= 6)
  309. {
  310. Hexdump.ToHexdump(Log, Sbuf, 4, n);
  311. }
  312. }
  313. Out.Write(Sbuf, 0, 4 + n);
  314. Out.Flush();
  315. if (PeekKey() == null)
  316. {
  317. throw new IOException("transport closed in negotiate");
  318. }
  319. int size = Encdec.Dec_uint16be(Sbuf, 2) & 0xFFFF;
  320. if (size < 33 || (4 + size) > Sbuf.Length)
  321. {
  322. throw new IOException("Invalid payload size: " + size);
  323. }
  324. Readn(In, Sbuf, 4 + 32, size - 32);
  325. resp.Decode(Sbuf, 4);
  326. if (Log.Level >= 4)
  327. {
  328. Log.WriteLine(resp);
  329. if (Log.Level >= 6)
  330. {
  331. Hexdump.ToHexdump(Log, Sbuf, 4, n);
  332. }
  333. }
  334. }
  335. }
  336. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  337. public virtual void Connect()
  338. {
  339. try
  340. {
  341. base.Connect(SmbConstants.ResponseTimeout);
  342. }
  343. catch (TransportException te)
  344. {
  345. throw new SmbException("Failed to connect: " + Address, te);
  346. }
  347. }
  348. /// <exception cref="System.IO.IOException"></exception>
  349. protected internal override void DoConnect()
  350. {
  351. SmbComNegotiateResponse resp = new SmbComNegotiateResponse(Server);
  352. try
  353. {
  354. Negotiate(Port, resp);
  355. }
  356. catch (ConnectException)
  357. {
  358. Port = (Port == -1 || Port == SmbConstants.DefaultPort) ? 139 : SmbConstants.DefaultPort;
  359. Negotiate(Port, resp);
  360. }
  361. if (resp.DialectIndex > 10)
  362. {
  363. throw new SmbException("This client does not support the negotiated dialect.");
  364. }
  365. if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) != SmbConstants.CapExtendedSecurity && Server
  366. .EncryptionKeyLength != 8 && SmbConstants.LmCompatibility == 0)
  367. {
  368. throw new SmbException("Unexpected encryption key length: " + Server.EncryptionKeyLength
  369. );
  370. }
  371. TconHostName = Address.GetHostName();
  372. if (Server.SignaturesRequired || (Server.SignaturesEnabled && SmbConstants.Signpref))
  373. {
  374. Flags2 |= SmbConstants.Flags2SecuritySignatures;
  375. }
  376. else
  377. {
  378. Flags2 &= 0xFFFF ^ SmbConstants.Flags2SecuritySignatures;
  379. }
  380. MaxMpxCount = Math.Min(MaxMpxCount, Server.MaxMpxCount);
  381. if (MaxMpxCount < 1)
  382. {
  383. MaxMpxCount = 1;
  384. }
  385. SndBufSize = Math.Min(SndBufSize, Server.MaxBufferSize);
  386. Capabilities &= Server.Capabilities;
  387. if ((Server.Capabilities & SmbConstants.CapExtendedSecurity) == SmbConstants.CapExtendedSecurity)
  388. {
  389. Capabilities |= SmbConstants.CapExtendedSecurity;
  390. }
  391. // & doesn't copy high bit
  392. if ((Capabilities & SmbConstants.CapUnicode) == 0)
  393. {
  394. // server doesn't want unicode
  395. if (SmbConstants.ForceUnicode)
  396. {
  397. Capabilities |= SmbConstants.CapUnicode;
  398. }
  399. else
  400. {
  401. UseUnicode = false;
  402. Flags2 &= 0xFFFF ^ SmbConstants.Flags2Unicode;
  403. }
  404. }
  405. }
  406. /// <exception cref="System.IO.IOException"></exception>
  407. protected internal override void DoDisconnect(bool hard)
  408. {
  409. try
  410. {
  411. foreach (var ssn in Sessions)
  412. {
  413. ssn.Logoff(hard);
  414. }
  415. Out.Close();
  416. In.Close();
  417. //Socket.`Close` method deleted
  418. //Socket.Close();
  419. Socket.Dispose();
  420. }
  421. finally
  422. {
  423. Digest = null;
  424. Socket = null;
  425. TconHostName = null;
  426. }
  427. }
  428. /// <exception cref="System.IO.IOException"></exception>
  429. protected internal override void MakeKey(ServerMessageBlock request)
  430. {
  431. if (++Mid == 32000)
  432. {
  433. Mid = 1;
  434. }
  435. request.Mid = Mid;
  436. }
  437. /// <exception cref="System.IO.IOException"></exception>
  438. protected internal override ServerMessageBlock PeekKey()
  439. {
  440. int n;
  441. do
  442. {
  443. if ((n = Readn(In, Sbuf, 0, 4)) < 4)
  444. {
  445. return null;
  446. }
  447. }
  448. while (Sbuf[0] == 0x85);
  449. if ((n = Readn(In, Sbuf, 4, 32)) < 32)
  450. {
  451. return null;
  452. }
  453. if (Log.Level >= 4)
  454. {
  455. Log.WriteLine("New data read: " + this);
  456. Hexdump.ToHexdump(Log, Sbuf, 4, 32);
  457. }
  458. for (; ; )
  459. {
  460. if (Sbuf[0] == 0x00 && Sbuf[1] == 0x00 &&
  461. Sbuf[4] == 0xFF &&
  462. Sbuf[5] == 'S' &&
  463. Sbuf[6] == 'M' &&
  464. Sbuf[7] == 'B')
  465. {
  466. break;
  467. }
  468. for (int i = 0; i < 35; i++)
  469. {
  470. Sbuf[i] = Sbuf[i + 1];
  471. }
  472. int b;
  473. if ((b = In.Read()) == -1)
  474. {
  475. return null;
  476. }
  477. Sbuf[35] = unchecked((byte)b);
  478. }
  479. Key.Mid = Encdec.Dec_uint16le(Sbuf, 34) & 0xFFFF;
  480. return Key;
  481. }
  482. /// <exception cref="System.IO.IOException"></exception>
  483. protected internal override void DoSend(ServerMessageBlock request)
  484. {
  485. lock (Buf)
  486. {
  487. ServerMessageBlock smb = request;
  488. int n = smb.Encode(Buf, 4);
  489. Encdec.Enc_uint32be(n & 0xFFFF, Buf, 0);
  490. if (Log.Level >= 4)
  491. {
  492. do
  493. {
  494. Log.WriteLine(smb);
  495. }
  496. while (smb is AndXServerMessageBlock && (smb = ((AndXServerMessageBlock)smb).Andx
  497. ) != null);
  498. if (Log.Level >= 6)
  499. {
  500. Hexdump.ToHexdump(Log, Buf, 4, n);
  501. }
  502. }
  503. Out.Write(Buf, 0, 4 + n);
  504. }
  505. }
  506. /// <exception cref="System.IO.IOException"></exception>
  507. protected internal virtual void DoSend0(ServerMessageBlock request)
  508. {
  509. try
  510. {
  511. DoSend(request);
  512. }
  513. catch (IOException ioe)
  514. {
  515. if (Log.Level > 2)
  516. {
  517. Runtime.PrintStackTrace(ioe, Log);
  518. }
  519. try
  520. {
  521. Disconnect(true);
  522. }
  523. catch (IOException ioe2)
  524. {
  525. Runtime.PrintStackTrace(ioe2, Log);
  526. }
  527. throw;
  528. }
  529. }
  530. /// <exception cref="System.IO.IOException"></exception>
  531. protected internal override void DoRecv(Response response)
  532. {
  533. ServerMessageBlock resp = (ServerMessageBlock)response;
  534. resp.UseUnicode = UseUnicode;
  535. resp.ExtendedSecurity = (Capabilities & SmbConstants.CapExtendedSecurity) == SmbConstants.CapExtendedSecurity;
  536. lock (Buf)
  537. {
  538. Array.Copy(Sbuf, 0, Buf, 0, 4 + SmbConstants.HeaderLength);
  539. int size = Encdec.Dec_uint16be(Buf, 2) & 0xFFFF;
  540. if (size < (SmbConstants.HeaderLength + 1) || (4 + size) > RcvBufSize)
  541. {
  542. throw new IOException("Invalid payload size: " + size);
  543. }
  544. int errorCode = Encdec.Dec_uint32le(Buf, 9) & unchecked((int)(0xFFFFFFFF));
  545. if (resp.Command == ServerMessageBlock.SmbComReadAndx && (errorCode == 0 || errorCode
  546. == unchecked((int)(0x80000005))))
  547. {
  548. // overflow indicator normal for pipe
  549. SmbComReadAndXResponse r = (SmbComReadAndXResponse)resp;
  550. int off = SmbConstants.HeaderLength;
  551. Readn(In, Buf, 4 + off, 27);
  552. off += 27;
  553. resp.Decode(Buf, 4);
  554. int pad = r.DataOffset - off;
  555. if (r.ByteCount > 0 && pad > 0 && pad < 4)
  556. {
  557. Readn(In, Buf, 4 + off, pad);
  558. }
  559. if (r.DataLength > 0)
  560. {
  561. Readn(In, r.B, r.Off, r.DataLength);
  562. }
  563. }
  564. else
  565. {
  566. Readn(In, Buf, 4 + 32, size - 32);
  567. resp.Decode(Buf, 4);
  568. if (resp is SmbComTransactionResponse)
  569. {
  570. ((SmbComTransactionResponse)resp).Current();
  571. }
  572. }
  573. if (Digest != null && resp.ErrorCode == 0)
  574. {
  575. Digest.Verify(Buf, 4, resp);
  576. }
  577. if (Log.Level >= 4)
  578. {
  579. Log.WriteLine(response);
  580. if (Log.Level >= 6)
  581. {
  582. Hexdump.ToHexdump(Log, Buf, 4, size);
  583. }
  584. }
  585. }
  586. }
  587. /// <exception cref="System.IO.IOException"></exception>
  588. protected internal override void DoSkip()
  589. {
  590. int size = Encdec.Dec_uint16be(Sbuf, 2) & 0xFFFF;
  591. if (size < 33 || (4 + size) > RcvBufSize)
  592. {
  593. In.Skip(In.Available());
  594. }
  595. else
  596. {
  597. In.Skip(size - 32);
  598. }
  599. }
  600. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  601. internal virtual void CheckStatus(ServerMessageBlock req, ServerMessageBlock resp
  602. )
  603. {
  604. resp.ErrorCode = SmbException.GetStatusByCode(resp.ErrorCode);
  605. switch (resp.ErrorCode)
  606. {
  607. case NtStatus.NtStatusOk:
  608. {
  609. break;
  610. }
  611. case NtStatus.NtStatusAccessDenied:
  612. case NtStatus.NtStatusWrongPassword:
  613. case NtStatus.NtStatusLogonFailure:
  614. case NtStatus.NtStatusAccountRestriction:
  615. case NtStatus.NtStatusInvalidLogonHours:
  616. case NtStatus.NtStatusInvalidWorkstation:
  617. case NtStatus.NtStatusPasswordExpired:
  618. case NtStatus.NtStatusAccountDisabled:
  619. case NtStatus.NtStatusAccountLockedOut:
  620. case NtStatus.NtStatusTrustedDomainFailure:
  621. {
  622. throw new SmbAuthException(resp.ErrorCode);
  623. }
  624. case NtStatus.NtStatusPathNotCovered:
  625. {
  626. if (req.Auth == null)
  627. {
  628. throw new SmbException(resp.ErrorCode, null);
  629. }
  630. DfsReferral dr = GetDfsReferrals(req.Auth, req.Path, 1);
  631. if (dr == null)
  632. {
  633. throw new SmbException(resp.ErrorCode, null);
  634. }
  635. SmbFile.Dfs.Insert(req.Path, dr);
  636. throw dr;
  637. }
  638. case unchecked((int)(0x80000005)):
  639. {
  640. break;
  641. }
  642. case NtStatus.NtStatusMoreProcessingRequired:
  643. {
  644. break;
  645. }
  646. default:
  647. {
  648. throw new SmbException(resp.ErrorCode, null);
  649. }
  650. }
  651. if (resp.VerifyFailed)
  652. {
  653. throw new SmbException("Signature verification failed.");
  654. }
  655. }
  656. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  657. internal virtual void Send(ServerMessageBlock request, ServerMessageBlock response
  658. )
  659. {
  660. Connect();
  661. request.Flags2 |= Flags2;
  662. request.UseUnicode = UseUnicode;
  663. request.Response = response;
  664. if (request.Digest == null)
  665. {
  666. request.Digest = Digest;
  667. }
  668. try
  669. {
  670. if (response == null)
  671. {
  672. DoSend0(request);
  673. return;
  674. }
  675. if (request is SmbComTransaction)
  676. {
  677. response.Command = request.Command;
  678. SmbComTransaction req = (SmbComTransaction)request;
  679. SmbComTransactionResponse resp = (SmbComTransactionResponse)response;
  680. req.MaxBufferSize = SndBufSize;
  681. resp.Reset();
  682. try
  683. {
  684. BufferCache.GetBuffers(req, resp);
  685. req.Current();
  686. if (req.MoveNext())
  687. {
  688. SmbComBlankResponse interim = new SmbComBlankResponse();
  689. Sendrecv(req, interim, SmbConstants.ResponseTimeout);
  690. if (interim.ErrorCode != 0)
  691. {
  692. CheckStatus(req, interim);
  693. }
  694. req.Current();
  695. }
  696. else
  697. {
  698. MakeKey(req);
  699. }
  700. lock (this)
  701. {
  702. response.Received = false;
  703. resp.IsReceived = false;
  704. try
  705. {
  706. ResponseMap.Put(req, resp);
  707. do
  708. {
  709. DoSend0(req);
  710. }
  711. while (req.MoveNext() && req.Current() != null);
  712. long timeout = SmbConstants.ResponseTimeout;
  713. resp.Expiration = Runtime.CurrentTimeMillis() + timeout;
  714. while (resp.MoveNext())
  715. {
  716. Runtime.Wait(this, timeout);
  717. timeout = resp.Expiration - Runtime.CurrentTimeMillis();
  718. if (timeout <= 0)
  719. {
  720. throw new TransportException(this + " timedout waiting for response to " + req);
  721. }
  722. }
  723. if (response.ErrorCode != 0)
  724. {
  725. CheckStatus(req, resp);
  726. }
  727. }
  728. catch (Exception ie)
  729. {
  730. if (ie is SmbException)
  731. {
  732. throw;
  733. }
  734. else
  735. {
  736. throw new TransportException(ie);
  737. }
  738. }
  739. finally
  740. {
  741. //Sharpen.Collections.Remove<Hashtable, SmbComTransaction>(response_map, req);
  742. ResponseMap.Remove(req);
  743. }
  744. }
  745. }
  746. finally
  747. {
  748. BufferCache.ReleaseBuffer(req.TxnBuf);
  749. BufferCache.ReleaseBuffer(resp.TxnBuf);
  750. }
  751. }
  752. else
  753. {
  754. response.Command = request.Command;
  755. Sendrecv(request, response, SmbConstants.ResponseTimeout);
  756. }
  757. }
  758. catch (SmbException se)
  759. {
  760. throw;
  761. }
  762. catch (IOException ioe)
  763. {
  764. throw new SmbException(ioe.Message, ioe);
  765. }
  766. CheckStatus(request, response);
  767. }
  768. public override string ToString()
  769. {
  770. return base.ToString() + "[" + Address + ":" + Port + "]";
  771. }
  772. internal virtual void DfsPathSplit(string path, string[] result)
  773. {
  774. int ri = 0;
  775. int rlast = result.Length - 1;
  776. int i = 0;
  777. int b = 0;
  778. int len = path.Length;
  779. do
  780. {
  781. if (ri == rlast)
  782. {
  783. result[rlast] = Runtime.Substring(path, b);
  784. return;
  785. }
  786. if (i == len || path[i] == '\\')
  787. {
  788. result[ri++] = Runtime.Substring(path, b, i);
  789. b = i + 1;
  790. }
  791. }
  792. while (i++ < len);
  793. while (ri < result.Length)
  794. {
  795. result[ri++] = string.Empty;
  796. }
  797. }
  798. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  799. internal virtual DfsReferral GetDfsReferrals(NtlmPasswordAuthentication auth, string
  800. path, int rn)
  801. {
  802. SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null);
  803. Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();
  804. ipc.Send(new Trans2GetDfsReferral(path), resp);
  805. if (resp.NumReferrals == 0)
  806. {
  807. return null;
  808. }
  809. if (rn == 0 || resp.NumReferrals < rn)
  810. {
  811. rn = resp.NumReferrals;
  812. }
  813. DfsReferral dr = new DfsReferral();
  814. string[] arr = new string[4];
  815. long expiration = Runtime.CurrentTimeMillis() + Dfs.Ttl * 1000;
  816. int di = 0;
  817. for (; ; )
  818. {
  819. dr.ResolveHashes = auth.HashesExternal;
  820. dr.Ttl = resp.Referrals[di].Ttl;
  821. dr.Expiration = expiration;
  822. if (path.Equals(string.Empty))
  823. {
  824. dr.Server = Runtime.Substring(resp.Referrals[di].Path, 1).ToLower();
  825. }
  826. else
  827. {
  828. DfsPathSplit(resp.Referrals[di].Node, arr);
  829. dr.Server = arr[1];
  830. dr.Share = arr[2];
  831. dr.Path = arr[3];
  832. }
  833. dr.PathConsumed = resp.PathConsumed;
  834. di++;
  835. if (di == rn)
  836. {
  837. break;
  838. }
  839. dr.Append(new DfsReferral());
  840. dr = dr.Next;
  841. }
  842. return dr.Next;
  843. }
  844. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  845. internal virtual DfsReferral[] __getDfsReferrals(NtlmPasswordAuthentication auth,
  846. string path, int rn)
  847. {
  848. SmbTree ipc = GetSmbSession(auth).GetSmbTree("IPC$", null);
  849. Trans2GetDfsReferralResponse resp = new Trans2GetDfsReferralResponse();
  850. ipc.Send(new Trans2GetDfsReferral(path), resp);
  851. if (rn == 0 || resp.NumReferrals < rn)
  852. {
  853. rn = resp.NumReferrals;
  854. }
  855. DfsReferral[] drs = new DfsReferral[rn];
  856. string[] arr = new string[4];
  857. long expiration = Runtime.CurrentTimeMillis() + Dfs.Ttl * 1000;
  858. for (int di = 0; di < drs.Length; di++)
  859. {
  860. DfsReferral dr = new DfsReferral();
  861. dr.ResolveHashes = auth.HashesExternal;
  862. dr.Ttl = resp.Referrals[di].Ttl;
  863. dr.Expiration = expiration;
  864. if (path.Equals(string.Empty))
  865. {
  866. dr.Server = Runtime.Substring(resp.Referrals[di].Path, 1).ToLower();
  867. }
  868. else
  869. {
  870. DfsPathSplit(resp.Referrals[di].Node, arr);
  871. dr.Server = arr[1];
  872. dr.Share = arr[2];
  873. dr.Path = arr[3];
  874. }
  875. dr.PathConsumed = resp.PathConsumed;
  876. drs[di] = dr;
  877. }
  878. return drs;
  879. }
  880. }
  881. }