-
-
Notifications
You must be signed in to change notification settings - Fork 932
/
SftpFileStream.cs
1382 lines (1197 loc) · 54.5 KB
/
SftpFileStream.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Renci.SshNet.Common;
namespace Renci.SshNet.Sftp
{
/// <summary>
/// Exposes a <see cref="Stream"/> around a remote SFTP file, supporting both synchronous and asynchronous read and write operations.
/// </summary>
/// <threadsafety static="true" instance="false"/>
#pragma warning disable IDE0079 // We intentionally want to suppress the below warning.
[SuppressMessage("Performance", "CA1844: Provide memory-based overrides of async methods when subclassing 'Stream'", Justification = "TODO: This should be addressed in the future.")]
#pragma warning restore IDE0079
public class SftpFileStream : Stream
{
private readonly object _lock = new object();
private readonly int _readBufferSize;
private readonly int _writeBufferSize;
// Internal state.
private byte[] _handle;
private ISftpSession _session;
// Buffer information.
private byte[] _readBuffer;
private byte[] _writeBuffer;
private int _bufferPosition;
private int _bufferLen;
private long _position;
private bool _bufferOwnedByWrite;
private bool _canRead;
private bool _canSeek;
private bool _canWrite;
private TimeSpan _timeout;
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
/// <value>
/// <see langword="true"/> if the stream supports reading; otherwise, <see langword="false"/>.
/// </value>
public override bool CanRead
{
get { return _canRead; }
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
/// <value>
/// <see langword="true"/> if the stream supports seeking; otherwise, <see langword="false"/>.
/// </value>
public override bool CanSeek
{
get { return _canSeek; }
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
/// <value>
/// <see langword="true"/> if the stream supports writing; otherwise, <see langword="false"/>.
/// </value>
public override bool CanWrite
{
get { return _canWrite; }
}
/// <summary>
/// Gets a value indicating whether timeout properties are usable for <see cref="SftpFileStream"/>.
/// </summary>
/// <value>
/// <see langword="true"/> in all cases.
/// </value>
public override bool CanTimeout
{
get { return true; }
}
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
/// <value>A long value representing the length of the stream in bytes.</value>
/// <exception cref="NotSupportedException">A class derived from Stream does not support seeking. </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
/// <exception cref="IOException">IO operation failed. </exception>
public override long Length
{
get
{
// Lock down the file stream while we do this.
lock (_lock)
{
CheckSessionIsOpen();
if (!CanSeek)
{
throw new NotSupportedException("Seek operation is not supported.");
}
// Flush the write buffer, because it may
// affect the length of the stream.
if (_bufferOwnedByWrite)
{
FlushWriteBuffer();
}
// obtain file attributes
var attributes = _session.RequestFStat(_handle, nullOnError: true);
if (attributes != null)
{
return attributes.Size;
}
throw new IOException("Seek operation failed.");
}
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// </summary>
/// <value>The current position within the stream.</value>
/// <exception cref="IOException">An I/O error occurs. </exception>
/// <exception cref="NotSupportedException">The stream does not support seeking. </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
public override long Position
{
get
{
CheckSessionIsOpen();
if (!CanSeek)
{
throw new NotSupportedException("Seek operation not supported.");
}
return _position;
}
set
{
_ = Seek(value, SeekOrigin.Begin);
}
}
/// <summary>
/// Gets the name of the path that was used to construct the current <see cref="SftpFileStream"/>.
/// </summary>
/// <value>
/// The name of the path that was used to construct the current <see cref="SftpFileStream"/>.
/// </value>
public string Name { get; private set; }
/// <summary>
/// Gets the operating system file handle for the file that the current <see cref="SftpFileStream"/> encapsulates.
/// </summary>
/// <value>
/// The operating system file handle for the file that the current <see cref="SftpFileStream"/> encapsulates.
/// </value>
public virtual byte[] Handle
{
get
{
Flush();
return _handle;
}
}
/// <summary>
/// Gets or sets the operation timeout.
/// </summary>
/// <value>
/// The timeout.
/// </value>
public TimeSpan Timeout
{
get
{
return _timeout;
}
set
{
value.EnsureValidTimeout(nameof(Timeout));
_timeout = value;
}
}
private SftpFileStream(ISftpSession session, string path, FileAccess access, int bufferSize, byte[] handle, long position)
{
Timeout = TimeSpan.FromSeconds(30);
Name = path;
_session = session;
_canRead = (access & FileAccess.Read) == FileAccess.Read;
_canSeek = true;
_canWrite = (access & FileAccess.Write) == FileAccess.Write;
_handle = handle;
/*
* Instead of using the specified buffer size as is, we use it to calculate a buffer size
* that ensures we always receive or send the max. number of bytes in a single SSH_FXP_READ
* or SSH_FXP_WRITE message.
*/
_readBufferSize = (int)session.CalculateOptimalReadLength((uint)bufferSize);
_writeBufferSize = (int)session.CalculateOptimalWriteLength((uint)bufferSize, _handle);
_position = position;
}
internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAccess access, int bufferSize)
{
if (session is null)
{
throw new SshConnectionException("Client not connected.");
}
if (path is null)
{
throw new ArgumentNullException(nameof(path));
}
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), "Cannot be less than or equal to zero.");
}
Timeout = TimeSpan.FromSeconds(30);
Name = path;
// Initialize the object state.
_session = session;
_canRead = (access & FileAccess.Read) == FileAccess.Read;
_canSeek = true;
_canWrite = (access & FileAccess.Write) == FileAccess.Write;
var flags = Flags.None;
switch (access)
{
case FileAccess.Read:
flags |= Flags.Read;
break;
case FileAccess.Write:
flags |= Flags.Write;
break;
case FileAccess.ReadWrite:
flags |= Flags.Read;
flags |= Flags.Write;
break;
default:
throw new ArgumentOutOfRangeException(nameof(access));
}
if ((access & FileAccess.Read) == FileAccess.Read && mode == FileMode.Append)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"{0} mode can be requested only when combined with write-only access.",
mode.ToString("G")),
nameof(mode));
}
if ((access & FileAccess.Write) != FileAccess.Write)
{
if (mode is FileMode.Create or FileMode.CreateNew or FileMode.Truncate or FileMode.Append)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"Combining {0}: {1} with {2}: {3} is invalid.",
nameof(FileMode),
mode,
nameof(FileAccess),
access),
nameof(mode));
}
}
switch (mode)
{
case FileMode.Append:
flags |= Flags.Append | Flags.CreateNewOrOpen;
break;
case FileMode.Create:
_handle = _session.RequestOpen(path, flags | Flags.Truncate, nullOnError: true);
if (_handle is null)
{
flags |= Flags.CreateNew;
}
else
{
flags |= Flags.Truncate;
}
break;
case FileMode.CreateNew:
flags |= Flags.CreateNew;
break;
case FileMode.Open:
break;
case FileMode.OpenOrCreate:
flags |= Flags.CreateNewOrOpen;
break;
case FileMode.Truncate:
flags |= Flags.Truncate;
break;
default:
throw new ArgumentOutOfRangeException(nameof(mode));
}
_handle ??= _session.RequestOpen(path, flags);
/*
* Instead of using the specified buffer size as is, we use it to calculate a buffer size
* that ensures we always receive or send the max. number of bytes in a single SSH_FXP_READ
* or SSH_FXP_WRITE message.
*/
_readBufferSize = (int)session.CalculateOptimalReadLength((uint)bufferSize);
_writeBufferSize = (int)session.CalculateOptimalWriteLength((uint)bufferSize, _handle);
if (mode == FileMode.Append)
{
var attributes = _session.RequestFStat(_handle, nullOnError: false);
_position = attributes.Size;
}
}
internal static async Task<SftpFileStream> OpenAsync(ISftpSession session, string path, FileMode mode, FileAccess access, int bufferSize, CancellationToken cancellationToken)
{
if (session is null)
{
throw new SshConnectionException("Client not connected.");
}
if (path is null)
{
throw new ArgumentNullException(nameof(path));
}
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), "Cannot be less than or equal to zero.");
}
var flags = Flags.None;
switch (access)
{
case FileAccess.Read:
flags |= Flags.Read;
break;
case FileAccess.Write:
flags |= Flags.Write;
break;
case FileAccess.ReadWrite:
flags |= Flags.Read;
flags |= Flags.Write;
break;
default:
throw new ArgumentOutOfRangeException(nameof(access));
}
if ((access & FileAccess.Read) == FileAccess.Read && mode == FileMode.Append)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"{0} mode can be requested only when combined with write-only access.",
mode.ToString("G")),
nameof(mode));
}
if ((access & FileAccess.Write) != FileAccess.Write)
{
if (mode is FileMode.Create or FileMode.CreateNew or FileMode.Truncate or FileMode.Append)
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
"Combining {0}: {1} with {2}: {3} is invalid.",
nameof(FileMode),
mode,
nameof(FileAccess),
access),
nameof(mode));
}
}
switch (mode)
{
case FileMode.Append:
flags |= Flags.Append | Flags.CreateNewOrOpen;
break;
case FileMode.Create:
flags |= Flags.CreateNewOrOpen | Flags.Truncate;
break;
case FileMode.CreateNew:
flags |= Flags.CreateNew;
break;
case FileMode.Open:
break;
case FileMode.OpenOrCreate:
flags |= Flags.CreateNewOrOpen;
break;
case FileMode.Truncate:
flags |= Flags.Truncate;
break;
default:
throw new ArgumentOutOfRangeException(nameof(mode));
}
var handle = await session.RequestOpenAsync(path, flags, cancellationToken).ConfigureAwait(false);
long position = 0;
if (mode == FileMode.Append)
{
try
{
var attributes = await session.RequestFStatAsync(handle, cancellationToken).ConfigureAwait(false);
position = attributes.Size;
}
catch
{
try
{
await session.RequestCloseAsync(handle, cancellationToken).ConfigureAwait(false);
}
catch
{
// The original exception is presumably more informative, so we just ignore this one.
}
throw;
}
}
return new SftpFileStream(session, path, access, bufferSize, handle, position);
}
/// <summary>
/// Finalizes an instance of the <see cref="SftpFileStream"/> class.
/// </summary>
~SftpFileStream()
{
Dispose(disposing: false);
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written to the file.
/// </summary>
/// <exception cref="IOException">An I/O error occurs. </exception>
/// <exception cref="ObjectDisposedException">Stream is closed.</exception>
public override void Flush()
{
lock (_lock)
{
CheckSessionIsOpen();
if (_bufferOwnedByWrite)
{
FlushWriteBuffer();
}
else
{
FlushReadBuffer();
}
}
}
/// <summary>
/// Asynchronously clears all buffers for this stream and causes any buffered data to be written to the file.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous flush operation.</returns>
/// <exception cref="IOException">An I/O error occurs. </exception>
/// <exception cref="ObjectDisposedException">Stream is closed.</exception>
public override Task FlushAsync(CancellationToken cancellationToken)
{
CheckSessionIsOpen();
if (_bufferOwnedByWrite)
{
return FlushWriteBufferAsync(cancellationToken);
}
FlushReadBuffer();
return Task.CompletedTask;
}
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position within the stream by the
/// number of bytes read.
/// </summary>
/// <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>
/// <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>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the number of bytes requested
/// if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
/// </returns>
/// <exception cref="ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length.</exception>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>. </exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> or <paramref name="count"/> is negative.</exception>
/// <exception cref="IOException">An I/O error occurs. </exception>
/// <exception cref="NotSupportedException">The stream does not support reading. </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
/// <remarks>
/// <para>
/// This method attempts to read up to <paramref name="count"/> bytes. This either from the buffer, from the
/// server (using one or more <c>SSH_FXP_READ</c> requests) or using a combination of both.
/// </para>
/// <para>
/// The read loop is interrupted when either <paramref name="count"/> bytes are read, the server returns zero
/// bytes (EOF) or less bytes than the read buffer size.
/// </para>
/// <para>
/// When a server returns less number of bytes than the read buffer size, this <c>may</c> indicate that EOF has
/// been reached. A subsequent (<c>SSH_FXP_READ</c>) server request is necessary to make sure EOF has effectively
/// been reached. Breaking out of the read loop avoids reading from the server twice to determine EOF: once in
/// the read loop, and once upon the next <see cref="Read"/> or <see cref="ReadByte"/> invocation.
/// </para>
/// </remarks>
public override int Read(byte[] buffer, int offset, int count)
{
var readLen = 0;
if (buffer is null)
{
throw new ArgumentNullException(nameof(buffer));
}
#if NET8_0_OR_GREATER
ArgumentOutOfRangeException.ThrowIfNegative(offset);
ArgumentOutOfRangeException.ThrowIfNegative(count);
#else
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
#endif
if ((buffer.Length - offset) < count)
{
throw new ArgumentException("Invalid array range.");
}
// Lock down the file stream while we do this.
lock (_lock)
{
CheckSessionIsOpen();
// Set up for the read operation.
SetupRead();
// Read data into the caller's buffer.
while (count > 0)
{
// How much data do we have available in the buffer?
var bytesAvailableInBuffer = _bufferLen - _bufferPosition;
if (bytesAvailableInBuffer <= 0)
{
var data = _session.RequestRead(_handle, (ulong)_position, (uint)_readBufferSize);
if (data.Length == 0)
{
_bufferPosition = 0;
_bufferLen = 0;
break;
}
var bytesToWriteToCallerBuffer = count;
if (bytesToWriteToCallerBuffer >= data.Length)
{
// write all data read to caller-provided buffer
bytesToWriteToCallerBuffer = data.Length;
// reset buffer since we will skip buffering
_bufferPosition = 0;
_bufferLen = 0;
}
else
{
// determine number of bytes that we should write into read buffer
var bytesToWriteToReadBuffer = data.Length - bytesToWriteToCallerBuffer;
// write remaining bytes to read buffer
Buffer.BlockCopy(data, count, GetOrCreateReadBuffer(), 0, bytesToWriteToReadBuffer);
// update position in read buffer
_bufferPosition = 0;
// update number of bytes in read buffer
_bufferLen = bytesToWriteToReadBuffer;
}
// write bytes to caller-provided buffer
Buffer.BlockCopy(data, 0, buffer, offset, bytesToWriteToCallerBuffer);
// update stream position
_position += bytesToWriteToCallerBuffer;
// record total number of bytes read into caller-provided buffer
readLen += bytesToWriteToCallerBuffer;
// break out of the read loop when the server returned less than the request number of bytes
// as that *may* indicate that we've reached EOF
//
// doing this avoids reading from server twice to determine EOF: once in the read loop, and
// once upon the next Read or ReadByte invocation by the caller
if (data.Length < _readBufferSize)
{
break;
}
// advance offset to start writing bytes into caller-provided buffer
offset += bytesToWriteToCallerBuffer;
// update number of bytes left to read into caller-provided buffer
count -= bytesToWriteToCallerBuffer;
}
else
{
// limit the number of bytes to use from read buffer to the caller-request number of bytes
if (bytesAvailableInBuffer > count)
{
bytesAvailableInBuffer = count;
}
// copy data from read buffer to the caller-provided buffer
Buffer.BlockCopy(GetOrCreateReadBuffer(), _bufferPosition, buffer, offset, bytesAvailableInBuffer);
// update position in read buffer
_bufferPosition += bytesAvailableInBuffer;
// update stream position
_position += bytesAvailableInBuffer;
// record total number of bytes read into caller-provided buffer
readLen += bytesAvailableInBuffer;
// advance offset to start writing bytes into caller-provided buffer
offset += bytesAvailableInBuffer;
// update number of bytes left to read
count -= bytesAvailableInBuffer;
}
}
}
// return the number of bytes that were read to the caller.
return readLen;
}
/// <summary>
/// Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the
/// number of bytes read.
/// </summary>
/// <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>
/// <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>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken" /> to observe.</param>
/// <returns>A <see cref="Task" /> that represents the asynchronous read operation.</returns>
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var readLen = 0;
if (buffer is null)
{
throw new ArgumentNullException(nameof(buffer));
}
#if NET8_0_OR_GREATER
ArgumentOutOfRangeException.ThrowIfNegative(offset);
ArgumentOutOfRangeException.ThrowIfNegative(count);
#else
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
#endif
if ((buffer.Length - offset) < count)
{
throw new ArgumentException("Invalid array range.");
}
CheckSessionIsOpen();
// Set up for the read operation.
SetupRead();
// Read data into the caller's buffer.
while (count > 0)
{
// How much data do we have available in the buffer?
var bytesAvailableInBuffer = _bufferLen - _bufferPosition;
if (bytesAvailableInBuffer <= 0)
{
var data = await _session.RequestReadAsync(_handle, (ulong)_position, (uint)_readBufferSize, cancellationToken).ConfigureAwait(false);
if (data.Length == 0)
{
_bufferPosition = 0;
_bufferLen = 0;
break;
}
var bytesToWriteToCallerBuffer = count;
if (bytesToWriteToCallerBuffer >= data.Length)
{
// write all data read to caller-provided buffer
bytesToWriteToCallerBuffer = data.Length;
// reset buffer since we will skip buffering
_bufferPosition = 0;
_bufferLen = 0;
}
else
{
// determine number of bytes that we should write into read buffer
var bytesToWriteToReadBuffer = data.Length - bytesToWriteToCallerBuffer;
// write remaining bytes to read buffer
Buffer.BlockCopy(data, count, GetOrCreateReadBuffer(), 0, bytesToWriteToReadBuffer);
// update position in read buffer
_bufferPosition = 0;
// update number of bytes in read buffer
_bufferLen = bytesToWriteToReadBuffer;
}
// write bytes to caller-provided buffer
Buffer.BlockCopy(data, 0, buffer, offset, bytesToWriteToCallerBuffer);
// update stream position
_position += bytesToWriteToCallerBuffer;
// record total number of bytes read into caller-provided buffer
readLen += bytesToWriteToCallerBuffer;
// break out of the read loop when the server returned less than the request number of bytes
// as that *may* indicate that we've reached EOF
//
// doing this avoids reading from server twice to determine EOF: once in the read loop, and
// once upon the next Read or ReadByte invocation by the caller
if (data.Length < _readBufferSize)
{
break;
}
// advance offset to start writing bytes into caller-provided buffer
offset += bytesToWriteToCallerBuffer;
// update number of bytes left to read into caller-provided buffer
count -= bytesToWriteToCallerBuffer;
}
else
{
// limit the number of bytes to use from read buffer to the caller-request number of bytes
if (bytesAvailableInBuffer > count)
{
bytesAvailableInBuffer = count;
}
// copy data from read buffer to the caller-provided buffer
Buffer.BlockCopy(GetOrCreateReadBuffer(), _bufferPosition, buffer, offset, bytesAvailableInBuffer);
// update position in read buffer
_bufferPosition += bytesAvailableInBuffer;
// update stream position
_position += bytesAvailableInBuffer;
// record total number of bytes read into caller-provided buffer
readLen += bytesAvailableInBuffer;
// advance offset to start writing bytes into caller-provided buffer
offset += bytesAvailableInBuffer;
// update number of bytes left to read
count -= bytesAvailableInBuffer;
}
}
// return the number of bytes that were read to the caller.
return readLen;
}
/// <summary>
/// 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.
/// </summary>
/// <returns>
/// The unsigned byte cast to an <see cref="int"/>, or -1 if at the end of the stream.
/// </returns>
/// <exception cref="NotSupportedException">The stream does not support reading. </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
/// <exception cref="IOException">Read operation failed.</exception>
public override int ReadByte()
{
// Lock down the file stream while we do this.
lock (_lock)
{
CheckSessionIsOpen();
// Setup the object for reading.
SetupRead();
byte[] readBuffer;
// Read more data into the internal buffer if necessary.
if (_bufferPosition >= _bufferLen)
{
var data = _session.RequestRead(_handle, (ulong)_position, (uint)_readBufferSize);
if (data.Length == 0)
{
// We've reached EOF.
return -1;
}
readBuffer = GetOrCreateReadBuffer();
Buffer.BlockCopy(data, 0, readBuffer, 0, data.Length);
_bufferPosition = 0;
_bufferLen = data.Length;
}
else
{
readBuffer = GetOrCreateReadBuffer();
}
// Extract the next byte from the buffer.
++_position;
return readBuffer[_bufferPosition++];
}
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param>
/// <param name="origin">A value of type <see cref="SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
/// <returns>
/// The new position within the current stream.
/// </returns>
/// <exception cref="IOException">An I/O error occurs. </exception>
/// <exception cref="NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
public override long Seek(long offset, SeekOrigin origin)
{
long newPosn;
// Lock down the file stream while we do this.
lock (_lock)
{
CheckSessionIsOpen();
if (!CanSeek)
{
throw new NotSupportedException("Seek is not supported.");
}
// Don't do anything if the position won't be moving.
if (origin == SeekOrigin.Begin && offset == _position)
{
return offset;
}
if (origin == SeekOrigin.Current && offset == 0)
{
return _position;
}
// The behaviour depends upon the read/write mode.
if (_bufferOwnedByWrite)
{
// Flush the write buffer and then seek.
FlushWriteBuffer();
}
else
{
// Determine if the seek is to somewhere inside
// the current read buffer bounds.
if (origin == SeekOrigin.Begin)
{
newPosn = _position - _bufferPosition;
if (offset >= newPosn && offset < (newPosn + _bufferLen))
{
_bufferPosition = (int)(offset - newPosn);
_position = offset;
return _position;
}
}
else if (origin == SeekOrigin.Current)
{
newPosn = _position + offset;
if (newPosn >= (_position - _bufferPosition) &&
newPosn < (_position - _bufferPosition + _bufferLen))
{
_bufferPosition = (int)(newPosn - (_position - _bufferPosition));
_position = newPosn;
return _position;
}
}
// Abandon the read buffer.
_bufferPosition = 0;
_bufferLen = 0;
}
// Seek to the new position.
switch (origin)
{
case SeekOrigin.Begin:
newPosn = offset;
break;
case SeekOrigin.Current:
newPosn = _position + offset;
break;
case SeekOrigin.End:
var attributes = _session.RequestFStat(_handle, nullOnError: false);
newPosn = attributes.Size + offset;
break;
default:
throw new ArgumentException("Invalid seek origin.", nameof(origin));
}
if (newPosn < 0)
{
throw new EndOfStreamException();
}
_position = newPosn;
return _position;
}
}
/// <summary>
/// Sets the length of the current stream.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.</param>
/// <exception cref="IOException">An I/O error occurs.</exception>
/// <exception cref="NotSupportedException">The stream does not support both writing and seeking.</exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> must be greater than zero.</exception>
/// <remarks>
/// <para>
/// Buffers are first flushed.
/// </para>
/// <para>
/// If the specified value is less than the current length of the stream, the stream is truncated and - if the
/// current position is greater than the new length - the current position is moved to the last byte of the stream.
/// </para>
/// <para>
/// If the given value is greater than the current length of the stream, the stream is expanded and the current
/// position remains the same.
/// </para>
/// </remarks>
public override void SetLength(long value)
{
#if NET8_0_OR_GREATER
ArgumentOutOfRangeException.ThrowIfNegative(value);
#else
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
#endif
// Lock down the file stream while we do this.
lock (_lock)
{
CheckSessionIsOpen();
if (!CanSeek)
{
throw new NotSupportedException("Seek is not supported.");
}
if (_bufferOwnedByWrite)
{
FlushWriteBuffer();
}
else
{
SetupWrite();