SftpSession.cs 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. using System;
  2. using System.Text;
  3. using System.Threading;
  4. using Renci.SshNet.Common;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using Renci.SshNet.Sftp.Responses;
  8. using Renci.SshNet.Sftp.Requests;
  9. namespace Renci.SshNet.Sftp
  10. {
  11. internal class SftpSession : SubsystemSession, ISftpSession
  12. {
  13. private const int MaximumSupportedVersion = 3;
  14. private const int MinimumSupportedVersion = 0;
  15. private readonly Dictionary<uint, SftpRequest> _requests = new Dictionary<uint, SftpRequest>();
  16. //FIXME: obtain from SftpClient!
  17. private readonly List<byte> _data = new List<byte>(32 * 1024);
  18. private EventWaitHandle _sftpVersionConfirmed = new AutoResetEvent(false);
  19. private IDictionary<string, string> _supportedExtensions;
  20. /// <summary>
  21. /// Gets the remote working directory.
  22. /// </summary>
  23. /// <value>
  24. /// The remote working directory.
  25. /// </value>
  26. public string WorkingDirectory { get; private set; }
  27. /// <summary>
  28. /// Gets the SFTP protocol version.
  29. /// </summary>
  30. /// <value>
  31. /// The SFTP protocol version.
  32. /// </value>
  33. public uint ProtocolVersion { get; private set; }
  34. private long _requestId;
  35. /// <summary>
  36. /// Gets the next request id for sftp session.
  37. /// </summary>
  38. public uint NextRequestId
  39. {
  40. get
  41. {
  42. return (uint) Interlocked.Increment(ref _requestId);
  43. }
  44. }
  45. public SftpSession(ISession session, int operationTimeout, Encoding encoding)
  46. : base(session, "sftp", operationTimeout, encoding)
  47. {
  48. }
  49. /// <summary>
  50. /// Changes the current working directory to the specified path.
  51. /// </summary>
  52. /// <param name="path">The new working directory.</param>
  53. public void ChangeDirectory(string path)
  54. {
  55. var fullPath = GetCanonicalPath(path);
  56. var handle = RequestOpenDir(fullPath);
  57. RequestClose(handle);
  58. WorkingDirectory = fullPath;
  59. }
  60. internal void SendMessage(SftpMessage sftpMessage)
  61. {
  62. var data = sftpMessage.GetBytes();
  63. SendData(data);
  64. }
  65. /// <summary>
  66. /// Resolves a given path into an absolute path on the server.
  67. /// </summary>
  68. /// <param name="path">The path to resolve.</param>
  69. /// <returns>
  70. /// The absolute path.
  71. /// </returns>
  72. public string GetCanonicalPath(string path)
  73. {
  74. var fullPath = GetFullRemotePath(path);
  75. var canonizedPath = string.Empty;
  76. var realPathFiles = RequestRealPath(fullPath, true);
  77. if (realPathFiles != null)
  78. {
  79. canonizedPath = realPathFiles[0].Key;
  80. }
  81. if (!string.IsNullOrEmpty(canonizedPath))
  82. return canonizedPath;
  83. // Check for special cases
  84. if (fullPath.EndsWith("/.", StringComparison.OrdinalIgnoreCase) ||
  85. fullPath.EndsWith("/..", StringComparison.OrdinalIgnoreCase) ||
  86. fullPath.Equals("/", StringComparison.OrdinalIgnoreCase) ||
  87. fullPath.IndexOf('/') < 0)
  88. return fullPath;
  89. var pathParts = fullPath.Split('/');
  90. var partialFullPath = string.Join("/", pathParts, 0, pathParts.Length - 1);
  91. if (string.IsNullOrEmpty(partialFullPath))
  92. partialFullPath = "/";
  93. realPathFiles = RequestRealPath(partialFullPath, true);
  94. if (realPathFiles != null)
  95. {
  96. canonizedPath = realPathFiles[0].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. public ISftpFileReader CreateFileReader(byte[] handle, ISftpSession sftpSession, uint chunkSize, int maxPendingReads, long? fileSize)
  108. {
  109. return new SftpFileReader(handle, sftpSession, chunkSize, maxPendingReads, fileSize);
  110. }
  111. internal string GetFullRemotePath(string path)
  112. {
  113. var fullPath = path;
  114. if (!string.IsNullOrEmpty(path) && path[0] != '/' && WorkingDirectory != null)
  115. {
  116. if (WorkingDirectory[WorkingDirectory.Length - 1] == '/')
  117. {
  118. fullPath = string.Format(CultureInfo.InvariantCulture, "{0}{1}", WorkingDirectory, path);
  119. }
  120. else
  121. {
  122. fullPath = string.Format(CultureInfo.InvariantCulture, "{0}/{1}", WorkingDirectory, path);
  123. }
  124. }
  125. return fullPath;
  126. }
  127. protected override void OnChannelOpen()
  128. {
  129. SendMessage(new SftpInitRequest(MaximumSupportedVersion));
  130. WaitOnHandle(_sftpVersionConfirmed, OperationTimeout);
  131. if (ProtocolVersion > MaximumSupportedVersion || ProtocolVersion < MinimumSupportedVersion)
  132. {
  133. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Server SFTP version {0} is not supported.", ProtocolVersion));
  134. }
  135. // Resolve current directory
  136. WorkingDirectory = RequestRealPath(".")[0].Key;
  137. }
  138. protected override void OnDataReceived(byte[] data)
  139. {
  140. const int packetLengthByteCount = 4;
  141. const int sftpMessageTypeByteCount = 1;
  142. const int minimumChannelDataLength = packetLengthByteCount + sftpMessageTypeByteCount;
  143. var offset = 0;
  144. var count = data.Length;
  145. // improve performance and reduce GC pressure by not buffering channel data if the received
  146. // chunk contains the complete packet data.
  147. //
  148. // for this, the buffer should be empty and the chunk should contain at least the packet length
  149. // and the type of the SFTP message
  150. if (_data.Count == 0)
  151. {
  152. while (count >= minimumChannelDataLength)
  153. {
  154. // extract packet length
  155. var packetDataLength = data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 |
  156. data[offset + 3];
  157. var packetTotalLength = packetDataLength + packetLengthByteCount;
  158. // check if complete packet data (or more) is available
  159. if (count >= packetTotalLength)
  160. {
  161. // load and process SFTP message
  162. if (!TryLoadSftpMessage(data, offset + packetLengthByteCount, packetDataLength))
  163. {
  164. return;
  165. }
  166. // remove processed bytes from the number of bytes to process as the channel
  167. // data we received may contain (part of) another message
  168. count -= packetTotalLength;
  169. // move offset beyond bytes we just processed
  170. offset += packetTotalLength;
  171. }
  172. else
  173. {
  174. // we don't have a complete message
  175. break;
  176. }
  177. }
  178. // check if there is channel data left to process or buffer
  179. if (count == 0)
  180. {
  181. return;
  182. }
  183. // check if we processed part of the channel data we received
  184. if (offset > 0)
  185. {
  186. // add (remaining) channel data to internal data holder
  187. var remainingChannelData = new byte[count];
  188. Buffer.BlockCopy(data, offset, remainingChannelData, 0, count);
  189. _data.AddRange(remainingChannelData);
  190. }
  191. else
  192. {
  193. // add (remaining) channel data to internal data holder
  194. _data.AddRange(data);
  195. }
  196. // skip further processing as we'll need a new chunk to complete the message
  197. return;
  198. }
  199. // add (remaining) channel data to internal data holder
  200. _data.AddRange(data);
  201. while (_data.Count >= minimumChannelDataLength)
  202. {
  203. // extract packet length
  204. var packetDataLength = _data[0] << 24 | _data[1] << 16 | _data[2] << 8 | _data[3];
  205. var packetTotalLength = packetDataLength + packetLengthByteCount;
  206. // check if complete packet data is available
  207. if (_data.Count < packetTotalLength)
  208. {
  209. // wait for complete message to arrive first
  210. break;
  211. }
  212. // create buffer to hold packet data
  213. var packetData = new byte[packetDataLength];
  214. // copy packet data and bytes for length to array
  215. _data.CopyTo(packetLengthByteCount, packetData, 0, packetDataLength);
  216. // remove loaded data and bytes for length from _data holder
  217. if (_data.Count == packetTotalLength)
  218. {
  219. // the only buffered data is the data we're processing
  220. _data.Clear();
  221. }
  222. else
  223. {
  224. // remove only the data we're processing
  225. _data.RemoveRange(0, packetTotalLength);
  226. }
  227. // load and process SFTP message
  228. if (!TryLoadSftpMessage(packetData, 0, packetDataLength))
  229. {
  230. break;
  231. }
  232. }
  233. }
  234. private bool TryLoadSftpMessage(byte[] packetData, int offset, int count)
  235. {
  236. // Load SFTP Message and handle it
  237. var response = SftpMessage.Load(ProtocolVersion, packetData, offset, count, Encoding);
  238. try
  239. {
  240. var versionResponse = response as SftpVersionResponse;
  241. if (versionResponse != null)
  242. {
  243. ProtocolVersion = versionResponse.Version;
  244. _supportedExtensions = versionResponse.Extentions;
  245. _sftpVersionConfirmed.Set();
  246. }
  247. else
  248. {
  249. HandleResponse(response as SftpResponse);
  250. }
  251. return true;
  252. }
  253. catch (Exception exp)
  254. {
  255. RaiseError(exp);
  256. return false;
  257. }
  258. }
  259. protected override void Dispose(bool disposing)
  260. {
  261. base.Dispose(disposing);
  262. if (disposing)
  263. {
  264. var sftpVersionConfirmed = _sftpVersionConfirmed;
  265. if (sftpVersionConfirmed != null)
  266. {
  267. _sftpVersionConfirmed = null;
  268. sftpVersionConfirmed.Dispose();
  269. }
  270. }
  271. }
  272. private void SendRequest(SftpRequest request)
  273. {
  274. lock (_requests)
  275. {
  276. _requests.Add(request.RequestId, request);
  277. }
  278. SendMessage(request);
  279. }
  280. #region SFTP API functions
  281. /// <summary>
  282. /// Performs SSH_FXP_OPEN request
  283. /// </summary>
  284. /// <param name="path">The path.</param>
  285. /// <param name="flags">The flags.</param>
  286. /// <param name="nullOnError">if set to <c>true</c> returns <c>null</c> instead of throwing an exception.</param>
  287. /// <returns>File handle.</returns>
  288. public byte[] RequestOpen(string path, Flags flags, bool nullOnError = false)
  289. {
  290. byte[] handle = null;
  291. SshException exception = null;
  292. using (var wait = new AutoResetEvent(false))
  293. {
  294. var request = new SftpOpenRequest(ProtocolVersion, NextRequestId, path, Encoding, flags,
  295. response =>
  296. {
  297. handle = response.Handle;
  298. wait.Set();
  299. },
  300. response =>
  301. {
  302. exception = GetSftpException(response);
  303. wait.Set();
  304. });
  305. SendRequest(request);
  306. WaitOnHandle(wait, OperationTimeout);
  307. }
  308. if (!nullOnError && exception != null)
  309. {
  310. throw exception;
  311. }
  312. return handle;
  313. }
  314. /// <summary>
  315. /// Performs SSH_FXP_OPEN request
  316. /// </summary>
  317. /// <param name="path">The path.</param>
  318. /// <param name="flags">The flags.</param>
  319. /// <param name="callback">The <see cref="AsyncCallback"/> delegate that is executed when <see cref="BeginOpen(string, Flags, AsyncCallback, object)"/> completes.</param>
  320. /// <param name="state">An object that contains any additional user-defined data.</param>
  321. /// <returns>
  322. /// A <see cref="SftpOpenAsyncResult"/> that represents the asynchronous call.
  323. /// </returns>
  324. public SftpOpenAsyncResult BeginOpen(string path, Flags flags, AsyncCallback callback, object state)
  325. {
  326. var asyncResult = new SftpOpenAsyncResult(callback, state);
  327. var request = new SftpOpenRequest(ProtocolVersion, NextRequestId, path, Encoding, flags,
  328. response =>
  329. {
  330. asyncResult.SetAsCompleted(response.Handle, false);
  331. },
  332. response =>
  333. {
  334. asyncResult.SetAsCompleted(GetSftpException(response), false);
  335. });
  336. SendRequest(request);
  337. return asyncResult;
  338. }
  339. /// <summary>
  340. /// Handles the end of an asynchronous open.
  341. /// </summary>
  342. /// <param name="asyncResult">An <see cref="SftpOpenAsyncResult"/> that represents an asynchronous call.</param>
  343. /// <returns>
  344. /// A <see cref="byte"/> array representing a file handle.
  345. /// </returns>
  346. /// <remarks>
  347. /// If all available data has been read, the <see cref="EndOpen(SftpOpenAsyncResult)"/> method completes
  348. /// immediately and returns zero bytes.
  349. /// </remarks>
  350. /// <exception cref="ArgumentNullException"><paramref name="asyncResult"/> is <c>null</c>.</exception>
  351. public byte[] EndOpen(SftpOpenAsyncResult asyncResult)
  352. {
  353. if (asyncResult == null)
  354. throw new ArgumentNullException("asyncResult");
  355. if (asyncResult.EndInvokeCalled)
  356. throw new InvalidOperationException("EndOpen has already been called.");
  357. if (asyncResult.IsCompleted)
  358. return asyncResult.EndInvoke();
  359. using (var waitHandle = asyncResult.AsyncWaitHandle)
  360. {
  361. WaitOnHandle(waitHandle, OperationTimeout);
  362. return asyncResult.EndInvoke();
  363. }
  364. }
  365. /// <summary>
  366. /// Performs SSH_FXP_CLOSE request.
  367. /// </summary>
  368. /// <param name="handle">The handle.</param>
  369. public void RequestClose(byte[] handle)
  370. {
  371. SshException exception = null;
  372. using (var wait = new AutoResetEvent(false))
  373. {
  374. var request = new SftpCloseRequest(ProtocolVersion, NextRequestId, handle,
  375. response =>
  376. {
  377. exception = GetSftpException(response);
  378. wait.Set();
  379. });
  380. SendRequest(request);
  381. WaitOnHandle(wait, OperationTimeout);
  382. }
  383. if (exception != null)
  384. {
  385. throw exception;
  386. }
  387. }
  388. /// <summary>
  389. /// Performs SSH_FXP_CLOSE request.
  390. /// </summary>
  391. /// <param name="handle">The handle.</param>
  392. /// <param name="callback">The <see cref="AsyncCallback"/> delegate that is executed when <see cref="BeginClose(byte[], AsyncCallback, object)"/> completes.</param>
  393. /// <param name="state">An object that contains any additional user-defined data.</param>
  394. /// <returns>
  395. /// A <see cref="SftpCloseAsyncResult"/> that represents the asynchronous call.
  396. /// </returns>
  397. public SftpCloseAsyncResult BeginClose(byte[] handle, AsyncCallback callback, object state)
  398. {
  399. var asyncResult = new SftpCloseAsyncResult(callback, state);
  400. var request = new SftpCloseRequest(ProtocolVersion, NextRequestId, handle,
  401. response =>
  402. {
  403. asyncResult.SetAsCompleted(GetSftpException(response), false);
  404. });
  405. SendRequest(request);
  406. return asyncResult;
  407. }
  408. /// <summary>
  409. /// Handles the end of an asynchronous close.
  410. /// </summary>
  411. /// <param name="asyncResult">An <see cref="SftpCloseAsyncResult"/> that represents an asynchronous call.</param>
  412. /// <exception cref="ArgumentNullException"><paramref name="asyncResult"/> is <c>null</c>.</exception>
  413. public void EndClose(SftpCloseAsyncResult asyncResult)
  414. {
  415. if (asyncResult == null)
  416. throw new ArgumentNullException("asyncResult");
  417. if (asyncResult.EndInvokeCalled)
  418. throw new InvalidOperationException("EndClose has already been called.");
  419. if (asyncResult.IsCompleted)
  420. {
  421. asyncResult.EndInvoke();
  422. }
  423. else
  424. {
  425. using (var waitHandle = asyncResult.AsyncWaitHandle)
  426. {
  427. WaitOnHandle(waitHandle, OperationTimeout);
  428. asyncResult.EndInvoke();
  429. }
  430. }
  431. }
  432. /// <summary>
  433. /// Begins an asynchronous read using a SSH_FXP_READ request.
  434. /// </summary>
  435. /// <param name="handle">The handle to the file to read from.</param>
  436. /// <param name="offset">The offset in the file to start reading from.</param>
  437. /// <param name="length">The number of bytes to read.</param>
  438. /// <param name="callback">The <see cref="AsyncCallback"/> delegate that is executed when <see cref="BeginRead(byte[], ulong, uint, AsyncCallback, object)"/> completes.</param>
  439. /// <param name="state">An object that contains any additional user-defined data.</param>
  440. /// <returns>
  441. /// A <see cref="SftpReadAsyncResult"/> that represents the asynchronous call.
  442. /// </returns>
  443. public SftpReadAsyncResult BeginRead(byte[] handle, ulong offset, uint length, AsyncCallback callback, object state)
  444. {
  445. var asyncResult = new SftpReadAsyncResult(callback, state);
  446. var request = new SftpReadRequest(ProtocolVersion, NextRequestId, handle, offset, length,
  447. response =>
  448. {
  449. asyncResult.SetAsCompleted(response.Data, false);
  450. },
  451. response =>
  452. {
  453. if (response.StatusCode != StatusCodes.Eof)
  454. {
  455. asyncResult.SetAsCompleted(GetSftpException(response), false);
  456. }
  457. else
  458. {
  459. asyncResult.SetAsCompleted(Array<byte>.Empty, false);
  460. }
  461. });
  462. SendRequest(request);
  463. return asyncResult;
  464. }
  465. /// <summary>
  466. /// Handles the end of an asynchronous read.
  467. /// </summary>
  468. /// <param name="asyncResult">An <see cref="SftpReadAsyncResult"/> that represents an asynchronous call.</param>
  469. /// <returns>
  470. /// A <see cref="byte"/> array representing the data read.
  471. /// </returns>
  472. /// <remarks>
  473. /// If all available data has been read, the <see cref="EndRead(SftpReadAsyncResult)"/> method completes
  474. /// immediately and returns zero bytes.
  475. /// </remarks>
  476. /// <exception cref="ArgumentNullException"><paramref name="asyncResult"/> is <c>null</c>.</exception>
  477. public byte[] EndRead(SftpReadAsyncResult asyncResult)
  478. {
  479. if (asyncResult == null)
  480. throw new ArgumentNullException("asyncResult");
  481. if (asyncResult.EndInvokeCalled)
  482. throw new InvalidOperationException("EndRead has already been called.");
  483. if (asyncResult.IsCompleted)
  484. return asyncResult.EndInvoke();
  485. using (var waitHandle = asyncResult.AsyncWaitHandle)
  486. {
  487. WaitOnHandle(waitHandle, OperationTimeout);
  488. return asyncResult.EndInvoke();
  489. }
  490. }
  491. /// <summary>
  492. /// Performs SSH_FXP_READ request.
  493. /// </summary>
  494. /// <param name="handle">The handle.</param>
  495. /// <param name="offset">The offset.</param>
  496. /// <param name="length">The length.</param>
  497. /// <returns>data array; null if EOF</returns>
  498. public byte[] RequestRead(byte[] handle, ulong offset, uint length)
  499. {
  500. SshException exception = null;
  501. byte[] data = null;
  502. using (var wait = new AutoResetEvent(false))
  503. {
  504. var request = new SftpReadRequest(ProtocolVersion, NextRequestId, handle, offset, length,
  505. response =>
  506. {
  507. data = response.Data;
  508. wait.Set();
  509. },
  510. response =>
  511. {
  512. if (response.StatusCode != StatusCodes.Eof)
  513. {
  514. exception = GetSftpException(response);
  515. }
  516. else
  517. {
  518. data = Array<byte>.Empty;
  519. }
  520. wait.Set();
  521. });
  522. SendRequest(request);
  523. WaitOnHandle(wait, OperationTimeout);
  524. }
  525. if (exception != null)
  526. {
  527. throw exception;
  528. }
  529. return data;
  530. }
  531. /// <summary>
  532. /// Performs SSH_FXP_WRITE request.
  533. /// </summary>
  534. /// <param name="handle">The handle.</param>
  535. /// <param name="serverOffset">The the zero-based offset (in bytes) relative to the beginning of the file that the write must start at.</param>
  536. /// <param name="data">The buffer holding the data to write.</param>
  537. /// <param name="offset">the zero-based offset in <paramref name="data" /> at which to begin taking bytes to write.</param>
  538. /// <param name="length">The length (in bytes) of the data to write.</param>
  539. /// <param name="wait">The wait event handle if needed.</param>
  540. /// <param name="writeCompleted">The callback to invoke when the write has completed.</param>
  541. public void RequestWrite(byte[] handle,
  542. ulong serverOffset,
  543. byte[] data,
  544. int offset,
  545. int length,
  546. AutoResetEvent wait,
  547. Action<SftpStatusResponse> writeCompleted = null)
  548. {
  549. SshException exception = null;
  550. var request = new SftpWriteRequest(ProtocolVersion, NextRequestId, handle, serverOffset, data, offset,
  551. length, response =>
  552. {
  553. if (writeCompleted != null)
  554. {
  555. writeCompleted(response);
  556. }
  557. exception = GetSftpException(response);
  558. if (wait != null)
  559. wait.Set();
  560. });
  561. SendRequest(request);
  562. if (wait != null)
  563. WaitOnHandle(wait, OperationTimeout);
  564. if (exception != null)
  565. {
  566. throw exception;
  567. }
  568. }
  569. /// <summary>
  570. /// Performs SSH_FXP_LSTAT request.
  571. /// </summary>
  572. /// <param name="path">The path.</param>
  573. /// <returns>
  574. /// File attributes
  575. /// </returns>
  576. public SftpFileAttributes RequestLStat(string path)
  577. {
  578. SshException exception = null;
  579. SftpFileAttributes attributes = null;
  580. using (var wait = new AutoResetEvent(false))
  581. {
  582. var request = new SftpLStatRequest(ProtocolVersion, NextRequestId, path, Encoding,
  583. response =>
  584. {
  585. attributes = response.Attributes;
  586. wait.Set();
  587. },
  588. response =>
  589. {
  590. exception = GetSftpException(response);
  591. wait.Set();
  592. });
  593. SendRequest(request);
  594. WaitOnHandle(wait, OperationTimeout);
  595. }
  596. if (exception != null)
  597. {
  598. throw exception;
  599. }
  600. return attributes;
  601. }
  602. /// <summary>
  603. /// Performs SSH_FXP_LSTAT request.
  604. /// </summary>
  605. /// <param name="path">The path.</param>
  606. /// <param name="callback">The <see cref="AsyncCallback"/> delegate that is executed when <see cref="BeginLStat(string, AsyncCallback, object)"/> completes.</param>
  607. /// <param name="state">An object that contains any additional user-defined data.</param>
  608. /// <returns>
  609. /// A <see cref="SFtpStatAsyncResult"/> that represents the asynchronous call.
  610. /// </returns>
  611. public SFtpStatAsyncResult BeginLStat(string path, AsyncCallback callback, object state)
  612. {
  613. var asyncResult = new SFtpStatAsyncResult(callback, state);
  614. var request = new SftpLStatRequest(ProtocolVersion, NextRequestId, path, Encoding,
  615. response =>
  616. {
  617. asyncResult.SetAsCompleted(response.Attributes, false);
  618. },
  619. response =>
  620. {
  621. asyncResult.SetAsCompleted(GetSftpException(response), false);
  622. });
  623. SendRequest(request);
  624. return asyncResult;
  625. }
  626. /// <summary>
  627. /// Handles the end of an asynchronous SSH_FXP_LSTAT request.
  628. /// </summary>
  629. /// <param name="asyncResult">An <see cref="SFtpStatAsyncResult"/> that represents an asynchronous call.</param>
  630. /// <returns>
  631. /// The file attributes.
  632. /// </returns>
  633. /// <exception cref="ArgumentNullException"><paramref name="asyncResult"/> is <c>null</c>.</exception>
  634. public SftpFileAttributes EndLStat(SFtpStatAsyncResult asyncResult)
  635. {
  636. if (asyncResult == null)
  637. throw new ArgumentNullException("asyncResult");
  638. if (asyncResult.EndInvokeCalled)
  639. throw new InvalidOperationException("EndLStat has already been called.");
  640. if (asyncResult.IsCompleted)
  641. return asyncResult.EndInvoke();
  642. using (var waitHandle = asyncResult.AsyncWaitHandle)
  643. {
  644. WaitOnHandle(waitHandle, OperationTimeout);
  645. return asyncResult.EndInvoke();
  646. }
  647. }
  648. /// <summary>
  649. /// Performs SSH_FXP_FSTAT request.
  650. /// </summary>
  651. /// <param name="handle">The handle.</param>
  652. /// <param name="nullOnError">if set to <c>true</c> returns <c>null</c> instead of throwing an exception.</param>
  653. /// <returns>
  654. /// File attributes
  655. /// </returns>
  656. public SftpFileAttributes RequestFStat(byte[] handle, bool nullOnError)
  657. {
  658. SshException exception = null;
  659. SftpFileAttributes attributes = null;
  660. using (var wait = new AutoResetEvent(false))
  661. {
  662. var request = new SftpFStatRequest(ProtocolVersion, NextRequestId, handle,
  663. response =>
  664. {
  665. attributes = response.Attributes;
  666. wait.Set();
  667. },
  668. response =>
  669. {
  670. exception = GetSftpException(response);
  671. wait.Set();
  672. });
  673. SendRequest(request);
  674. WaitOnHandle(wait, OperationTimeout);
  675. }
  676. if (exception != null && !nullOnError)
  677. {
  678. throw exception;
  679. }
  680. return attributes;
  681. }
  682. /// <summary>
  683. /// Performs SSH_FXP_SETSTAT request.
  684. /// </summary>
  685. /// <param name="path">The path.</param>
  686. /// <param name="attributes">The attributes.</param>
  687. public void RequestSetStat(string path, SftpFileAttributes attributes)
  688. {
  689. SshException exception = null;
  690. using (var wait = new AutoResetEvent(false))
  691. {
  692. var request = new SftpSetStatRequest(ProtocolVersion, NextRequestId, path, Encoding, attributes,
  693. response =>
  694. {
  695. exception = GetSftpException(response);
  696. wait.Set();
  697. });
  698. SendRequest(request);
  699. WaitOnHandle(wait, OperationTimeout);
  700. }
  701. if (exception != null)
  702. {
  703. throw exception;
  704. }
  705. }
  706. /// <summary>
  707. /// Performs SSH_FXP_FSETSTAT request.
  708. /// </summary>
  709. /// <param name="handle">The handle.</param>
  710. /// <param name="attributes">The attributes.</param>
  711. public void RequestFSetStat(byte[] handle, SftpFileAttributes attributes)
  712. {
  713. SshException exception = null;
  714. using (var wait = new AutoResetEvent(false))
  715. {
  716. var request = new SftpFSetStatRequest(ProtocolVersion, NextRequestId, handle, attributes,
  717. response =>
  718. {
  719. exception = GetSftpException(response);
  720. wait.Set();
  721. });
  722. SendRequest(request);
  723. WaitOnHandle(wait, OperationTimeout);
  724. }
  725. if (exception != null)
  726. {
  727. throw exception;
  728. }
  729. }
  730. /// <summary>
  731. /// Performs SSH_FXP_OPENDIR request
  732. /// </summary>
  733. /// <param name="path">The path.</param>
  734. /// <param name="nullOnError">if set to <c>true</c> returns <c>null</c> instead of throwing an exception.</param>
  735. /// <returns>File handle.</returns>
  736. public byte[] RequestOpenDir(string path, bool nullOnError = false)
  737. {
  738. SshException exception = null;
  739. byte[] handle = null;
  740. using (var wait = new AutoResetEvent(false))
  741. {
  742. var request = new SftpOpenDirRequest(ProtocolVersion, NextRequestId, path, Encoding,
  743. response =>
  744. {
  745. handle = response.Handle;
  746. wait.Set();
  747. },
  748. response =>
  749. {
  750. exception = GetSftpException(response);
  751. wait.Set();
  752. });
  753. SendRequest(request);
  754. WaitOnHandle(wait, OperationTimeout);
  755. }
  756. if (!nullOnError && exception != null)
  757. {
  758. throw exception;
  759. }
  760. return handle;
  761. }
  762. /// <summary>
  763. /// Performs SSH_FXP_READDIR request
  764. /// </summary>
  765. /// <param name="handle">The handle.</param>
  766. /// <returns></returns>
  767. public KeyValuePair<string, SftpFileAttributes>[] RequestReadDir(byte[] handle)
  768. {
  769. SshException exception = null;
  770. KeyValuePair<string, SftpFileAttributes>[] result = null;
  771. using (var wait = new AutoResetEvent(false))
  772. {
  773. var request = new SftpReadDirRequest(ProtocolVersion, NextRequestId, handle,
  774. response =>
  775. {
  776. result = response.Files;
  777. wait.Set();
  778. },
  779. response =>
  780. {
  781. if (response.StatusCode != StatusCodes.Eof)
  782. {
  783. exception = GetSftpException(response);
  784. }
  785. wait.Set();
  786. });
  787. SendRequest(request);
  788. WaitOnHandle(wait, OperationTimeout);
  789. }
  790. if (exception != null)
  791. {
  792. throw exception;
  793. }
  794. return result;
  795. }
  796. /// <summary>
  797. /// Performs SSH_FXP_REMOVE request.
  798. /// </summary>
  799. /// <param name="path">The path.</param>
  800. public void RequestRemove(string path)
  801. {
  802. SshException exception = null;
  803. using (var wait = new AutoResetEvent(false))
  804. {
  805. var request = new SftpRemoveRequest(ProtocolVersion, NextRequestId, path, Encoding,
  806. response =>
  807. {
  808. exception = GetSftpException(response);
  809. wait.Set();
  810. });
  811. SendRequest(request);
  812. WaitOnHandle(wait, OperationTimeout);
  813. }
  814. if (exception != null)
  815. {
  816. throw exception;
  817. }
  818. }
  819. /// <summary>
  820. /// Performs SSH_FXP_MKDIR request.
  821. /// </summary>
  822. /// <param name="path">The path.</param>
  823. public void RequestMkDir(string path)
  824. {
  825. SshException exception = null;
  826. using (var wait = new AutoResetEvent(false))
  827. {
  828. var request = new SftpMkDirRequest(ProtocolVersion, NextRequestId, path, Encoding,
  829. response =>
  830. {
  831. exception = GetSftpException(response);
  832. wait.Set();
  833. });
  834. SendRequest(request);
  835. WaitOnHandle(wait, OperationTimeout);
  836. }
  837. if (exception != null)
  838. {
  839. throw exception;
  840. }
  841. }
  842. /// <summary>
  843. /// Performs SSH_FXP_RMDIR request.
  844. /// </summary>
  845. /// <param name="path">The path.</param>
  846. public void RequestRmDir(string path)
  847. {
  848. SshException exception = null;
  849. using (var wait = new AutoResetEvent(false))
  850. {
  851. var request = new SftpRmDirRequest(ProtocolVersion, NextRequestId, path, Encoding,
  852. response =>
  853. {
  854. exception = GetSftpException(response);
  855. wait.Set();
  856. });
  857. SendRequest(request);
  858. WaitOnHandle(wait, OperationTimeout);
  859. }
  860. if (exception != null)
  861. {
  862. throw exception;
  863. }
  864. }
  865. /// <summary>
  866. /// Performs SSH_FXP_REALPATH request
  867. /// </summary>
  868. /// <param name="path">The path.</param>
  869. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  870. /// <returns>
  871. /// The absolute path.
  872. /// </returns>
  873. internal KeyValuePair<string, SftpFileAttributes>[] RequestRealPath(string path, bool nullOnError = false)
  874. {
  875. SshException exception = null;
  876. KeyValuePair<string, SftpFileAttributes>[] result = null;
  877. using (var wait = new AutoResetEvent(false))
  878. {
  879. var request = new SftpRealPathRequest(ProtocolVersion, NextRequestId, path, Encoding,
  880. response =>
  881. {
  882. result = response.Files;
  883. wait.Set();
  884. },
  885. response =>
  886. {
  887. exception = GetSftpException(response);
  888. wait.Set();
  889. });
  890. SendRequest(request);
  891. WaitOnHandle(wait, OperationTimeout);
  892. }
  893. if (!nullOnError && exception != null)
  894. {
  895. throw exception;
  896. }
  897. return result;
  898. }
  899. /// <summary>
  900. /// Performs SSH_FXP_REALPATH request.
  901. /// </summary>
  902. /// <param name="path">The path.</param>
  903. /// <param name="callback">The <see cref="AsyncCallback"/> delegate that is executed when <see cref="BeginRealPath(string, AsyncCallback, object)"/> completes.</param>
  904. /// <param name="state">An object that contains any additional user-defined data.</param>
  905. /// <returns>
  906. /// A <see cref="SftpRealPathAsyncResult"/> that represents the asynchronous call.
  907. /// </returns>
  908. public SftpRealPathAsyncResult BeginRealPath(string path, AsyncCallback callback, object state)
  909. {
  910. var asyncResult = new SftpRealPathAsyncResult(callback, state);
  911. var request = new SftpRealPathRequest(ProtocolVersion, NextRequestId, path, Encoding,
  912. response =>
  913. {
  914. asyncResult.SetAsCompleted(response.Files[0].Key, false);
  915. },
  916. response =>
  917. {
  918. asyncResult.SetAsCompleted(GetSftpException(response), false);
  919. });
  920. SendRequest(request);
  921. return asyncResult;
  922. }
  923. /// <summary>
  924. /// Handles the end of an asynchronous SSH_FXP_REALPATH request.
  925. /// </summary>
  926. /// <param name="asyncResult">An <see cref="SftpRealPathAsyncResult"/> that represents an asynchronous call.</param>
  927. /// <returns>
  928. /// The absolute path.
  929. /// </returns>
  930. /// <exception cref="ArgumentNullException"><paramref name="asyncResult"/> is <c>null</c>.</exception>
  931. public string EndRealPath(SftpRealPathAsyncResult asyncResult)
  932. {
  933. if (asyncResult == null)
  934. throw new ArgumentNullException("asyncResult");
  935. if (asyncResult.EndInvokeCalled)
  936. throw new InvalidOperationException("EndRealPath has already been called.");
  937. if (asyncResult.IsCompleted)
  938. return asyncResult.EndInvoke();
  939. using (var waitHandle = asyncResult.AsyncWaitHandle)
  940. {
  941. WaitOnHandle(waitHandle, OperationTimeout);
  942. return asyncResult.EndInvoke();
  943. }
  944. }
  945. /// <summary>
  946. /// Performs SSH_FXP_STAT request.
  947. /// </summary>
  948. /// <param name="path">The path.</param>
  949. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  950. /// <returns>
  951. /// File attributes
  952. /// </returns>
  953. public SftpFileAttributes RequestStat(string path, bool nullOnError = false)
  954. {
  955. SshException exception = null;
  956. SftpFileAttributes attributes = null;
  957. using (var wait = new AutoResetEvent(false))
  958. {
  959. var request = new SftpStatRequest(ProtocolVersion, NextRequestId, path, Encoding,
  960. response =>
  961. {
  962. attributes = response.Attributes;
  963. wait.Set();
  964. },
  965. response =>
  966. {
  967. exception = GetSftpException(response);
  968. wait.Set();
  969. });
  970. SendRequest(request);
  971. WaitOnHandle(wait, OperationTimeout);
  972. }
  973. if (!nullOnError && exception != null)
  974. {
  975. throw exception;
  976. }
  977. return attributes;
  978. }
  979. /// <summary>
  980. /// Performs SSH_FXP_STAT request
  981. /// </summary>
  982. /// <param name="path">The path.</param>
  983. /// <param name="callback">The <see cref="AsyncCallback"/> delegate that is executed when <see cref="BeginStat(string, AsyncCallback, object)"/> completes.</param>
  984. /// <param name="state">An object that contains any additional user-defined data.</param>
  985. /// <returns>
  986. /// A <see cref="SFtpStatAsyncResult"/> that represents the asynchronous call.
  987. /// </returns>
  988. public SFtpStatAsyncResult BeginStat(string path, AsyncCallback callback, object state)
  989. {
  990. var asyncResult = new SFtpStatAsyncResult(callback, state);
  991. var request = new SftpStatRequest(ProtocolVersion, NextRequestId, path, Encoding,
  992. response =>
  993. {
  994. asyncResult.SetAsCompleted(response.Attributes, false);
  995. },
  996. response =>
  997. {
  998. asyncResult.SetAsCompleted(GetSftpException(response), false);
  999. });
  1000. SendRequest(request);
  1001. return asyncResult;
  1002. }
  1003. /// <summary>
  1004. /// Handles the end of an asynchronous stat.
  1005. /// </summary>
  1006. /// <param name="asyncResult">An <see cref="SFtpStatAsyncResult"/> that represents an asynchronous call.</param>
  1007. /// <returns>
  1008. /// The file attributes.
  1009. /// </returns>
  1010. /// <exception cref="ArgumentNullException"><paramref name="asyncResult"/> is <c>null</c>.</exception>
  1011. public SftpFileAttributes EndStat(SFtpStatAsyncResult asyncResult)
  1012. {
  1013. if (asyncResult == null)
  1014. throw new ArgumentNullException("asyncResult");
  1015. if (asyncResult.EndInvokeCalled)
  1016. throw new InvalidOperationException("EndStat has already been called.");
  1017. if (asyncResult.IsCompleted)
  1018. return asyncResult.EndInvoke();
  1019. using (var waitHandle = asyncResult.AsyncWaitHandle)
  1020. {
  1021. WaitOnHandle(waitHandle, OperationTimeout);
  1022. return asyncResult.EndInvoke();
  1023. }
  1024. }
  1025. /// <summary>
  1026. /// Performs SSH_FXP_RENAME request.
  1027. /// </summary>
  1028. /// <param name="oldPath">The old path.</param>
  1029. /// <param name="newPath">The new path.</param>
  1030. public void RequestRename(string oldPath, string newPath)
  1031. {
  1032. if (ProtocolVersion < 2)
  1033. {
  1034. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_RENAME operation is not supported in {0} version that server operates in.", ProtocolVersion));
  1035. }
  1036. SshException exception = null;
  1037. using (var wait = new AutoResetEvent(false))
  1038. {
  1039. var request = new SftpRenameRequest(ProtocolVersion, NextRequestId, oldPath, newPath, Encoding,
  1040. response =>
  1041. {
  1042. exception = GetSftpException(response);
  1043. wait.Set();
  1044. });
  1045. SendRequest(request);
  1046. WaitOnHandle(wait, OperationTimeout);
  1047. }
  1048. if (exception != null)
  1049. {
  1050. throw exception;
  1051. }
  1052. }
  1053. /// <summary>
  1054. /// Performs SSH_FXP_READLINK request.
  1055. /// </summary>
  1056. /// <param name="path">The path.</param>
  1057. /// <param name="nullOnError">if set to <c>true</c> returns null instead of throwing an exception.</param>
  1058. /// <returns></returns>
  1059. internal KeyValuePair<string, SftpFileAttributes>[] RequestReadLink(string path, bool nullOnError = false)
  1060. {
  1061. if (ProtocolVersion < 3)
  1062. {
  1063. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_READLINK operation is not supported in {0} version that server operates in.", ProtocolVersion));
  1064. }
  1065. SshException exception = null;
  1066. KeyValuePair<string, SftpFileAttributes>[] result = null;
  1067. using (var wait = new AutoResetEvent(false))
  1068. {
  1069. var request = new SftpReadLinkRequest(ProtocolVersion, NextRequestId, path, Encoding,
  1070. response =>
  1071. {
  1072. result = response.Files;
  1073. wait.Set();
  1074. },
  1075. response =>
  1076. {
  1077. exception = GetSftpException(response);
  1078. wait.Set();
  1079. });
  1080. SendRequest(request);
  1081. WaitOnHandle(wait, OperationTimeout);
  1082. }
  1083. if (!nullOnError && exception != null)
  1084. {
  1085. throw exception;
  1086. }
  1087. return result;
  1088. }
  1089. /// <summary>
  1090. /// Performs SSH_FXP_SYMLINK request.
  1091. /// </summary>
  1092. /// <param name="linkpath">The linkpath.</param>
  1093. /// <param name="targetpath">The targetpath.</param>
  1094. public void RequestSymLink(string linkpath, string targetpath)
  1095. {
  1096. if (ProtocolVersion < 3)
  1097. {
  1098. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_SYMLINK operation is not supported in {0} version that server operates in.", ProtocolVersion));
  1099. }
  1100. SshException exception = null;
  1101. using (var wait = new AutoResetEvent(false))
  1102. {
  1103. var request = new SftpSymLinkRequest(ProtocolVersion, NextRequestId, linkpath, targetpath, Encoding,
  1104. response =>
  1105. {
  1106. exception = GetSftpException(response);
  1107. wait.Set();
  1108. });
  1109. SendRequest(request);
  1110. WaitOnHandle(wait, OperationTimeout);
  1111. }
  1112. if (exception != null)
  1113. {
  1114. throw exception;
  1115. }
  1116. }
  1117. #endregion
  1118. #region SFTP Extended API functions
  1119. /// <summary>
  1120. /// Performs posix-rename@openssh.com extended request.
  1121. /// </summary>
  1122. /// <param name="oldPath">The old path.</param>
  1123. /// <param name="newPath">The new path.</param>
  1124. public void RequestPosixRename(string oldPath, string newPath)
  1125. {
  1126. if (ProtocolVersion < 3)
  1127. {
  1128. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", ProtocolVersion));
  1129. }
  1130. SshException exception = null;
  1131. using (var wait = new AutoResetEvent(false))
  1132. {
  1133. var request = new PosixRenameRequest(ProtocolVersion, NextRequestId, oldPath, newPath, Encoding,
  1134. response =>
  1135. {
  1136. exception = GetSftpException(response);
  1137. wait.Set();
  1138. });
  1139. if (!_supportedExtensions.ContainsKey(request.Name))
  1140. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
  1141. SendRequest(request);
  1142. WaitOnHandle(wait, OperationTimeout);
  1143. }
  1144. if (exception != null)
  1145. {
  1146. throw exception;
  1147. }
  1148. }
  1149. /// <summary>
  1150. /// Performs statvfs@openssh.com extended request.
  1151. /// </summary>
  1152. /// <param name="path">The path.</param>
  1153. /// <param name="nullOnError">if set to <c>true</c> [null on error].</param>
  1154. /// <returns></returns>
  1155. public SftpFileSytemInformation RequestStatVfs(string path, bool nullOnError = false)
  1156. {
  1157. if (ProtocolVersion < 3)
  1158. {
  1159. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", ProtocolVersion));
  1160. }
  1161. SshException exception = null;
  1162. SftpFileSytemInformation information = null;
  1163. using (var wait = new AutoResetEvent(false))
  1164. {
  1165. var request = new StatVfsRequest(ProtocolVersion, NextRequestId, path, Encoding,
  1166. response =>
  1167. {
  1168. information = response.GetReply<StatVfsReplyInfo>().Information;
  1169. wait.Set();
  1170. },
  1171. response =>
  1172. {
  1173. exception = GetSftpException(response);
  1174. wait.Set();
  1175. });
  1176. if (!_supportedExtensions.ContainsKey(request.Name))
  1177. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
  1178. SendRequest(request);
  1179. WaitOnHandle(wait, OperationTimeout);
  1180. }
  1181. if (!nullOnError && exception != null)
  1182. {
  1183. throw exception;
  1184. }
  1185. return information;
  1186. }
  1187. /// <summary>
  1188. /// Performs fstatvfs@openssh.com extended request.
  1189. /// </summary>
  1190. /// <param name="handle">The file handle.</param>
  1191. /// <param name="nullOnError">if set to <c>true</c> [null on error].</param>
  1192. /// <returns></returns>
  1193. /// <exception cref="NotSupportedException"></exception>
  1194. internal SftpFileSytemInformation RequestFStatVfs(byte[] handle, bool nullOnError = false)
  1195. {
  1196. if (ProtocolVersion < 3)
  1197. {
  1198. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", ProtocolVersion));
  1199. }
  1200. SshException exception = null;
  1201. SftpFileSytemInformation information = null;
  1202. using (var wait = new AutoResetEvent(false))
  1203. {
  1204. var request = new FStatVfsRequest(ProtocolVersion, NextRequestId, handle,
  1205. response =>
  1206. {
  1207. information = response.GetReply<StatVfsReplyInfo>().Information;
  1208. wait.Set();
  1209. },
  1210. response =>
  1211. {
  1212. exception = GetSftpException(response);
  1213. wait.Set();
  1214. });
  1215. if (!_supportedExtensions.ContainsKey(request.Name))
  1216. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
  1217. SendRequest(request);
  1218. WaitOnHandle(wait, OperationTimeout);
  1219. }
  1220. if (!nullOnError && exception != null)
  1221. {
  1222. throw exception;
  1223. }
  1224. return information;
  1225. }
  1226. /// <summary>
  1227. /// Performs hardlink@openssh.com extended request.
  1228. /// </summary>
  1229. /// <param name="oldPath">The old path.</param>
  1230. /// <param name="newPath">The new path.</param>
  1231. internal void HardLink(string oldPath, string newPath)
  1232. {
  1233. if (ProtocolVersion < 3)
  1234. {
  1235. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "SSH_FXP_EXTENDED operation is not supported in {0} version that server operates in.", ProtocolVersion));
  1236. }
  1237. SshException exception = null;
  1238. using (var wait = new AutoResetEvent(false))
  1239. {
  1240. var request = new HardLinkRequest(ProtocolVersion, NextRequestId, oldPath, newPath,
  1241. response =>
  1242. {
  1243. exception = GetSftpException(response);
  1244. wait.Set();
  1245. });
  1246. if (!_supportedExtensions.ContainsKey(request.Name))
  1247. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Extension method {0} currently not supported by the server.", request.Name));
  1248. SendRequest(request);
  1249. WaitOnHandle(wait, OperationTimeout);
  1250. }
  1251. if (exception != null)
  1252. {
  1253. throw exception;
  1254. }
  1255. }
  1256. #endregion
  1257. /// <summary>
  1258. /// Calculates the optimal size of the buffer to read data from the channel.
  1259. /// </summary>
  1260. /// <param name="bufferSize">The buffer size configured on the client.</param>
  1261. /// <returns>
  1262. /// The optimal size of the buffer to read data from the channel.
  1263. /// </returns>
  1264. public uint CalculateOptimalReadLength(uint bufferSize)
  1265. {
  1266. // a SSH_FXP_DATA message has 13 bytes of protocol fields:
  1267. // bytes 1 to 4: packet length
  1268. // byte 5: message type
  1269. // bytes 6 to 9: response id
  1270. // bytes 10 to 13: length of payload‏
  1271. //
  1272. // most ssh servers limit the size of the payload of a SSH_MSG_CHANNEL_DATA
  1273. // response to 16 KB; if we requested 16 KB of data, then the SSH_FXP_DATA
  1274. // payload of the SSH_MSG_CHANNEL_DATA message would be too big (16 KB + 13 bytes), and
  1275. // as a result, the ssh server would split this into two responses:
  1276. // one containing 16384 bytes (13 bytes header, and 16371 bytes file data)
  1277. // and one with the remaining 13 bytes of file data
  1278. const uint lengthOfNonDataProtocolFields = 13u;
  1279. var maximumPacketSize = Channel.LocalPacketSize;
  1280. return Math.Min(bufferSize, maximumPacketSize) - lengthOfNonDataProtocolFields;
  1281. }
  1282. /// <summary>
  1283. /// Calculates the optimal size of the buffer to write data on the channel.
  1284. /// </summary>
  1285. /// <param name="bufferSize">The buffer size configured on the client.</param>
  1286. /// <param name="handle">The file handle.</param>
  1287. /// <returns>
  1288. /// The optimal size of the buffer to write data on the channel.
  1289. /// </returns>
  1290. /// <remarks>
  1291. /// Currently, we do not take the remote window size into account.
  1292. /// </remarks>
  1293. public uint CalculateOptimalWriteLength(uint bufferSize, byte[] handle)
  1294. {
  1295. // 1-4: package length of SSH_FXP_WRITE message
  1296. // 5: message type
  1297. // 6-9: request id
  1298. // 10-13: handle length
  1299. // <handle>
  1300. // 14-21: offset
  1301. // 22-25: data length
  1302. var lengthOfNonDataProtocolFields = 25u + (uint)handle.Length;
  1303. var maximumPacketSize = Channel.RemotePacketSize;
  1304. return Math.Min(bufferSize, maximumPacketSize) - lengthOfNonDataProtocolFields;
  1305. }
  1306. private static SshException GetSftpException(SftpStatusResponse response)
  1307. {
  1308. switch (response.StatusCode)
  1309. {
  1310. case StatusCodes.Ok:
  1311. return null;
  1312. case StatusCodes.PermissionDenied:
  1313. return new SftpPermissionDeniedException(response.ErrorMessage);
  1314. case StatusCodes.NoSuchFile:
  1315. return new SftpPathNotFoundException(response.ErrorMessage);
  1316. default:
  1317. return new SshException(response.ErrorMessage);
  1318. }
  1319. }
  1320. private void HandleResponse(SftpResponse response)
  1321. {
  1322. SftpRequest request;
  1323. lock (_requests)
  1324. {
  1325. _requests.TryGetValue(response.ResponseId, out request);
  1326. if (request != null)
  1327. {
  1328. _requests.Remove(response.ResponseId);
  1329. }
  1330. }
  1331. if (request == null)
  1332. throw new InvalidOperationException("Invalid response.");
  1333. request.Complete(response);
  1334. }
  1335. }
  1336. }