SftpSession.cs 41 KB

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