SftpFileStream.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using System.Diagnostics.CodeAnalysis;
  5. using Renci.SshNet.Common;
  6. namespace Renci.SshNet.Sftp
  7. {
  8. /// <summary>
  9. /// Exposes a <see cref="Stream"/> around a remote SFTP file, supporting both synchronous and asynchronous read and write operations.
  10. /// </summary>
  11. public class SftpFileStream : Stream
  12. {
  13. // TODO: Add security method to set userid, groupid and other permission settings
  14. // Internal state.
  15. private byte[] _handle;
  16. private ISftpSession _session;
  17. // Buffer information.
  18. private readonly int _readBufferSize;
  19. private byte[] _readBuffer;
  20. private readonly int _writeBufferSize;
  21. private byte[] _writeBuffer;
  22. private int _bufferPosition;
  23. private int _bufferLen;
  24. private long _position;
  25. private bool _bufferOwnedByWrite;
  26. private bool _canRead;
  27. private bool _canSeek;
  28. private bool _canWrite;
  29. private readonly object _lock = new object();
  30. /// <summary>
  31. /// Gets a value indicating whether the current stream supports reading.
  32. /// </summary>
  33. /// <returns>
  34. /// <c>true</c> if the stream supports reading; otherwise, <c>false</c>.
  35. /// </returns>
  36. public override bool CanRead
  37. {
  38. get { return _canRead; }
  39. }
  40. /// <summary>
  41. /// Gets a value indicating whether the current stream supports seeking.
  42. /// </summary>
  43. /// <returns>
  44. /// <c>true</c> if the stream supports seeking; otherwise, <c>false</c>.
  45. /// </returns>
  46. public override bool CanSeek
  47. {
  48. get { return _canSeek; }
  49. }
  50. /// <summary>
  51. /// Gets a value indicating whether the current stream supports writing.
  52. /// </summary>
  53. /// <returns>
  54. /// <c>true</c> if the stream supports writing; otherwise, <c>false</c>.
  55. /// </returns>
  56. public override bool CanWrite
  57. {
  58. get { return _canWrite; }
  59. }
  60. /// <summary>
  61. /// Indicates whether timeout properties are usable for <see cref="SftpFileStream"/>.
  62. /// </summary>
  63. /// <value>
  64. /// <c>true</c> in all cases.
  65. /// </value>
  66. public override bool CanTimeout
  67. {
  68. get { return true; }
  69. }
  70. /// <summary>
  71. /// Gets the length in bytes of the stream.
  72. /// </summary>
  73. /// <returns>A long value representing the length of the stream in bytes.</returns>
  74. /// <exception cref="NotSupportedException">A class derived from Stream does not support seeking. </exception>
  75. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  76. /// <exception cref="IOException">IO operation failed. </exception>
  77. [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations", Justification = "Be design this is the exception that stream need to throw.")]
  78. public override long Length
  79. {
  80. get
  81. {
  82. // Lock down the file stream while we do this.
  83. lock (_lock)
  84. {
  85. CheckSessionIsOpen();
  86. if (!CanSeek)
  87. throw new NotSupportedException("Seek operation is not supported.");
  88. // Flush the write buffer, because it may
  89. // affect the length of the stream.
  90. if (_bufferOwnedByWrite)
  91. {
  92. FlushWriteBuffer();
  93. }
  94. // obtain file attributes
  95. var attributes = _session.RequestFStat(_handle, true);
  96. if (attributes != null)
  97. {
  98. return attributes.Size;
  99. }
  100. throw new IOException("Seek operation failed.");
  101. }
  102. }
  103. }
  104. /// <summary>
  105. /// Gets or sets the position within the current stream.
  106. /// </summary>
  107. /// <returns>The current position within the stream.</returns>
  108. /// <exception cref="IOException">An I/O error occurs. </exception>
  109. /// <exception cref="NotSupportedException">The stream does not support seeking. </exception>
  110. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  111. public override long Position
  112. {
  113. get
  114. {
  115. CheckSessionIsOpen();
  116. if (!CanSeek)
  117. throw new NotSupportedException("Seek operation not supported.");
  118. return _position;
  119. }
  120. set
  121. {
  122. Seek(value, SeekOrigin.Begin);
  123. }
  124. }
  125. /// <summary>
  126. /// Gets the name of the path that was used to construct the current <see cref="SftpFileStream"/>.
  127. /// </summary>
  128. /// <value>
  129. /// The name of the path that was used to construct the current <see cref="SftpFileStream"/>.
  130. /// </value>
  131. public string Name { get; private set; }
  132. /// <summary>
  133. /// Gets the operating system file handle for the file that the current <see cref="SftpFileStream"/> encapsulates.
  134. /// </summary>
  135. /// <value>
  136. /// The operating system file handle for the file that the current <see cref="SftpFileStream"/> encapsulates.
  137. /// </value>
  138. public virtual byte[] Handle
  139. {
  140. get
  141. {
  142. Flush();
  143. return _handle;
  144. }
  145. }
  146. /// <summary>
  147. /// Gets or sets the operation timeout.
  148. /// </summary>
  149. /// <value>
  150. /// The timeout.
  151. /// </value>
  152. public TimeSpan Timeout { get; set; }
  153. internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAccess access, int bufferSize)
  154. {
  155. if (session == null)
  156. throw new SshConnectionException("Client not connected.");
  157. if (path == null)
  158. throw new ArgumentNullException("path");
  159. if (bufferSize <= 0)
  160. throw new ArgumentOutOfRangeException("bufferSize");
  161. Timeout = TimeSpan.FromSeconds(30);
  162. Name = path;
  163. // Initialize the object state.
  164. _session = session;
  165. _canRead = (access & FileAccess.Read) != 0;
  166. _canSeek = true;
  167. _canWrite = (access & FileAccess.Write) != 0;
  168. var flags = Flags.None;
  169. switch (access)
  170. {
  171. case FileAccess.Read:
  172. flags |= Flags.Read;
  173. break;
  174. case FileAccess.Write:
  175. flags |= Flags.Write;
  176. break;
  177. case FileAccess.ReadWrite:
  178. flags |= Flags.Read;
  179. flags |= Flags.Write;
  180. break;
  181. default:
  182. throw new ArgumentOutOfRangeException("access");
  183. }
  184. if ((access & FileAccess.Read) != 0 && mode == FileMode.Append)
  185. {
  186. throw new ArgumentException(string.Format("{0} mode can be requested only when combined with write-only access.", mode.ToString("G")));
  187. }
  188. if ((access & FileAccess.Write) == 0)
  189. {
  190. if (mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate || mode == FileMode.Append)
  191. {
  192. throw new ArgumentException(string.Format("Combining {0}: {1} with {2}: {3} is invalid.",
  193. typeof(FileMode).Name,
  194. mode,
  195. typeof(FileAccess).Name,
  196. access));
  197. }
  198. }
  199. switch (mode)
  200. {
  201. case FileMode.Append:
  202. flags |= Flags.Append | Flags.CreateNewOrOpen;
  203. break;
  204. case FileMode.Create:
  205. _handle = _session.RequestOpen(path, flags | Flags.Truncate, true);
  206. if (_handle == null)
  207. {
  208. flags |= Flags.CreateNew;
  209. }
  210. else
  211. {
  212. flags |= Flags.Truncate;
  213. }
  214. break;
  215. case FileMode.CreateNew:
  216. flags |= Flags.CreateNew;
  217. break;
  218. case FileMode.Open:
  219. break;
  220. case FileMode.OpenOrCreate:
  221. flags |= Flags.CreateNewOrOpen;
  222. break;
  223. case FileMode.Truncate:
  224. flags |= Flags.Truncate;
  225. break;
  226. default:
  227. throw new ArgumentOutOfRangeException("mode");
  228. }
  229. if (_handle == null)
  230. _handle = _session.RequestOpen(path, flags);
  231. // instead of using the specified buffer size as is, we use it to calculate a buffer size
  232. // that ensures we always receive or send the max. number of bytes in a single SSH_FXP_READ
  233. // or SSH_FXP_WRITE message
  234. _readBufferSize = (int) session.CalculateOptimalReadLength((uint) bufferSize);
  235. _writeBufferSize = (int) session.CalculateOptimalWriteLength((uint) bufferSize, _handle);
  236. if (mode == FileMode.Append)
  237. {
  238. var attributes = _session.RequestFStat(_handle, false);
  239. _position = attributes.Size;
  240. }
  241. }
  242. /// <summary>
  243. /// Releases unmanaged resources and performs other cleanup operations before the
  244. /// <see cref="SftpFileStream"/> is reclaimed by garbage collection.
  245. /// </summary>
  246. ~SftpFileStream()
  247. {
  248. Dispose(false);
  249. }
  250. /// <summary>
  251. /// Clears all buffers for this stream and causes any buffered data to be written to the file.
  252. /// </summary>
  253. /// <exception cref="IOException">An I/O error occurs. </exception>
  254. /// <exception cref="ObjectDisposedException">Stream is closed.</exception>
  255. public override void Flush()
  256. {
  257. lock (_lock)
  258. {
  259. CheckSessionIsOpen();
  260. if (_bufferOwnedByWrite)
  261. {
  262. FlushWriteBuffer();
  263. }
  264. else
  265. {
  266. FlushReadBuffer();
  267. }
  268. }
  269. }
  270. /// <summary>
  271. /// Reads a sequence of bytes from the current stream and advances the position within the stream by the
  272. /// number of bytes read.
  273. /// </summary>
  274. /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param>
  275. /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param>
  276. /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
  277. /// <returns>
  278. /// The total number of bytes read into the buffer. This can be less than the number of bytes requested
  279. /// if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
  280. /// </returns>
  281. /// <exception cref="ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length.</exception>
  282. /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <c>null</c>. </exception>
  283. /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> or <paramref name="count"/> is negative.</exception>
  284. /// <exception cref="IOException">An I/O error occurs. </exception>
  285. /// <exception cref="NotSupportedException">The stream does not support reading. </exception>
  286. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  287. /// <remarks>
  288. /// <para>
  289. /// This method attempts to read up to <paramref name="count"/> bytes. This either from the buffer, from the
  290. /// server (using one or more <c>SSH_FXP_READ</c> requests) or using a combination of both.
  291. /// </para>
  292. /// <para>
  293. /// The read loop is interrupted when either <paramref name="count"/> bytes are read, the server returns zero
  294. /// bytes (EOF) or less bytes than the read buffer size.
  295. /// </para>
  296. /// <para>
  297. /// When a server returns less number of bytes than the read buffer size, this <c>may</c> indicate that EOF has
  298. /// been reached. A subsequent (<c>SSH_FXP_READ</c>) server request is necessary to make sure EOF has effectively
  299. /// been reached. Breaking out of the read loop avoids reading from the server twice to determine EOF: once in
  300. /// the read loop, and once upon the next <see cref="Read"/> or <see cref="ReadByte"/> invocation.
  301. /// </para>
  302. /// </remarks>
  303. public override int Read(byte[] buffer, int offset, int count)
  304. {
  305. var readLen = 0;
  306. if (buffer == null)
  307. throw new ArgumentNullException("buffer");
  308. if (offset < 0)
  309. throw new ArgumentOutOfRangeException("offset");
  310. if (count < 0)
  311. throw new ArgumentOutOfRangeException("count");
  312. if ((buffer.Length - offset) < count)
  313. throw new ArgumentException("Invalid array range.");
  314. // Lock down the file stream while we do this.
  315. lock (_lock)
  316. {
  317. CheckSessionIsOpen();
  318. // Set up for the read operation.
  319. SetupRead();
  320. // Read data into the caller's buffer.
  321. while (count > 0)
  322. {
  323. // How much data do we have available in the buffer?
  324. var bytesAvailableInBuffer = _bufferLen - _bufferPosition;
  325. if (bytesAvailableInBuffer <= 0)
  326. {
  327. var data = _session.RequestRead(_handle, (ulong) _position, (uint) _readBufferSize);
  328. if (data.Length == 0)
  329. {
  330. _bufferPosition = 0;
  331. _bufferLen = 0;
  332. break;
  333. }
  334. var bytesToWriteToCallerBuffer = count;
  335. if (bytesToWriteToCallerBuffer >= data.Length)
  336. {
  337. // write all data read to caller-provided buffer
  338. bytesToWriteToCallerBuffer = data.Length;
  339. // reset buffer since we will skip buffering
  340. _bufferPosition = 0;
  341. _bufferLen = 0;
  342. }
  343. else
  344. {
  345. // determine number of bytes that we should write into read buffer
  346. var bytesToWriteToReadBuffer = data.Length - bytesToWriteToCallerBuffer;
  347. // write remaining bytes to read buffer
  348. Buffer.BlockCopy(data, count, GetOrCreateReadBuffer(), 0, bytesToWriteToReadBuffer);
  349. // update position in read buffer
  350. _bufferPosition = 0;
  351. // update number of bytes in read buffer
  352. _bufferLen = bytesToWriteToReadBuffer;
  353. }
  354. // write bytes to caller-provided buffer
  355. Buffer.BlockCopy(data, 0, buffer, offset, bytesToWriteToCallerBuffer);
  356. // update stream position
  357. _position += bytesToWriteToCallerBuffer;
  358. // record total number of bytes read into caller-provided buffer
  359. readLen += bytesToWriteToCallerBuffer;
  360. // break out of the read loop when the server returned less than the request number of bytes
  361. // as that *may* indicate that we've reached EOF
  362. //
  363. // doing this avoids reading from server twice to determine EOF: once in the read loop, and
  364. // once upon the next Read or ReadByte invocation by the caller
  365. if (data.Length < _readBufferSize)
  366. {
  367. break;
  368. }
  369. // advance offset to start writing bytes into caller-provided buffer
  370. offset += bytesToWriteToCallerBuffer;
  371. // update number of bytes left to read into caller-provided buffer
  372. count -= bytesToWriteToCallerBuffer;
  373. }
  374. else
  375. {
  376. // limit the number of bytes to use from read buffer to the caller-request number of bytes
  377. if (bytesAvailableInBuffer > count)
  378. bytesAvailableInBuffer = count;
  379. // copy data from read buffer to the caller-provided buffer
  380. Buffer.BlockCopy(GetOrCreateReadBuffer(), _bufferPosition, buffer, offset, bytesAvailableInBuffer);
  381. // update position in read buffer
  382. _bufferPosition += bytesAvailableInBuffer;
  383. // update stream position
  384. _position += bytesAvailableInBuffer;
  385. // record total number of bytes read into caller-provided buffer
  386. readLen += bytesAvailableInBuffer;
  387. // advance offset to start writing bytes into caller-provided buffer
  388. offset += bytesAvailableInBuffer;
  389. // update number of bytes left to read
  390. count -= bytesAvailableInBuffer;
  391. }
  392. }
  393. }
  394. // return the number of bytes that were read to the caller.
  395. return readLen;
  396. }
  397. /// <summary>
  398. /// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
  399. /// </summary>
  400. /// <returns>
  401. /// The unsigned byte cast to an <see cref="int"/>, or -1 if at the end of the stream.
  402. /// </returns>
  403. /// <exception cref="NotSupportedException">The stream does not support reading. </exception>
  404. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  405. /// <exception cref="IOException">Read operation failed.</exception>
  406. public override int ReadByte()
  407. {
  408. // Lock down the file stream while we do this.
  409. lock (_lock)
  410. {
  411. CheckSessionIsOpen();
  412. // Setup the object for reading.
  413. SetupRead();
  414. byte[] readBuffer;
  415. // Read more data into the internal buffer if necessary.
  416. if (_bufferPosition >= _bufferLen)
  417. {
  418. var data = _session.RequestRead(_handle, (ulong) _position, (uint) _readBufferSize);
  419. if (data.Length == 0)
  420. {
  421. // We've reached EOF.
  422. return -1;
  423. }
  424. readBuffer = GetOrCreateReadBuffer();
  425. Buffer.BlockCopy(data, 0, readBuffer, 0, data.Length);
  426. _bufferPosition = 0;
  427. _bufferLen = data.Length;
  428. }
  429. else
  430. {
  431. readBuffer = GetOrCreateReadBuffer();
  432. }
  433. // Extract the next byte from the buffer.
  434. ++_position;
  435. return readBuffer[_bufferPosition++];
  436. }
  437. }
  438. /// <summary>
  439. /// Sets the position within the current stream.
  440. /// </summary>
  441. /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param>
  442. /// <param name="origin">A value of type <see cref="SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
  443. /// <returns>
  444. /// The new position within the current stream.
  445. /// </returns>
  446. /// <exception cref="IOException">An I/O error occurs. </exception>
  447. /// <exception cref="NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception>
  448. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  449. public override long Seek(long offset, SeekOrigin origin)
  450. {
  451. long newPosn = -1;
  452. // Lock down the file stream while we do this.
  453. lock (_lock)
  454. {
  455. CheckSessionIsOpen();
  456. if (!CanSeek)
  457. throw new NotSupportedException("Seek is not supported.");
  458. // Don't do anything if the position won't be moving.
  459. if (origin == SeekOrigin.Begin && offset == _position)
  460. {
  461. return offset;
  462. }
  463. if (origin == SeekOrigin.Current && offset == 0)
  464. {
  465. return _position;
  466. }
  467. // The behaviour depends upon the read/write mode.
  468. if (_bufferOwnedByWrite)
  469. {
  470. // Flush the write buffer and then seek.
  471. FlushWriteBuffer();
  472. switch (origin)
  473. {
  474. case SeekOrigin.Begin:
  475. newPosn = offset;
  476. break;
  477. case SeekOrigin.Current:
  478. newPosn = _position + offset;
  479. break;
  480. case SeekOrigin.End:
  481. var attributes = _session.RequestFStat(_handle, false);
  482. newPosn = attributes.Size - offset;
  483. break;
  484. }
  485. if (newPosn == -1)
  486. {
  487. throw new EndOfStreamException("End of stream.");
  488. }
  489. _position = newPosn;
  490. }
  491. else
  492. {
  493. // Determine if the seek is to somewhere inside
  494. // the current read buffer bounds.
  495. if (origin == SeekOrigin.Begin)
  496. {
  497. newPosn = _position - _bufferPosition;
  498. if (offset >= newPosn && offset < (newPosn + _bufferLen))
  499. {
  500. _bufferPosition = (int)(offset - newPosn);
  501. _position = offset;
  502. return _position;
  503. }
  504. }
  505. else if (origin == SeekOrigin.Current)
  506. {
  507. newPosn = _position + offset;
  508. if (newPosn >= (_position - _bufferPosition) &&
  509. newPosn < (_position - _bufferPosition + _bufferLen))
  510. {
  511. _bufferPosition = (int) (newPosn - (_position - _bufferPosition));
  512. _position = newPosn;
  513. return _position;
  514. }
  515. }
  516. // Abandon the read buffer.
  517. _bufferPosition = 0;
  518. _bufferLen = 0;
  519. // Seek to the new position.
  520. switch (origin)
  521. {
  522. case SeekOrigin.Begin:
  523. newPosn = offset;
  524. break;
  525. case SeekOrigin.Current:
  526. newPosn = _position + offset;
  527. break;
  528. case SeekOrigin.End:
  529. var attributes = _session.RequestFStat(_handle, false);
  530. newPosn = attributes.Size - offset;
  531. break;
  532. }
  533. if (newPosn < 0)
  534. {
  535. throw new EndOfStreamException();
  536. }
  537. _position = newPosn;
  538. }
  539. return _position;
  540. }
  541. }
  542. /// <summary>
  543. /// Sets the length of the current stream.
  544. /// </summary>
  545. /// <param name="value">The desired length of the current stream in bytes.</param>
  546. /// <exception cref="IOException">An I/O error occurs.</exception>
  547. /// <exception cref="NotSupportedException">The stream does not support both writing and seeking.</exception>
  548. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
  549. /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> must be greater than zero.</exception>
  550. /// <remarks>
  551. /// <para>
  552. /// Buffers are first flushed.
  553. /// </para>
  554. /// <para>
  555. /// If the specified value is less than the current length of the stream, the stream is truncated and - if the
  556. /// current position is greater than the new length - the current position is moved to the last byte of the stream.
  557. /// </para>
  558. /// <para>
  559. /// If the given value is greater than the current length of the stream, the stream is expanded and the current
  560. /// position remains the same.
  561. /// </para>
  562. /// </remarks>
  563. public override void SetLength(long value)
  564. {
  565. if (value < 0)
  566. throw new ArgumentOutOfRangeException("value");
  567. // Lock down the file stream while we do this.
  568. lock (_lock)
  569. {
  570. CheckSessionIsOpen();
  571. if (!CanSeek)
  572. throw new NotSupportedException("Seek is not supported.");
  573. if (_bufferOwnedByWrite)
  574. {
  575. FlushWriteBuffer();
  576. }
  577. else
  578. {
  579. SetupWrite();
  580. }
  581. var attributes = _session.RequestFStat(_handle, false);
  582. attributes.Size = value;
  583. _session.RequestFSetStat(_handle, attributes);
  584. if (_position > value)
  585. {
  586. _position = value;
  587. }
  588. }
  589. }
  590. /// <summary>
  591. /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
  592. /// </summary>
  593. /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param>
  594. /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param>
  595. /// <param name="count">The number of bytes to be written to the current stream.</param>
  596. /// <exception cref="ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is greater than the buffer length.</exception>
  597. /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <c>null</c>.</exception>
  598. /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> or <paramref name="count"/> is negative.</exception>
  599. /// <exception cref="IOException">An I/O error occurs.</exception>
  600. /// <exception cref="NotSupportedException">The stream does not support writing.</exception>
  601. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
  602. public override void Write(byte[] buffer, int offset, int count)
  603. {
  604. if (buffer == null)
  605. throw new ArgumentNullException("buffer");
  606. if (offset < 0)
  607. throw new ArgumentOutOfRangeException("offset");
  608. if (count < 0)
  609. throw new ArgumentOutOfRangeException("count");
  610. if ((buffer.Length - offset) < count)
  611. throw new ArgumentException("Invalid array range.");
  612. // Lock down the file stream while we do this.
  613. lock (_lock)
  614. {
  615. CheckSessionIsOpen();
  616. // Setup this object for writing.
  617. SetupWrite();
  618. // Write data to the file stream.
  619. while (count > 0)
  620. {
  621. // Determine how many bytes we can write to the buffer.
  622. var tempLen = _writeBufferSize - _bufferPosition;
  623. if (tempLen <= 0)
  624. {
  625. // flush write buffer, and mark it empty
  626. FlushWriteBuffer();
  627. // we can now write or buffer the full buffer size
  628. tempLen = _writeBufferSize;
  629. }
  630. // limit the number of bytes to write to the actual number of bytes requested
  631. if (tempLen > count)
  632. {
  633. tempLen = count;
  634. }
  635. // Can we short-cut the internal buffer?
  636. if (_bufferPosition == 0 && tempLen == _writeBufferSize)
  637. {
  638. using (var wait = new AutoResetEvent(false))
  639. {
  640. _session.RequestWrite(_handle, (ulong) _position, buffer, offset, tempLen, wait);
  641. }
  642. }
  643. else
  644. {
  645. // No: copy the data to the write buffer first.
  646. Buffer.BlockCopy(buffer, offset, GetOrCreateWriteBuffer(), _bufferPosition, tempLen);
  647. _bufferPosition += tempLen;
  648. }
  649. // Advance the buffer and stream positions.
  650. _position += tempLen;
  651. offset += tempLen;
  652. count -= tempLen;
  653. }
  654. // If the buffer is full, then do a speculative flush now,
  655. // rather than waiting for the next call to this method.
  656. if (_bufferPosition >= _writeBufferSize)
  657. {
  658. using (var wait = new AutoResetEvent(false))
  659. {
  660. _session.RequestWrite(_handle, (ulong) (_position - _bufferPosition), GetOrCreateWriteBuffer(), 0, _bufferPosition, wait);
  661. }
  662. _bufferPosition = 0;
  663. }
  664. }
  665. }
  666. /// <summary>
  667. /// Writes a byte to the current position in the stream and advances the position within the stream by one byte.
  668. /// </summary>
  669. /// <param name="value">The byte to write to the stream.</param>
  670. /// <exception cref="IOException">An I/O error occurs. </exception>
  671. /// <exception cref="NotSupportedException">The stream does not support writing, or the stream is already closed. </exception>
  672. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  673. public override void WriteByte(byte value)
  674. {
  675. // Lock down the file stream while we do this.
  676. lock (_lock)
  677. {
  678. CheckSessionIsOpen();
  679. // Setup the object for writing.
  680. SetupWrite();
  681. var writeBuffer = GetOrCreateWriteBuffer();
  682. // Flush the current buffer if it is full.
  683. if (_bufferPosition >= _writeBufferSize)
  684. {
  685. using (var wait = new AutoResetEvent(false))
  686. {
  687. _session.RequestWrite(_handle, (ulong) (_position - _bufferPosition), writeBuffer, 0, _bufferPosition, wait);
  688. }
  689. _bufferPosition = 0;
  690. }
  691. // Write the byte into the buffer and advance the posn.
  692. writeBuffer[_bufferPosition++] = value;
  693. ++_position;
  694. }
  695. }
  696. /// <summary>
  697. /// Releases the unmanaged resources used by the <see cref="Stream"/> and optionally releases the managed resources.
  698. /// </summary>
  699. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  700. protected override void Dispose(bool disposing)
  701. {
  702. base.Dispose(disposing);
  703. if (_session != null)
  704. {
  705. if (disposing)
  706. {
  707. lock (_lock)
  708. {
  709. if (_session != null)
  710. {
  711. _canRead = false;
  712. _canSeek = false;
  713. _canWrite = false;
  714. if (_handle != null)
  715. {
  716. if (_session.IsOpen)
  717. {
  718. if (_bufferOwnedByWrite)
  719. {
  720. FlushWriteBuffer();
  721. }
  722. _session.RequestClose(_handle);
  723. }
  724. _handle = null;
  725. }
  726. _session = null;
  727. }
  728. }
  729. }
  730. }
  731. }
  732. private byte[] GetOrCreateReadBuffer()
  733. {
  734. if (_readBuffer == null)
  735. _readBuffer = new byte[_readBufferSize];
  736. return _readBuffer;
  737. }
  738. private byte[] GetOrCreateWriteBuffer()
  739. {
  740. if (_writeBuffer == null)
  741. _writeBuffer = new byte[_writeBufferSize];
  742. return _writeBuffer;
  743. }
  744. /// <summary>
  745. /// Flushes the read data from the buffer.
  746. /// </summary>
  747. private void FlushReadBuffer()
  748. {
  749. if (_canSeek)
  750. {
  751. if (_bufferPosition < _bufferLen)
  752. {
  753. _position -= _bufferPosition;
  754. }
  755. _bufferPosition = 0;
  756. _bufferLen = 0;
  757. }
  758. }
  759. /// <summary>
  760. /// Flush any buffered write data to the file.
  761. /// </summary>
  762. private void FlushWriteBuffer()
  763. {
  764. if (_bufferPosition > 0)
  765. {
  766. using (var wait = new AutoResetEvent(false))
  767. {
  768. _session.RequestWrite(_handle, (ulong) (_position - _bufferPosition), _writeBuffer, 0, _bufferPosition, wait);
  769. }
  770. _bufferPosition = 0;
  771. }
  772. }
  773. /// <summary>
  774. /// Setups the read.
  775. /// </summary>
  776. private void SetupRead()
  777. {
  778. if (!CanRead)
  779. throw new NotSupportedException("Read not supported.");
  780. if (_bufferOwnedByWrite)
  781. {
  782. FlushWriteBuffer();
  783. _bufferOwnedByWrite = false;
  784. }
  785. }
  786. /// <summary>
  787. /// Setups the write.
  788. /// </summary>
  789. private void SetupWrite()
  790. {
  791. if ((!CanWrite))
  792. throw new NotSupportedException("Write not supported.");
  793. if (!_bufferOwnedByWrite)
  794. {
  795. FlushReadBuffer();
  796. _bufferOwnedByWrite = true;
  797. }
  798. }
  799. private void CheckSessionIsOpen()
  800. {
  801. if (_session == null)
  802. throw new ObjectDisposedException(GetType().FullName);
  803. if (!_session.IsOpen)
  804. throw new ObjectDisposedException(GetType().FullName, "Cannot access a closed SFTP session.");
  805. }
  806. }
  807. }