SftpSession.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using Renci.SshNet.Channels;
  7. using Renci.SshNet.Common;
  8. using System.Diagnostics;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  11. using Renci.SshNet.Sftp.Responses;
  12. using Renci.SshNet.Sftp.Requests;
  13. namespace Renci.SshNet.Sftp
  14. {
  15. internal class SftpSession : SubsystemSession
  16. {
  17. private Dictionary<uint, SftpRequest> _requests = new Dictionary<uint, SftpRequest>();
  18. private List<byte> _data = new List<byte>(32 * 1024);
  19. private EventWaitHandle _sftpVersionConfirmed = new AutoResetEvent(false);
  20. /// <summary>
  21. /// Gets remote working directory.
  22. /// </summary>
  23. public string WorkingDirectory { get; private set; }
  24. /// <summary>
  25. /// Gets SFTP protocol version.
  26. /// </summary>
  27. public int ProtocolVersion { get; private set; }
  28. private long _requestId;
  29. /// <summary>
  30. /// Gets the next request id for sftp session.
  31. /// </summary>
  32. public uint NextRequestId
  33. {
  34. get
  35. {
  36. return ((uint)Interlocked.Increment(ref this._requestId));
  37. }
  38. }
  39. #region SFTP messages
  40. //internal event EventHandler<MessageEventArgs<StatusMessage>> StatusMessageReceived;
  41. //internal event EventHandler<MessageEventArgs<DataMessage>> DataMessageReceived;
  42. //internal event EventHandler<MessageEventArgs<HandleMessage>> HandleMessageReceived;
  43. //internal event EventHandler<MessageEventArgs<NameMessage>> NameMessageReceived;
  44. //internal event EventHandler<MessageEventArgs<AttributesMessage>> AttributesMessageReceived;
  45. #endregion
  46. public SftpSession(Session session, TimeSpan operationTimeout)
  47. : base(session, "sftp", operationTimeout)
  48. {
  49. }
  50. public void ChangeDirectory(string path)
  51. {
  52. var fullPath = this.GetCanonicalPath(path);
  53. var handle = this.RequestOpenDir(fullPath);
  54. this.RequestClose(handle);
  55. this.WorkingDirectory = fullPath;
  56. }
  57. internal void SendMessage(SftpMessage sftpMessage)
  58. {
  59. this.SendData(new SftpDataMessage(this.ChannelNumber, sftpMessage));
  60. }
  61. /// <summary>
  62. /// Resolves path into absolute path on the server.
  63. /// </summary>
  64. /// <param name="path">Path to resolve.</param>
  65. /// <returns>Absolute path</returns>
  66. internal string GetCanonicalPath(string path)
  67. {
  68. var fullPath = path;
  69. if (!string.IsNullOrEmpty(path) && path[0] != '/' && this.WorkingDirectory != null)
  70. {
  71. if (this.WorkingDirectory[this.WorkingDirectory.Length - 1] == '/')
  72. {
  73. fullPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", this.WorkingDirectory, path);
  74. }
  75. else
  76. {
  77. fullPath = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", this.WorkingDirectory, path);
  78. }
  79. }
  80. var canonizedPath = string.Empty;
  81. var realPathFiles = this.RequestRealPath(fullPath, true);
  82. if (realPathFiles != null)
  83. {
  84. canonizedPath = realPathFiles.Keys.First();
  85. }
  86. if (!string.IsNullOrEmpty(canonizedPath))
  87. return canonizedPath;
  88. // Check for special cases
  89. if (fullPath.EndsWith("/.", StringComparison.InvariantCultureIgnoreCase) ||
  90. fullPath.EndsWith("/..", StringComparison.InvariantCultureIgnoreCase) ||
  91. fullPath.Equals("/", StringComparison.InvariantCultureIgnoreCase) ||
  92. fullPath.IndexOf('/') < 0)
  93. return fullPath;
  94. var pathParts = fullPath.Split(new char[] { '/' });
  95. var partialFullPath = string.Join("/", pathParts, 0, pathParts.Length - 1);
  96. if (string.IsNullOrEmpty(partialFullPath))
  97. partialFullPath = "/";
  98. realPathFiles = this.RequestRealPath(partialFullPath, true);
  99. if (realPathFiles != null)
  100. {
  101. canonizedPath = realPathFiles.Keys.First();
  102. }
  103. if (string.IsNullOrEmpty(canonizedPath))
  104. {
  105. return fullPath;
  106. }
  107. else
  108. {
  109. var slash = string.Empty;
  110. if (canonizedPath[canonizedPath.Length - 1] != '/')
  111. slash = "/";
  112. return string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", canonizedPath, slash, pathParts[pathParts.Length - 1]);
  113. }
  114. }
  115. internal bool FileExistsCommand(string path, Flags flags)
  116. {
  117. var handle = this.RequestOpen(path, flags, true);
  118. if (handle == null)
  119. {
  120. return false;
  121. }
  122. else
  123. {
  124. this.RequestClose(handle);
  125. return true;
  126. }
  127. }
  128. protected override void OnChannelOpen()
  129. {
  130. this.SendMessage(new SftpInitRequest(3));
  131. this.WaitHandle(this._sftpVersionConfirmed, this._operationTimeout);
  132. this.ProtocolVersion = 3;
  133. // Resolve current directory
  134. this.WorkingDirectory = this.RequestRealPath(".").Keys.First();
  135. }
  136. protected override void OnDataReceived(uint dataTypeCode, byte[] data)
  137. {
  138. // Add channel data to internal data holder
  139. this._data.AddRange(data);
  140. while (this._data.Count > 4 + 1)
  141. {
  142. // Extract packet length
  143. var packetLength = (this._data[0] << 24 | this._data[1] << 16 | this._data[2] << 8 | this._data[3]);
  144. // Check if complete packet data is available
  145. if (this._data.Count < packetLength + 4)
  146. {
  147. // Wait for complete message to arrive first
  148. break;
  149. }
  150. this._data.RemoveRange(0, 4);
  151. // Create buffer to hold packet data
  152. var packetData = new byte[packetLength];
  153. // Cope packet data to array
  154. this._data.CopyTo(0, packetData, 0, packetLength);
  155. // Remove loaded data from _data holder
  156. this._data.RemoveRange(0, packetLength);
  157. // Load SFTP Message and handle it
  158. var response = SftpMessage.Load(packetData);
  159. try
  160. {
  161. var versionResponse = response as SftpVersionResponse;
  162. if (versionResponse != null)
  163. {
  164. if (versionResponse.Version == 3)
  165. {
  166. this._sftpVersionConfirmed.Set();
  167. }
  168. else
  169. {
  170. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Server SFTP version {0} is not supported.", versionResponse.Version));
  171. }
  172. }
  173. else
  174. {
  175. this.HandleResponse(response as SftpResponse);
  176. }
  177. }
  178. catch (Exception exp)
  179. {
  180. this.RaiseError(exp);
  181. break;
  182. }
  183. }
  184. }
  185. protected override void Dispose(bool disposing)
  186. {
  187. base.Dispose(disposing);
  188. if (disposing)
  189. {
  190. if (this._sftpVersionConfirmed != null)
  191. {
  192. this._sftpVersionConfirmed.Dispose();
  193. this._sftpVersionConfirmed = null;
  194. }
  195. }
  196. }
  197. private void SendRequest(SftpRequest request)
  198. {
  199. lock (this._requests)
  200. {
  201. this._requests.Add(request.RequestId, request);
  202. }
  203. this.SendData(new SftpDataMessage(this.ChannelNumber, request));
  204. }
  205. #region SFTP API functions
  206. //#define SSH_FXP_INIT 1
  207. //#define SSH_FXP_VERSION 2
  208. /// <summary>
  209. /// Performs SSH_FXP_OPEN request
  210. /// </summary>
  211. /// <param name="path">The path.</param>
  212. /// <param name="flags">The flags.</param>
  213. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  214. /// <returns></returns>
  215. internal byte[] RequestOpen(string path, Flags flags, bool nullOnError = false)
  216. {
  217. byte[] handle = null;
  218. using (var wait = new AutoResetEvent(false))
  219. {
  220. var request = new SftpOpenRequest(this.NextRequestId, path, flags,
  221. (response) =>
  222. {
  223. handle = response.Handle;
  224. wait.Set();
  225. },
  226. (response) =>
  227. {
  228. if (nullOnError)
  229. {
  230. wait.Set();
  231. }
  232. else
  233. {
  234. this.ThrowSftpException(response);
  235. }
  236. });
  237. this.SendRequest(request);
  238. this.WaitHandle(wait, this._operationTimeout);
  239. }
  240. return handle;
  241. }
  242. /// <summary>
  243. /// Performs SSH_FXP_CLOSE request.
  244. /// </summary>
  245. /// <param name="handle">The handle.</param>
  246. internal void RequestClose(byte[] handle)
  247. {
  248. using (var wait = new AutoResetEvent(false))
  249. {
  250. var request = new SftpCloseRequest(this.NextRequestId, handle,
  251. (response) =>
  252. {
  253. if (response.StatusCode == StatusCodes.Ok)
  254. {
  255. wait.Set();
  256. }
  257. else
  258. {
  259. this.ThrowSftpException(response);
  260. }
  261. });
  262. this.SendRequest(request);
  263. this.WaitHandle(wait, this._operationTimeout);
  264. }
  265. }
  266. /// <summary>
  267. /// Performs SSH_FXP_READ request.
  268. /// </summary>
  269. /// <param name="handle">The handle.</param>
  270. /// <param name="offset">The offset.</param>
  271. /// <param name="length">The length.</param>
  272. /// <returns>data array; null if EOF</returns>
  273. internal byte[] RequestRead(byte[] handle, UInt64 offset, UInt32 length)
  274. {
  275. byte[] data = new byte[0];
  276. using (var wait = new AutoResetEvent(false))
  277. {
  278. var request = new SftpReadRequest(this.NextRequestId, handle, offset, length,
  279. (response) =>
  280. {
  281. data = response.Data;
  282. wait.Set();
  283. },
  284. (response) =>
  285. {
  286. if (response.StatusCode == StatusCodes.Eof)
  287. {
  288. wait.Set();
  289. }
  290. else
  291. {
  292. this.ThrowSftpException(response);
  293. }
  294. });
  295. this.SendRequest(request);
  296. this.WaitHandle(wait, this._operationTimeout);
  297. }
  298. return data;
  299. }
  300. /// <summary>
  301. /// Performs SSH_FXP_WRITE request.
  302. /// </summary>
  303. /// <param name="handle">The handle.</param>
  304. /// <param name="offset">The offset.</param>
  305. /// <param name="data">The data to send.</param>
  306. /// <param name="wait">The wait event handle if needed.</param>
  307. internal void RequestWrite(byte[] handle, UInt64 offset, byte[] data, EventWaitHandle wait)
  308. {
  309. var maximumDataSize = 1024 * 32 - 38;
  310. if (data.Length < maximumDataSize + 1)
  311. {
  312. var request = new SftpWriteRequest(this.NextRequestId, handle, offset, data,
  313. (response) =>
  314. {
  315. if (response.StatusCode == StatusCodes.Ok)
  316. {
  317. if (wait != null)
  318. wait.Set();
  319. }
  320. else
  321. {
  322. this.ThrowSftpException(response);
  323. }
  324. });
  325. this.SendRequest(request);
  326. if (wait != null)
  327. this.WaitHandle(wait, this._operationTimeout);
  328. }
  329. else
  330. {
  331. var block = data.Length / maximumDataSize + 1;
  332. for (int i = 0; i < block; i++)
  333. {
  334. var blockBufferSize = Math.Min(data.Length - maximumDataSize * i, maximumDataSize);
  335. var blockBuffer = new byte[blockBufferSize];
  336. Buffer.BlockCopy(data, i * maximumDataSize, blockBuffer, 0, blockBufferSize);
  337. var request = new SftpWriteRequest(this.NextRequestId, handle, offset + (ulong)(i * maximumDataSize), blockBuffer,
  338. (response) =>
  339. {
  340. if (response.StatusCode == StatusCodes.Ok)
  341. {
  342. if (wait != null)
  343. wait.Set();
  344. }
  345. else
  346. {
  347. this.ThrowSftpException(response);
  348. }
  349. });
  350. this.SendRequest(request);
  351. if (wait != null)
  352. this.WaitHandle(wait, this._operationTimeout);
  353. }
  354. }
  355. }
  356. /// <summary>
  357. /// Performs SSH_FXP_LSTAT request.
  358. /// </summary>
  359. /// <param name="path">The path.</param>
  360. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  361. /// <returns>
  362. /// File attributes
  363. /// </returns>
  364. internal SftpFileAttributes RequestLStat(string path, bool nullOnError = false)
  365. {
  366. SftpFileAttributes attributes = null;
  367. using (var wait = new AutoResetEvent(false))
  368. {
  369. var request = new SftpLStatRequest(this.NextRequestId, path,
  370. (response) =>
  371. {
  372. attributes = response.Attributes;
  373. wait.Set();
  374. },
  375. (response) =>
  376. {
  377. this.ThrowSftpException(response);
  378. });
  379. this.SendRequest(request);
  380. this.WaitHandle(wait, this._operationTimeout);
  381. }
  382. return attributes;
  383. }
  384. /// <summary>
  385. /// Performs SSH_FXP_FSTAT request.
  386. /// </summary>
  387. /// <param name="handle">The handle.</param>
  388. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  389. /// <returns>
  390. /// File attributes
  391. /// </returns>
  392. internal SftpFileAttributes RequestFStat(byte[] handle, bool nullOnError = false)
  393. {
  394. SftpFileAttributes attributes = null;
  395. using (var wait = new AutoResetEvent(false))
  396. {
  397. var request = new SftpFStatRequest(this.NextRequestId, handle,
  398. (response) =>
  399. {
  400. attributes = response.Attributes;
  401. wait.Set();
  402. },
  403. (response) =>
  404. {
  405. this.ThrowSftpException(response);
  406. });
  407. this.SendRequest(request);
  408. this.WaitHandle(wait, this._operationTimeout);
  409. }
  410. return attributes;
  411. }
  412. /// <summary>
  413. /// Performs SSH_FXP_SETSTAT request.
  414. /// </summary>
  415. /// <param name="path">The path.</param>
  416. /// <param name="attributes">The attributes.</param>
  417. internal void RequestSetStat(string path, SftpFileAttributes attributes)
  418. {
  419. using (var wait = new AutoResetEvent(false))
  420. {
  421. var request = new SftpSetStatRequest(this.NextRequestId, path, attributes,
  422. (response) =>
  423. {
  424. if (response.StatusCode == StatusCodes.Ok)
  425. {
  426. wait.Set();
  427. }
  428. else
  429. {
  430. this.ThrowSftpException(response);
  431. }
  432. });
  433. this.SendRequest(request);
  434. this.WaitHandle(wait, this._operationTimeout);
  435. }
  436. }
  437. /// <summary>
  438. /// Performs SSH_FXP_FSETSTAT request.
  439. /// </summary>
  440. /// <param name="handle">The handle.</param>
  441. /// <param name="attributes">The attributes.</param>
  442. internal void RequestFSetStat(byte[] handle, SftpFileAttributes attributes)
  443. {
  444. using (var wait = new AutoResetEvent(false))
  445. {
  446. var request = new SftpFSetStatRequest(this.NextRequestId, handle, attributes,
  447. (response) =>
  448. {
  449. if (response.StatusCode == StatusCodes.Ok)
  450. {
  451. wait.Set();
  452. }
  453. else
  454. {
  455. this.ThrowSftpException(response);
  456. }
  457. });
  458. this.SendRequest(request);
  459. this.WaitHandle(wait, this._operationTimeout);
  460. }
  461. }
  462. /// <summary>
  463. /// Performs SSH_FXP_OPENDIR request
  464. /// </summary>
  465. /// <param name="path">The path.</param>
  466. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  467. /// <returns></returns>
  468. internal byte[] RequestOpenDir(string path, bool nullOnError = false)
  469. {
  470. byte[] handle = null;
  471. using (var wait = new AutoResetEvent(false))
  472. {
  473. var request = new SftpOpenDirRequest(this.NextRequestId, path,
  474. (response) =>
  475. {
  476. handle = response.Handle;
  477. wait.Set();
  478. },
  479. (response) =>
  480. {
  481. if (nullOnError)
  482. {
  483. wait.Set();
  484. }
  485. else
  486. {
  487. this.ThrowSftpException(response);
  488. }
  489. });
  490. this.SendRequest(request);
  491. this.WaitHandle(wait, this._operationTimeout);
  492. }
  493. return handle;
  494. }
  495. /// <summary>
  496. /// Performs SSH_FXP_READDIR request
  497. /// </summary>
  498. /// <param name="handle">The handle.</param>
  499. /// <returns></returns>
  500. internal IDictionary<string, SftpFileAttributes> RequestReadDir(byte[] handle)
  501. {
  502. IDictionary<string, SftpFileAttributes> result = null;
  503. using (var wait = new AutoResetEvent(false))
  504. {
  505. var request = new SftpReadDirRequest(this.NextRequestId, handle,
  506. (response) =>
  507. {
  508. result = response.Files;
  509. wait.Set();
  510. },
  511. (response) =>
  512. {
  513. if (response.StatusCode == StatusCodes.Eof)
  514. {
  515. wait.Set();
  516. }
  517. else
  518. {
  519. this.ThrowSftpException(response);
  520. }
  521. });
  522. this.SendRequest(request);
  523. this.WaitHandle(wait, this._operationTimeout);
  524. }
  525. return result;
  526. }
  527. /// <summary>
  528. /// Performs SSH_FXP_REMOVE request.
  529. /// </summary>
  530. /// <param name="path">The path.</param>
  531. internal void RequestRemove(string path)
  532. {
  533. using (var wait = new AutoResetEvent(false))
  534. {
  535. var request = new SftpRemoveRequest(this.NextRequestId, path,
  536. (response) =>
  537. {
  538. if (response.StatusCode == StatusCodes.Ok)
  539. {
  540. wait.Set();
  541. }
  542. else
  543. {
  544. this.ThrowSftpException(response);
  545. }
  546. });
  547. this.SendRequest(request);
  548. this.WaitHandle(wait, this._operationTimeout);
  549. }
  550. }
  551. /// <summary>
  552. /// Performs SSH_FXP_MKDIR request.
  553. /// </summary>
  554. /// <param name="path">The path.</param>
  555. internal void RequestMkDir(string path)
  556. {
  557. using (var wait = new AutoResetEvent(false))
  558. {
  559. var request = new SftpMkDirRequest(this.NextRequestId, path,
  560. (response) =>
  561. {
  562. if (response.StatusCode == StatusCodes.Ok)
  563. {
  564. wait.Set();
  565. }
  566. else
  567. {
  568. this.ThrowSftpException(response);
  569. }
  570. });
  571. this.SendRequest(request);
  572. this.WaitHandle(wait, this._operationTimeout);
  573. }
  574. }
  575. /// <summary>
  576. /// Performs SSH_FXP_RMDIR request.
  577. /// </summary>
  578. /// <param name="path">The path.</param>
  579. internal void RequestRmDir(string path)
  580. {
  581. using (var wait = new AutoResetEvent(false))
  582. {
  583. var request = new SftpRmDirRequest(this.NextRequestId, path,
  584. (response) =>
  585. {
  586. if (response.StatusCode == StatusCodes.Ok)
  587. {
  588. wait.Set();
  589. }
  590. else
  591. {
  592. this.ThrowSftpException(response);
  593. }
  594. });
  595. this.SendRequest(request);
  596. this.WaitHandle(wait, this._operationTimeout);
  597. }
  598. }
  599. /// <summary>
  600. /// Performs SSH_FXP_REALPATH request
  601. /// </summary>
  602. /// <param name="path">The path.</param>
  603. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  604. /// <returns></returns>
  605. internal IDictionary<string, SftpFileAttributes> RequestRealPath(string path, bool nullOnError = false)
  606. {
  607. IDictionary<string, SftpFileAttributes> result = null;
  608. using (var wait = new AutoResetEvent(false))
  609. {
  610. var request = new SftpRealPathRequest(this.NextRequestId, path,
  611. (response) =>
  612. {
  613. result = response.Files;
  614. wait.Set();
  615. },
  616. (response) =>
  617. {
  618. if (nullOnError)
  619. {
  620. wait.Set();
  621. }
  622. else
  623. {
  624. this.ThrowSftpException(response);
  625. }
  626. });
  627. this.SendRequest(request);
  628. this.WaitHandle(wait, this._operationTimeout);
  629. }
  630. return result;
  631. }
  632. /// <summary>
  633. /// Performs SSH_FXP_STAT request.
  634. /// </summary>
  635. /// <param name="path">The path.</param>
  636. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  637. /// <returns>
  638. /// File attributes
  639. /// </returns>
  640. internal SftpFileAttributes RequestStat(string path, bool nullOnError = false)
  641. {
  642. SftpFileAttributes attributes = null;
  643. using (var wait = new AutoResetEvent(false))
  644. {
  645. var request = new SftpStatRequest(this.NextRequestId, path,
  646. (response) =>
  647. {
  648. attributes = response.Attributes;
  649. wait.Set();
  650. },
  651. (response) =>
  652. {
  653. if (nullOnError)
  654. {
  655. wait.Set();
  656. }
  657. else
  658. {
  659. this.ThrowSftpException(response);
  660. }
  661. });
  662. this.SendRequest(request);
  663. this.WaitHandle(wait, this._operationTimeout);
  664. }
  665. return attributes;
  666. }
  667. /// <summary>
  668. /// Performs SSH_FXP_RENAME request.
  669. /// </summary>
  670. /// <param name="oldPath">The old path.</param>
  671. /// <param name="newPath">The new path.</param>
  672. internal void RequestRename(string oldPath, string newPath)
  673. {
  674. using (var wait = new AutoResetEvent(false))
  675. {
  676. var request = new SftpRenameRequest(this.NextRequestId, oldPath, newPath,
  677. (response) =>
  678. {
  679. if (response.StatusCode == StatusCodes.Ok)
  680. {
  681. wait.Set();
  682. }
  683. else
  684. {
  685. this.ThrowSftpException(response);
  686. }
  687. });
  688. this.SendRequest(request);
  689. this.WaitHandle(wait, this._operationTimeout);
  690. }
  691. }
  692. /// <summary>
  693. /// Performs SSH_FXP_READLINK request.
  694. /// </summary>
  695. /// <param name="path">The path.</param>
  696. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  697. /// <returns></returns>
  698. internal IDictionary<string, SftpFileAttributes> RequestReadLink(string path, bool nullOnError = false)
  699. {
  700. IDictionary<string, SftpFileAttributes> result = null;
  701. using (var wait = new AutoResetEvent(false))
  702. {
  703. var request = new SftpReadLinkRequest(this.NextRequestId, path,
  704. (response) =>
  705. {
  706. result = response.Files;
  707. wait.Set();
  708. },
  709. (response) =>
  710. {
  711. if (nullOnError)
  712. {
  713. wait.Set();
  714. }
  715. else
  716. {
  717. this.ThrowSftpException(response);
  718. }
  719. });
  720. this.SendRequest(request);
  721. this.WaitHandle(wait, this._operationTimeout);
  722. }
  723. return result;
  724. }
  725. /// <summary>
  726. /// Performs SSH_FXP_SYMLINK request.
  727. /// </summary>
  728. /// <param name="linkpath">The linkpath.</param>
  729. /// <param name="targetpath">The targetpath.</param>
  730. internal void RequestSymLink(string linkpath, string targetpath)
  731. {
  732. using (var wait = new AutoResetEvent(false))
  733. {
  734. var request = new SftpSymLinkRequest(this.NextRequestId, linkpath, targetpath,
  735. (response) =>
  736. {
  737. if (response.StatusCode == StatusCodes.Ok)
  738. {
  739. wait.Set();
  740. }
  741. else
  742. {
  743. this.ThrowSftpException(response);
  744. }
  745. });
  746. this.SendRequest(request);
  747. this.WaitHandle(wait, this._operationTimeout);
  748. }
  749. }
  750. #endregion
  751. private void ThrowSftpException(SftpStatusResponse response)
  752. {
  753. if (response.StatusCode == StatusCodes.PermissionDenied)
  754. {
  755. throw new SftpPermissionDeniedException(response.ErrorMessage);
  756. }
  757. else if (response.StatusCode == StatusCodes.NoSuchFile)
  758. {
  759. throw new SftpPathNotFoundException(response.ErrorMessage);
  760. }
  761. else
  762. {
  763. throw new SshException(response.ErrorMessage);
  764. }
  765. }
  766. private void HandleResponse(SftpResponse response)
  767. {
  768. SftpRequest request = null;
  769. lock (this._requests)
  770. {
  771. this._requests.TryGetValue(response.ResponseId, out request);
  772. if (request != null)
  773. {
  774. this._requests.Remove(response.ResponseId);
  775. }
  776. }
  777. if (request == null)
  778. throw new InvalidOperationException("Invalid response.");
  779. request.Complete(response);
  780. }
  781. }
  782. }