|
3 | 3 | using System.Threading; |
4 | 4 | using System.Diagnostics.CodeAnalysis; |
5 | 5 | using Renci.SshNet.Common; |
| 6 | +#if FEATURE_TAP |
| 7 | +using System.Threading.Tasks; |
| 8 | +#endif |
6 | 9 |
|
7 | 10 | namespace Renci.SshNet.Sftp |
8 | 11 | { |
@@ -166,6 +169,28 @@ public virtual byte[] Handle |
166 | 169 | /// </value> |
167 | 170 | public TimeSpan Timeout { get; set; } |
168 | 171 |
|
| 172 | + private SftpFileStream(ISftpSession session, string path, FileAccess access, int bufferSize, byte[] handle, long position) |
| 173 | + { |
| 174 | + Timeout = TimeSpan.FromSeconds(30); |
| 175 | + Name = path; |
| 176 | + |
| 177 | + _session = session; |
| 178 | + _canRead = (access & FileAccess.Read) != 0; |
| 179 | + _canSeek = true; |
| 180 | + _canWrite = (access & FileAccess.Write) != 0; |
| 181 | + |
| 182 | + _handle = handle; |
| 183 | + |
| 184 | + // instead of using the specified buffer size as is, we use it to calculate a buffer size |
| 185 | + // that ensures we always receive or send the max. number of bytes in a single SSH_FXP_READ |
| 186 | + // or SSH_FXP_WRITE message |
| 187 | + |
| 188 | + _readBufferSize = (int)session.CalculateOptimalReadLength((uint)bufferSize); |
| 189 | + _writeBufferSize = (int)session.CalculateOptimalWriteLength((uint)bufferSize, _handle); |
| 190 | + |
| 191 | + _position = position; |
| 192 | + } |
| 193 | + |
169 | 194 | internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAccess access, int bufferSize) |
170 | 195 | { |
171 | 196 | if (session == null) |
@@ -267,6 +292,110 @@ internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAc |
267 | 292 | } |
268 | 293 | } |
269 | 294 |
|
| 295 | +#if FEATURE_TAP |
| 296 | + internal static async Task<SftpFileStream> OpenAsync(ISftpSession session, string path, FileMode mode, FileAccess access, int bufferSize, CancellationToken cancellationToken) |
| 297 | + { |
| 298 | + if (session == null) |
| 299 | + throw new SshConnectionException("Client not connected."); |
| 300 | + if (path == null) |
| 301 | + throw new ArgumentNullException("path"); |
| 302 | + if (bufferSize <= 0) |
| 303 | + throw new ArgumentOutOfRangeException("bufferSize"); |
| 304 | + |
| 305 | + var flags = Flags.None; |
| 306 | + |
| 307 | + switch (access) |
| 308 | + { |
| 309 | + case FileAccess.Read: |
| 310 | + flags |= Flags.Read; |
| 311 | + break; |
| 312 | + case FileAccess.Write: |
| 313 | + flags |= Flags.Write; |
| 314 | + break; |
| 315 | + case FileAccess.ReadWrite: |
| 316 | + flags |= Flags.Read; |
| 317 | + flags |= Flags.Write; |
| 318 | + break; |
| 319 | + default: |
| 320 | + throw new ArgumentOutOfRangeException("access"); |
| 321 | + } |
| 322 | + |
| 323 | + if ((access & FileAccess.Read) != 0 && mode == FileMode.Append) |
| 324 | + { |
| 325 | + throw new ArgumentException(string.Format("{0} mode can be requested only when combined with write-only access.", mode.ToString("G"))); |
| 326 | + } |
| 327 | + |
| 328 | + if ((access & FileAccess.Write) == 0) |
| 329 | + { |
| 330 | + if (mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate || mode == FileMode.Append) |
| 331 | + { |
| 332 | + throw new ArgumentException(string.Format("Combining {0}: {1} with {2}: {3} is invalid.", |
| 333 | + typeof(FileMode).Name, |
| 334 | + mode, |
| 335 | + typeof(FileAccess).Name, |
| 336 | + access)); |
| 337 | + } |
| 338 | + } |
| 339 | + |
| 340 | + byte[] handle = null; |
| 341 | + |
| 342 | + switch (mode) |
| 343 | + { |
| 344 | + case FileMode.Append: |
| 345 | + flags |= Flags.Append | Flags.CreateNewOrOpen; |
| 346 | + break; |
| 347 | + case FileMode.Create: |
| 348 | + try |
| 349 | + { |
| 350 | + handle = await session.OpenAsync(path, flags | Flags.Truncate, cancellationToken).ConfigureAwait(false); |
| 351 | + flags |= Flags.Truncate; |
| 352 | + } |
| 353 | + catch (TaskCanceledException)// ToDo: when (cancellationToken.IsCancellationRequested) |
| 354 | + { |
| 355 | + throw; |
| 356 | + } |
| 357 | + catch (Exception) |
| 358 | + { |
| 359 | + flags |= Flags.CreateNew; |
| 360 | + } |
| 361 | + break; |
| 362 | + case FileMode.CreateNew: |
| 363 | + flags |= Flags.CreateNew; |
| 364 | + break; |
| 365 | + case FileMode.Open: |
| 366 | + break; |
| 367 | + case FileMode.OpenOrCreate: |
| 368 | + flags |= Flags.CreateNewOrOpen; |
| 369 | + break; |
| 370 | + case FileMode.Truncate: |
| 371 | + flags |= Flags.Truncate; |
| 372 | + break; |
| 373 | + default: |
| 374 | + throw new ArgumentOutOfRangeException("mode"); |
| 375 | + } |
| 376 | + |
| 377 | + if (handle == null) |
| 378 | + handle = await session.OpenAsync(path, flags, cancellationToken).ConfigureAwait(false); |
| 379 | + |
| 380 | + long position = 0; |
| 381 | + if (mode == FileMode.Append) |
| 382 | + { |
| 383 | + try |
| 384 | + { |
| 385 | + var attributes = session.RequestFStat(handle, false); // ToDo: Async |
| 386 | + position = attributes.Size; |
| 387 | + } |
| 388 | + catch |
| 389 | + { |
| 390 | + session.RequestClose(handle); // ToDo: Async |
| 391 | + throw; |
| 392 | + } |
| 393 | + } |
| 394 | + |
| 395 | + return new SftpFileStream(session, path, access, bufferSize, handle, position); |
| 396 | + } |
| 397 | +#endif |
| 398 | + |
270 | 399 | /// <summary> |
271 | 400 | /// Releases unmanaged resources and performs other cleanup operations before the |
272 | 401 | /// <see cref="SftpFileStream"/> is reclaimed by garbage collection. |
@@ -359,7 +488,124 @@ public override int Read(byte[] buffer, int offset, int count) |
359 | 488 | var bytesAvailableInBuffer = _bufferLen - _bufferPosition; |
360 | 489 | if (bytesAvailableInBuffer <= 0) |
361 | 490 | { |
362 | | - var data = _session.RequestRead(_handle, (ulong) _position, (uint) _readBufferSize); |
| 491 | + var data = _session.RequestRead(_handle, (ulong)_position, (uint)_readBufferSize); |
| 492 | + |
| 493 | + if (data.Length == 0) |
| 494 | + { |
| 495 | + _bufferPosition = 0; |
| 496 | + _bufferLen = 0; |
| 497 | + |
| 498 | + break; |
| 499 | + } |
| 500 | + |
| 501 | + var bytesToWriteToCallerBuffer = count; |
| 502 | + if (bytesToWriteToCallerBuffer >= data.Length) |
| 503 | + { |
| 504 | + // write all data read to caller-provided buffer |
| 505 | + bytesToWriteToCallerBuffer = data.Length; |
| 506 | + // reset buffer since we will skip buffering |
| 507 | + _bufferPosition = 0; |
| 508 | + _bufferLen = 0; |
| 509 | + } |
| 510 | + else |
| 511 | + { |
| 512 | + // determine number of bytes that we should write into read buffer |
| 513 | + var bytesToWriteToReadBuffer = data.Length - bytesToWriteToCallerBuffer; |
| 514 | + // write remaining bytes to read buffer |
| 515 | + Buffer.BlockCopy(data, count, GetOrCreateReadBuffer(), 0, bytesToWriteToReadBuffer); |
| 516 | + // update position in read buffer |
| 517 | + _bufferPosition = 0; |
| 518 | + // update number of bytes in read buffer |
| 519 | + _bufferLen = bytesToWriteToReadBuffer; |
| 520 | + } |
| 521 | + |
| 522 | + // write bytes to caller-provided buffer |
| 523 | + Buffer.BlockCopy(data, 0, buffer, offset, bytesToWriteToCallerBuffer); |
| 524 | + // update stream position |
| 525 | + _position += bytesToWriteToCallerBuffer; |
| 526 | + // record total number of bytes read into caller-provided buffer |
| 527 | + readLen += bytesToWriteToCallerBuffer; |
| 528 | + |
| 529 | + // break out of the read loop when the server returned less than the request number of bytes |
| 530 | + // as that *may* indicate that we've reached EOF |
| 531 | + // |
| 532 | + // doing this avoids reading from server twice to determine EOF: once in the read loop, and |
| 533 | + // once upon the next Read or ReadByte invocation by the caller |
| 534 | + if (data.Length < _readBufferSize) |
| 535 | + { |
| 536 | + break; |
| 537 | + } |
| 538 | + |
| 539 | + // advance offset to start writing bytes into caller-provided buffer |
| 540 | + offset += bytesToWriteToCallerBuffer; |
| 541 | + // update number of bytes left to read into caller-provided buffer |
| 542 | + count -= bytesToWriteToCallerBuffer; |
| 543 | + } |
| 544 | + else |
| 545 | + { |
| 546 | + // limit the number of bytes to use from read buffer to the caller-request number of bytes |
| 547 | + if (bytesAvailableInBuffer > count) |
| 548 | + bytesAvailableInBuffer = count; |
| 549 | + |
| 550 | + // copy data from read buffer to the caller-provided buffer |
| 551 | + Buffer.BlockCopy(GetOrCreateReadBuffer(), _bufferPosition, buffer, offset, bytesAvailableInBuffer); |
| 552 | + // update position in read buffer |
| 553 | + _bufferPosition += bytesAvailableInBuffer; |
| 554 | + // update stream position |
| 555 | + _position += bytesAvailableInBuffer; |
| 556 | + // record total number of bytes read into caller-provided buffer |
| 557 | + readLen += bytesAvailableInBuffer; |
| 558 | + // advance offset to start writing bytes into caller-provided buffer |
| 559 | + offset += bytesAvailableInBuffer; |
| 560 | + // update number of bytes left to read |
| 561 | + count -= bytesAvailableInBuffer; |
| 562 | + } |
| 563 | + } |
| 564 | + } |
| 565 | + |
| 566 | + // return the number of bytes that were read to the caller. |
| 567 | + return readLen; |
| 568 | + } |
| 569 | + |
| 570 | +#if FEATURE_TAP |
| 571 | + /// <summary> |
| 572 | + /// Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the |
| 573 | + /// number of bytes read. |
| 574 | + /// </summary> |
| 575 | + /// <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> |
| 576 | + /// <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> |
| 577 | + /// <param name="count">The maximum number of bytes to be read from the current stream.</param> |
| 578 | + /// <param name="cancellationToken">The CancellationToken to observe.</param> |
| 579 | + /// <returns>A Task representing the asynchronous operation.</returns> |
| 580 | + public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| 581 | + { |
| 582 | + var readLen = 0; |
| 583 | + |
| 584 | + if (buffer == null) |
| 585 | + throw new ArgumentNullException("buffer"); |
| 586 | + if (offset < 0) |
| 587 | + throw new ArgumentOutOfRangeException("offset"); |
| 588 | + if (count < 0) |
| 589 | + throw new ArgumentOutOfRangeException("count"); |
| 590 | + if ((buffer.Length - offset) < count) |
| 591 | + throw new ArgumentException("Invalid array range."); |
| 592 | + |
| 593 | + // Lock down the file stream while we do this. |
| 594 | + //lock (_lock) Do we need to be thread safe? |
| 595 | + { |
| 596 | + CheckSessionIsOpen(); |
| 597 | + |
| 598 | + // Set up for the read operation. |
| 599 | + SetupRead(); |
| 600 | + |
| 601 | + // Read data into the caller's buffer. |
| 602 | + while (count > 0) |
| 603 | + { |
| 604 | + // How much data do we have available in the buffer? |
| 605 | + var bytesAvailableInBuffer = _bufferLen - _bufferPosition; |
| 606 | + if (bytesAvailableInBuffer <= 0) |
| 607 | + { |
| 608 | + var data = await _session.ReadAsync(_handle, (ulong)_position, (uint)_readBufferSize, cancellationToken).ConfigureAwait(false); |
363 | 609 |
|
364 | 610 | if (data.Length == 0) |
365 | 611 | { |
@@ -437,6 +683,7 @@ public override int Read(byte[] buffer, int offset, int count) |
437 | 683 | // return the number of bytes that were read to the caller. |
438 | 684 | return readLen; |
439 | 685 | } |
| 686 | +#endif |
440 | 687 |
|
441 | 688 | /// <summary> |
442 | 689 | /// 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. |
|
0 commit comments