SftpSession.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Threading;
  5. using Renci.SshNet.Channels;
  6. using Renci.SshNet.Common;
  7. using System.Collections.Generic;
  8. using System.Globalization;
  9. using Renci.SshNet.Sftp.Responses;
  10. using Renci.SshNet.Sftp.Requests;
  11. namespace Renci.SshNet.Sftp
  12. {
  13. internal class SftpSession : SubsystemSession
  14. {
  15. private const int MAXIMUM_SUPPORTED_VERSION = 3;
  16. private const int MINIMUM_SUPPORTED_VERSION = 0;
  17. private readonly Dictionary<uint, SftpRequest> _requests = new Dictionary<uint, SftpRequest>();
  18. private readonly List<byte> _data = new List<byte>(16 * 1024);
  19. private EventWaitHandle _sftpVersionConfirmed = new AutoResetEvent(false);
  20. private IDictionary<string, string> _supportedExtensions;
  21. /// <summary>
  22. /// Gets remote working directory.
  23. /// </summary>
  24. public string WorkingDirectory { get; private set; }
  25. /// <summary>
  26. /// Gets SFTP protocol version.
  27. /// </summary>
  28. public uint ProtocolVersion { get; private set; }
  29. private long _requestId;
  30. /// <summary>
  31. /// Gets the next request id for sftp session.
  32. /// </summary>
  33. public uint NextRequestId
  34. {
  35. get
  36. {
  37. #if WINDOWS_PHONE
  38. lock (this)
  39. {
  40. this._requestId++;
  41. }
  42. return (uint)this._requestId;
  43. #else
  44. return ((uint)Interlocked.Increment(ref this._requestId));
  45. #endif
  46. }
  47. }
  48. public SftpSession(Session session, TimeSpan operationTimeout, Encoding encoding)
  49. : base(session, "sftp", operationTimeout, encoding)
  50. {
  51. }
  52. public void ChangeDirectory(string path)
  53. {
  54. var fullPath = this.GetCanonicalPath(path);
  55. var handle = this.RequestOpenDir(fullPath);
  56. this.RequestClose(handle);
  57. this.WorkingDirectory = fullPath;
  58. }
  59. internal void SendMessage(SftpMessage sftpMessage)
  60. {
  61. var messageData = sftpMessage.GetBytes();
  62. var data = new byte[4 + messageData.Length];
  63. ((uint)messageData.Length).GetBytes().CopyTo(data, 0);
  64. messageData.CopyTo(data, 4);
  65. this.SendData(data);
  66. }
  67. /// <summary>
  68. /// Resolves path into absolute path on the server.
  69. /// </summary>
  70. /// <param name="path">Path to resolve.</param>
  71. /// <returns>Absolute path</returns>
  72. internal string GetCanonicalPath(string path)
  73. {
  74. var fullPath = GetFullRemotePath(path);
  75. var canonizedPath = string.Empty;
  76. var realPathFiles = this.RequestRealPath(fullPath, true);
  77. if (realPathFiles != null)
  78. {
  79. canonizedPath = realPathFiles.First().Key;
  80. }
  81. if (!string.IsNullOrEmpty(canonizedPath))
  82. return canonizedPath;
  83. // Check for special cases
  84. if (fullPath.EndsWith("/.", StringComparison.InvariantCultureIgnoreCase) ||
  85. fullPath.EndsWith("/..", StringComparison.InvariantCultureIgnoreCase) ||
  86. fullPath.Equals("/", StringComparison.InvariantCultureIgnoreCase) ||
  87. fullPath.IndexOf('/') < 0)
  88. return fullPath;
  89. var pathParts = fullPath.Split(new char[] { '/' });
  90. var partialFullPath = string.Join("/", pathParts, 0, pathParts.Length - 1);
  91. if (string.IsNullOrEmpty(partialFullPath))
  92. partialFullPath = "/";
  93. realPathFiles = this.RequestRealPath(partialFullPath, true);
  94. if (realPathFiles != null)
  95. {
  96. canonizedPath = realPathFiles.First().Key;
  97. }
  98. if (string.IsNullOrEmpty(canonizedPath))
  99. {
  100. return fullPath;
  101. }
  102. var slash = string.Empty;
  103. if (canonizedPath[canonizedPath.Length - 1] != '/')
  104. slash = "/";
  105. return string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", canonizedPath, slash, pathParts[pathParts.Length - 1]);
  106. }
  107. internal string GetFullRemotePath(string path)
  108. {
  109. var fullPath = path;
  110. if (!string.IsNullOrEmpty(path) && path[0] != '/' && this.WorkingDirectory != null)
  111. {
  112. if (this.WorkingDirectory[this.WorkingDirectory.Length - 1] == '/')
  113. {
  114. fullPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", this.WorkingDirectory, path);
  115. }
  116. else
  117. {
  118. fullPath = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", this.WorkingDirectory, path);
  119. }
  120. }
  121. return fullPath;
  122. }
  123. protected override void OnChannelOpen()
  124. {
  125. this.SendMessage(new SftpInitRequest(MAXIMUM_SUPPORTED_VERSION));
  126. this.WaitOnHandle(this._sftpVersionConfirmed, this._operationTimeout);
  127. if (this.ProtocolVersion > MAXIMUM_SUPPORTED_VERSION || this.ProtocolVersion < MINIMUM_SUPPORTED_VERSION)
  128. {
  129. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Server SFTP version {0} is not supported.", this.ProtocolVersion));
  130. }
  131. // Resolve current directory
  132. this.WorkingDirectory = this.RequestRealPath(".").First().Key;
  133. }
  134. protected override void OnDataReceived(uint dataTypeCode, byte[] data)
  135. {
  136. // Add channel data to internal data holder
  137. this._data.AddRange(data);
  138. while (this._data.Count > 4 + 1)
  139. {
  140. // Extract packet length
  141. var packetLength = (this._data[0] << 24 | this._data[1] << 16 | this._data[2] << 8 | this._data[3]);
  142. // Check if complete packet data is available
  143. if (this._data.Count < packetLength + 4)
  144. {
  145. // Wait for complete message to arrive first
  146. break;
  147. }
  148. this._data.RemoveRange(0, 4);
  149. // Create buffer to hold packet data
  150. var packetData = new byte[packetLength];
  151. // Cope packet data to array
  152. this._data.CopyTo(0, packetData, 0, packetLength);
  153. // Remove loaded data from _data holder
  154. this._data.RemoveRange(0, packetLength);
  155. // Load SFTP Message and handle it
  156. var response = SftpMessage.Load(this.ProtocolVersion, packetData, this.Encoding);
  157. try
  158. {
  159. var versionResponse = response as SftpVersionResponse;
  160. if (versionResponse != null)
  161. {
  162. this.ProtocolVersion = versionResponse.Version;
  163. this._supportedExtensions = versionResponse.Extentions;
  164. this._sftpVersionConfirmed.Set();
  165. }
  166. else
  167. {
  168. this.HandleResponse(response as SftpResponse);
  169. }
  170. }
  171. catch (Exception exp)
  172. {
  173. this.RaiseError(exp);
  174. break;
  175. }
  176. }
  177. }
  178. protected override void Dispose(bool disposing)
  179. {
  180. base.Dispose(disposing);
  181. if (disposing)
  182. {
  183. if (this._sftpVersionConfirmed != null)
  184. {
  185. this._sftpVersionConfirmed.Dispose();
  186. this._sftpVersionConfirmed = null;
  187. }
  188. }
  189. }
  190. private void SendRequest(SftpRequest request)
  191. {
  192. lock (this._requests)
  193. {
  194. this._requests.Add(request.RequestId, request);
  195. }
  196. this.SendMessage(request);
  197. }
  198. #region SFTP API functions
  199. /// <summary>
  200. /// Performs SSH_FXP_OPEN request
  201. /// </summary>
  202. /// <param name="path">The path.</param>
  203. /// <param name="flags">The flags.</param>
  204. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  205. /// <returns>File handle.</returns>
  206. internal byte[] RequestOpen(string path, Flags flags, bool nullOnError = false)
  207. {
  208. byte[] handle = null;
  209. SshException exception = null;
  210. using (var wait = new AutoResetEvent(false))
  211. {
  212. var request = new SftpOpenRequest(this.ProtocolVersion, this.NextRequestId, path, this.Encoding, flags,
  213. response =>
  214. {
  215. handle = response.Handle;
  216. wait.Set();
  217. },
  218. response =>
  219. {
  220. exception = this.GetSftpException(response);
  221. wait.Set();
  222. });
  223. this.SendRequest(request);
  224. this.WaitOnHandle(wait, this._operationTimeout);
  225. }
  226. if (!nullOnError && exception != null)
  227. {
  228. throw exception;
  229. }
  230. return handle;
  231. }
  232. /// <summary>
  233. /// Performs SSH_FXP_CLOSE request.
  234. /// </summary>
  235. /// <param name="handle">The handle.</param>
  236. internal void RequestClose(byte[] handle)
  237. {
  238. SshException exception = null;
  239. using (var wait = new AutoResetEvent(false))
  240. {
  241. var request = new SftpCloseRequest(this.ProtocolVersion, this.NextRequestId, handle,
  242. (response) =>
  243. {
  244. exception = this.GetSftpException(response);
  245. wait.Set();
  246. });
  247. this.SendRequest(request);
  248. this.WaitOnHandle(wait, this._operationTimeout);
  249. }
  250. if (exception != null)
  251. {
  252. throw exception;
  253. }
  254. }
  255. /// <summary>
  256. /// Performs SSH_FXP_READ request.
  257. /// </summary>
  258. /// <param name="handle">The handle.</param>
  259. /// <param name="offset">The offset.</param>
  260. /// <param name="length">The length.</param>
  261. /// <returns>data array; null if EOF</returns>
  262. internal byte[] RequestRead(byte[] handle, UInt64 offset, UInt32 length)
  263. {
  264. SshException exception = null;
  265. var data = new byte[0];
  266. using (var wait = new AutoResetEvent(false))
  267. {
  268. var request = new SftpReadRequest(this.ProtocolVersion, this.NextRequestId, handle, offset, length,
  269. (response) =>
  270. {
  271. data = response.Data;
  272. wait.Set();
  273. },
  274. (response) =>
  275. {
  276. if (response.StatusCode != StatusCodes.Eof)
  277. {
  278. exception = this.GetSftpException(response);
  279. }
  280. wait.Set();
  281. });
  282. this.SendRequest(request);
  283. this.WaitOnHandle(wait, this._operationTimeout);
  284. }
  285. if (exception != null)
  286. {
  287. throw exception;
  288. }
  289. return data;
  290. }
  291. /// <summary>
  292. /// Performs SSH_FXP_WRITE request.
  293. /// </summary>
  294. /// <param name="handle">The handle.</param>
  295. /// <param name="offset">The offset.</param>
  296. /// <param name="data">The data to send.</param>
  297. /// <param name="wait">The wait event handle if needed.</param>
  298. /// <param name="writeCompleted">The callback to invoke when the write has completed.</param>
  299. internal void RequestWrite(byte[] handle, UInt64 offset, byte[] data, EventWaitHandle wait, Action<SftpStatusResponse> writeCompleted = null)
  300. {
  301. SshException exception = null;
  302. var request = new SftpWriteRequest(this.ProtocolVersion, this.NextRequestId, handle, offset, data,
  303. (response) =>
  304. {
  305. if (writeCompleted != null)
  306. {
  307. writeCompleted(response);
  308. }
  309. exception = this.GetSftpException(response);
  310. if (wait != null)
  311. wait.Set();
  312. });
  313. this.SendRequest(request);
  314. if (wait != null)
  315. this.WaitOnHandle(wait, this._operationTimeout);
  316. if (exception != null)
  317. {
  318. throw exception;
  319. }
  320. }
  321. /// <summary>
  322. /// Performs SSH_FXP_LSTAT request.
  323. /// </summary>
  324. /// <param name="path">The path.</param>
  325. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  326. /// <returns>
  327. /// File attributes
  328. /// </returns>
  329. internal SftpFileAttributes RequestLStat(string path, bool nullOnError = false)
  330. {
  331. SshException exception = null;
  332. SftpFileAttributes attributes = null;
  333. using (var wait = new AutoResetEvent(false))
  334. {
  335. var request = new SftpLStatRequest(this.ProtocolVersion, this.NextRequestId, path, this.Encoding,
  336. (response) =>
  337. {
  338. attributes = response.Attributes;
  339. wait.Set();
  340. },
  341. (response) =>
  342. {
  343. exception = this.GetSftpException(response);
  344. wait.Set();
  345. });
  346. this.SendRequest(request);
  347. this.WaitOnHandle(wait, this._operationTimeout);
  348. }
  349. if (exception != null)
  350. {
  351. throw exception;
  352. }
  353. return attributes;
  354. }
  355. /// <summary>
  356. /// Performs SSH_FXP_FSTAT request.
  357. /// </summary>
  358. /// <param name="handle">The handle.</param>
  359. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  360. /// <returns>
  361. /// File attributes
  362. /// </returns>
  363. internal SftpFileAttributes RequestFStat(byte[] handle, bool nullOnError = false)
  364. {
  365. SshException exception = null;
  366. SftpFileAttributes attributes = null;
  367. using (var wait = new AutoResetEvent(false))
  368. {
  369. var request = new SftpFStatRequest(this.ProtocolVersion, this.NextRequestId, handle,
  370. (response) =>
  371. {
  372. attributes = response.Attributes;
  373. wait.Set();
  374. },
  375. (response) =>
  376. {
  377. exception = this.GetSftpException(response);
  378. wait.Set();
  379. });
  380. this.SendRequest(request);
  381. this.WaitOnHandle(wait, this._operationTimeout);
  382. }
  383. if (exception != null)
  384. {
  385. throw exception;
  386. }
  387. return attributes;
  388. }
  389. /// <summary>
  390. /// Performs SSH_FXP_SETSTAT request.
  391. /// </summary>
  392. /// <param name="path">The path.</param>
  393. /// <param name="attributes">The attributes.</param>
  394. internal void RequestSetStat(string path, SftpFileAttributes attributes)
  395. {
  396. SshException exception = null;
  397. using (var wait = new AutoResetEvent(false))
  398. {
  399. var request = new SftpSetStatRequest(this.ProtocolVersion, this.NextRequestId, path, this.Encoding, attributes,
  400. (response) =>
  401. {
  402. exception = this.GetSftpException(response);
  403. wait.Set();
  404. });
  405. this.SendRequest(request);
  406. this.WaitOnHandle(wait, this._operationTimeout);
  407. }
  408. if (exception != null)
  409. {
  410. throw exception;
  411. }
  412. }
  413. /// <summary>
  414. /// Performs SSH_FXP_FSETSTAT request.
  415. /// </summary>
  416. /// <param name="handle">The handle.</param>
  417. /// <param name="attributes">The attributes.</param>
  418. internal void RequestFSetStat(byte[] handle, SftpFileAttributes attributes)
  419. {
  420. SshException exception = null;
  421. using (var wait = new AutoResetEvent(false))
  422. {
  423. var request = new SftpFSetStatRequest(this.ProtocolVersion, this.NextRequestId, handle, attributes,
  424. (response) =>
  425. {
  426. exception = this.GetSftpException(response);
  427. wait.Set();
  428. });
  429. this.SendRequest(request);
  430. this.WaitOnHandle(wait, this._operationTimeout);
  431. }
  432. if (exception != null)
  433. {
  434. throw exception;
  435. }
  436. }
  437. /// <summary>
  438. /// Performs SSH_FXP_OPENDIR request
  439. /// </summary>
  440. /// <param name="path">The path.</param>
  441. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  442. /// <returns>File handle.</returns>
  443. internal byte[] RequestOpenDir(string path, bool nullOnError = false)
  444. {
  445. SshException exception = null;
  446. byte[] handle = null;
  447. using (var wait = new AutoResetEvent(false))
  448. {
  449. var request = new SftpOpenDirRequest(this.ProtocolVersion, this.NextRequestId, path, this.Encoding,
  450. (response) =>
  451. {
  452. handle = response.Handle;
  453. wait.Set();
  454. },
  455. (response) =>
  456. {
  457. exception = this.GetSftpException(response);
  458. wait.Set();
  459. });
  460. this.SendRequest(request);
  461. this.WaitOnHandle(wait, this._operationTimeout);
  462. }
  463. if (!nullOnError && exception != null)
  464. {
  465. throw exception;
  466. }
  467. return handle;
  468. }
  469. /// <summary>
  470. /// Performs SSH_FXP_READDIR request
  471. /// </summary>
  472. /// <param name="handle">The handle.</param>
  473. /// <returns></returns>
  474. internal KeyValuePair<string, SftpFileAttributes>[] RequestReadDir(byte[] handle)
  475. {
  476. SshException exception = null;
  477. KeyValuePair<string, SftpFileAttributes>[] result = null;
  478. using (var wait = new AutoResetEvent(false))
  479. {
  480. var request = new SftpReadDirRequest(this.ProtocolVersion, this.NextRequestId, handle,
  481. (response) =>
  482. {
  483. result = response.Files;
  484. wait.Set();
  485. },
  486. (response) =>
  487. {
  488. if (response.StatusCode != StatusCodes.Eof)
  489. {
  490. exception = this.GetSftpException(response);
  491. }
  492. wait.Set();
  493. });
  494. this.SendRequest(request);
  495. this.WaitOnHandle(wait, this._operationTimeout);
  496. }
  497. if (exception != null)
  498. {
  499. throw exception;
  500. }
  501. return result;
  502. }
  503. /// <summary>
  504. /// Performs SSH_FXP_REMOVE request.
  505. /// </summary>
  506. /// <param name="path">The path.</param>
  507. internal void RequestRemove(string path)
  508. {
  509. SshException exception = null;
  510. using (var wait = new AutoResetEvent(false))
  511. {
  512. var request = new SftpRemoveRequest(this.ProtocolVersion, this.NextRequestId, path, this.Encoding,
  513. (response) =>
  514. {
  515. exception = this.GetSftpException(response);
  516. wait.Set();
  517. });
  518. this.SendRequest(request);
  519. this.WaitOnHandle(wait, this._operationTimeout);
  520. }
  521. if (exception != null)
  522. {
  523. throw exception;
  524. }
  525. }
  526. /// <summary>
  527. /// Performs SSH_FXP_MKDIR request.
  528. /// </summary>
  529. /// <param name="path">The path.</param>
  530. internal void RequestMkDir(string path)
  531. {
  532. SshException exception = null;
  533. using (var wait = new AutoResetEvent(false))
  534. {
  535. var request = new SftpMkDirRequest(this.ProtocolVersion, this.NextRequestId, path, this.Encoding,
  536. (response) =>
  537. {
  538. exception = this.GetSftpException(response);
  539. wait.Set();
  540. });
  541. this.SendRequest(request);
  542. this.WaitOnHandle(wait, this._operationTimeout);
  543. }
  544. if (exception != null)
  545. {
  546. throw exception;
  547. }
  548. }
  549. /// <summary>
  550. /// Performs SSH_FXP_RMDIR request.
  551. /// </summary>
  552. /// <param name="path">The path.</param>
  553. internal void RequestRmDir(string path)
  554. {
  555. SshException exception = null;
  556. using (var wait = new AutoResetEvent(false))
  557. {
  558. var request = new SftpRmDirRequest(this.ProtocolVersion, this.NextRequestId, path, this.Encoding,
  559. (response) =>
  560. {
  561. exception = this.GetSftpException(response);
  562. wait.Set();
  563. });
  564. this.SendRequest(request);
  565. this.WaitOnHandle(wait, this._operationTimeout);
  566. }
  567. if (exception != null)
  568. {
  569. throw exception;
  570. }
  571. }
  572. /// <summary>
  573. /// Performs SSH_FXP_REALPATH request
  574. /// </summary>
  575. /// <param name="path">The path.</param>
  576. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  577. /// <returns></returns>
  578. internal KeyValuePair<string, SftpFileAttributes>[] RequestRealPath(string path, bool nullOnError = false)
  579. {
  580. SshException exception = null;
  581. KeyValuePair<string, SftpFileAttributes>[] result = null;
  582. using (var wait = new AutoResetEvent(false))
  583. {
  584. var request = new SftpRealPathRequest(this.ProtocolVersion, this.NextRequestId, path, this.Encoding,
  585. (response) =>
  586. {
  587. result = response.Files;
  588. wait.Set();
  589. },
  590. (response) =>
  591. {
  592. exception = this.GetSftpException(response);
  593. wait.Set();
  594. });
  595. this.SendRequest(request);
  596. this.WaitOnHandle(wait, this._operationTimeout);
  597. }
  598. if (!nullOnError && exception != null)
  599. {
  600. throw exception;
  601. }
  602. return result;
  603. }
  604. /// <summary>
  605. /// Performs SSH_FXP_STAT request.
  606. /// </summary>
  607. /// <param name="path">The path.</param>
  608. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  609. /// <returns>
  610. /// File attributes
  611. /// </returns>
  612. internal SftpFileAttributes RequestStat(string path, bool nullOnError = false)
  613. {
  614. SshException exception = null;
  615. SftpFileAttributes attributes = null;
  616. using (var wait = new AutoResetEvent(false))
  617. {
  618. var request = new SftpStatRequest(this.ProtocolVersion, this.NextRequestId, path, this.Encoding,
  619. (response) =>
  620. {
  621. attributes = response.Attributes;
  622. wait.Set();
  623. },
  624. (response) =>
  625. {
  626. exception = this.GetSftpException(response);
  627. wait.Set();
  628. });
  629. this.SendRequest(request);
  630. this.WaitOnHandle(wait, this._operationTimeout);
  631. }
  632. if (!nullOnError && exception != null)
  633. {
  634. throw exception;
  635. }
  636. return attributes;
  637. }
  638. /// <summary>
  639. /// Performs SSH_FXP_RENAME request.
  640. /// </summary>
  641. /// <param name="oldPath">The old path.</param>
  642. /// <param name="newPath">The new path.</param>
  643. internal void RequestRename(string oldPath, string newPath)
  644. {
  645. if (this.ProtocolVersion < 2)
  646. {
  647. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_RENAME operation is not supported in {0} version that server operates in.", this.ProtocolVersion));
  648. }
  649. SshException exception = null;
  650. using (var wait = new AutoResetEvent(false))
  651. {
  652. var request = new SftpRenameRequest(this.ProtocolVersion, this.NextRequestId, oldPath, newPath, this.Encoding,
  653. (response) =>
  654. {
  655. exception = this.GetSftpException(response);
  656. wait.Set();
  657. });
  658. this.SendRequest(request);
  659. this.WaitOnHandle(wait, this._operationTimeout);
  660. }
  661. if (exception != null)
  662. {
  663. throw exception;
  664. }
  665. }
  666. /// <summary>
  667. /// Performs SSH_FXP_READLINK request.
  668. /// </summary>
  669. /// <param name="path">The path.</param>
  670. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  671. /// <returns></returns>
  672. internal KeyValuePair<string, SftpFileAttributes>[] RequestReadLink(string path, bool nullOnError = false)
  673. {
  674. if (this.ProtocolVersion < 3)
  675. {
  676. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_READLINK operation is not supported in {0} version that server operates in.", this.ProtocolVersion));
  677. }
  678. SshException exception = null;
  679. KeyValuePair<string, SftpFileAttributes>[] result = null;
  680. using (var wait = new AutoResetEvent(false))
  681. {
  682. var request = new SftpReadLinkRequest(this.ProtocolVersion, this.NextRequestId, path, this.Encoding,
  683. (response) =>
  684. {
  685. result = response.Files;
  686. wait.Set();
  687. },
  688. (response) =>
  689. {
  690. exception = this.GetSftpException(response);
  691. wait.Set();
  692. });
  693. this.SendRequest(request);
  694. this.WaitOnHandle(wait, this._operationTimeout);
  695. }
  696. if (!nullOnError && exception != null)
  697. {
  698. throw exception;
  699. }
  700. return result;
  701. }
  702. /// <summary>
  703. /// Performs SSH_FXP_SYMLINK request.
  704. /// </summary>
  705. /// <param name="linkpath">The linkpath.</param>
  706. /// <param name="targetpath">The targetpath.</param>
  707. internal void RequestSymLink(string linkpath, string targetpath)
  708. {
  709. if (this.ProtocolVersion < 3)
  710. {
  711. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_SYMLINK operation is not supported in {0} version that server operates in.", this.ProtocolVersion));
  712. }
  713. SshException exception = null;
  714. using (var wait = new AutoResetEvent(false))
  715. {
  716. var request = new SftpSymLinkRequest(this.ProtocolVersion, this.NextRequestId, linkpath, targetpath, this.Encoding,
  717. (response) =>
  718. {
  719. exception = this.GetSftpException(response);
  720. wait.Set();
  721. });
  722. this.SendRequest(request);
  723. this.WaitOnHandle(wait, this._operationTimeout);
  724. }
  725. if (exception != null)
  726. {
  727. throw exception;
  728. }
  729. }
  730. #endregion
  731. #region SFTP Extended API functions
  732. /// <summary>
  733. /// Performs posix-rename@openssh.com extended request.
  734. /// </summary>
  735. /// <param name="oldPath">The old path.</param>
  736. /// <param name="newPath">The new path.</param>
  737. internal void RequestPosixRename(string oldPath, string newPath)
  738. {
  739. if (this.ProtocolVersion < 3)
  740. {
  741. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", this.ProtocolVersion));
  742. }
  743. SshException exception = null;
  744. using (var wait = new AutoResetEvent(false))
  745. {
  746. var request = new PosixRenameRequest(this.ProtocolVersion, this.NextRequestId, oldPath, newPath, this.Encoding,
  747. (response) =>
  748. {
  749. exception = this.GetSftpException(response);
  750. wait.Set();
  751. });
  752. if (!this._supportedExtensions.ContainsKey(request.Name))
  753. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
  754. this.SendRequest(request);
  755. this.WaitOnHandle(wait, this._operationTimeout);
  756. }
  757. if (exception != null)
  758. {
  759. throw exception;
  760. }
  761. }
  762. /// <summary>
  763. /// Performs statvfs@openssh.com extended request.
  764. /// </summary>
  765. /// <param name="path">The path.</param>
  766. /// <param name="nullOnError">if set to <c>true</c> [null on error].</param>
  767. /// <returns></returns>
  768. internal SftpFileSytemInformation RequestStatVfs(string path, bool nullOnError = false)
  769. {
  770. if (this.ProtocolVersion < 3)
  771. {
  772. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", this.ProtocolVersion));
  773. }
  774. SshException exception = null;
  775. SftpFileSytemInformation information = null;
  776. using (var wait = new AutoResetEvent(false))
  777. {
  778. var request = new StatVfsRequest(this.ProtocolVersion, this.NextRequestId, path, this.Encoding,
  779. (response) =>
  780. {
  781. information = response.GetReply<StatVfsReplyInfo>().Information;
  782. wait.Set();
  783. },
  784. (response) =>
  785. {
  786. exception = this.GetSftpException(response);
  787. wait.Set();
  788. });
  789. if (!this._supportedExtensions.ContainsKey(request.Name))
  790. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
  791. this.SendRequest(request);
  792. this.WaitOnHandle(wait, this._operationTimeout);
  793. }
  794. if (!nullOnError && exception != null)
  795. {
  796. throw exception;
  797. }
  798. return information;
  799. }
  800. /// <summary>
  801. /// Performs fstatvfs@openssh.com extended request.
  802. /// </summary>
  803. /// <param name="handle">The file handle.</param>
  804. /// <param name="nullOnError">if set to <c>true</c> [null on error].</param>
  805. /// <returns></returns>
  806. /// <exception cref="System.NotSupportedException"></exception>
  807. internal SftpFileSytemInformation RequestFStatVfs(byte[] handle, bool nullOnError = false)
  808. {
  809. if (this.ProtocolVersion < 3)
  810. {
  811. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", this.ProtocolVersion));
  812. }
  813. SshException exception = null;
  814. SftpFileSytemInformation information = null;
  815. using (var wait = new AutoResetEvent(false))
  816. {
  817. var request = new FStatVfsRequest(this.ProtocolVersion, this.NextRequestId, handle,
  818. (response) =>
  819. {
  820. information = response.GetReply<StatVfsReplyInfo>().Information;
  821. wait.Set();
  822. },
  823. (response) =>
  824. {
  825. exception = this.GetSftpException(response);
  826. wait.Set();
  827. });
  828. if (!this._supportedExtensions.ContainsKey(request.Name))
  829. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
  830. this.SendRequest(request);
  831. this.WaitOnHandle(wait, this._operationTimeout);
  832. }
  833. if (!nullOnError && exception != null)
  834. {
  835. throw exception;
  836. }
  837. return information;
  838. }
  839. /// <summary>
  840. /// Performs hardlink@openssh.com extended request.
  841. /// </summary>
  842. /// <param name="oldPath">The old path.</param>
  843. /// <param name="newPath">The new path.</param>
  844. internal void HardLink(string oldPath, string newPath)
  845. {
  846. if (this.ProtocolVersion < 3)
  847. {
  848. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", this.ProtocolVersion));
  849. }
  850. SshException exception = null;
  851. using (var wait = new AutoResetEvent(false))
  852. {
  853. var request = new HardLinkRequest(this.ProtocolVersion, this.NextRequestId, oldPath, newPath,
  854. (response) =>
  855. {
  856. exception = this.GetSftpException(response);
  857. wait.Set();
  858. });
  859. if (!this._supportedExtensions.ContainsKey(request.Name))
  860. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
  861. this.SendRequest(request);
  862. this.WaitOnHandle(wait, this._operationTimeout);
  863. }
  864. if (exception != null)
  865. {
  866. throw exception;
  867. }
  868. }
  869. #endregion
  870. /// <summary>
  871. /// Calculates the optimal size of the buffer to read data from the channel.
  872. /// </summary>
  873. /// <param name="bufferSize">The buffer size configured on the client.</param>
  874. /// <returns>
  875. /// The optimal size of the buffer to read data from the channel.
  876. /// </returns>
  877. internal uint CalculateOptimalReadLength(uint bufferSize)
  878. {
  879. // a SSH_FXP_DATA message has 13 bytes of protocol fields:
  880. // bytes 1 to 4: packet length
  881. // byte 5: message type
  882. // bytes 6 to 9: response id
  883. // bytes 10 to 13: length of payload‏
  884. //
  885. // most ssh servers limit the size of the payload of a SSH_MSG_CHANNEL_DATA
  886. // response to 16 KB; if we requested 16 KB of data, then the SSH_FXP_DATA
  887. // payload of the SSH_MSG_CHANNEL_DATA message would be too big (16 KB + 13 bytes), and
  888. // as a result, the ssh server would split this into two responses:
  889. // one containing 16384 bytes (13 bytes header, and 16371 bytes file data)
  890. // and one with the remaining 13 bytes of file data
  891. const uint lengthOfNonDataProtocolFields = 13u;
  892. var maximumPacketSize = Channel.LocalPacketSize;
  893. return Math.Min(bufferSize, maximumPacketSize) - lengthOfNonDataProtocolFields;
  894. }
  895. /// <summary>
  896. /// Calculates the optimal size of the buffer to write data on the channel.
  897. /// </summary>
  898. /// <param name="bufferSize">The buffer size configured on the client.</param>
  899. /// <param name="handle">The file handle.</param>
  900. /// <returns>
  901. /// The optimal size of the buffer to write data on the channel.
  902. /// </returns>
  903. /// <remarks>
  904. /// Currently, we do not take the remote window size into account.
  905. /// </remarks>
  906. internal uint CalculateOptimalWriteLength(uint bufferSize, byte[] handle)
  907. {
  908. // 1-4: package length of SSH_FXP_WRITE message
  909. // 5: message type
  910. // 6-9: request id
  911. // 10-13: handle length
  912. // <handle>
  913. // 14-21: offset
  914. // 22-25: data length
  915. var lengthOfNonDataProtocolFields = 25u + (uint)handle.Length;
  916. var maximumPacketSize = Channel.RemotePacketSize;
  917. return Math.Min(bufferSize, maximumPacketSize) - lengthOfNonDataProtocolFields;
  918. }
  919. private SshException GetSftpException(SftpStatusResponse response)
  920. {
  921. if (response.StatusCode == StatusCodes.Ok)
  922. {
  923. return null;
  924. }
  925. if (response.StatusCode == StatusCodes.PermissionDenied)
  926. {
  927. return new SftpPermissionDeniedException(response.ErrorMessage);
  928. }
  929. else if (response.StatusCode == StatusCodes.NoSuchFile)
  930. {
  931. return new SftpPathNotFoundException(response.ErrorMessage);
  932. }
  933. else
  934. {
  935. return new SshException(response.ErrorMessage);
  936. }
  937. }
  938. private void HandleResponse(SftpResponse response)
  939. {
  940. SftpRequest request;
  941. lock (this._requests)
  942. {
  943. this._requests.TryGetValue(response.ResponseId, out request);
  944. if (request != null)
  945. {
  946. this._requests.Remove(response.ResponseId);
  947. }
  948. }
  949. if (request == null)
  950. throw new InvalidOperationException("Invalid response.");
  951. request.Complete(response);
  952. }
  953. }
  954. }