-
-
Notifications
You must be signed in to change notification settings - Fork 978
Expand file tree
/
Copy pathSftpSession.cs
More file actions
2269 lines (1959 loc) · 98.5 KB
/
SftpSession.cs
File metadata and controls
2269 lines (1959 loc) · 98.5 KB
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.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Renci.SshNet.Common;
using Renci.SshNet.Sftp.Requests;
using Renci.SshNet.Sftp.Responses;
namespace Renci.SshNet.Sftp
{
/// <summary>
/// Represents an SFTP session.
/// </summary>
internal sealed class SftpSession : SubsystemSession, ISftpSession
{
internal const int MaximumSupportedVersion = 3;
private const int MinimumSupportedVersion = 0;
private readonly Dictionary<uint, SftpRequest> _requests = new Dictionary<uint, SftpRequest>();
private readonly ISftpResponseFactory _sftpResponseFactory;
private readonly List<byte> _data = new List<byte>(32 * 1024);
private readonly Encoding _encoding;
private EventWaitHandle _sftpVersionConfirmed = new AutoResetEvent(initialState: false);
private IDictionary<string, string> _supportedExtensions;
/// <summary>
/// Gets the remote working directory.
/// </summary>
/// <value>
/// The remote working directory.
/// </value>
public string WorkingDirectory { get; private set; }
/// <summary>
/// Gets the SFTP protocol version.
/// </summary>
/// <value>
/// The SFTP protocol version.
/// </value>
public uint ProtocolVersion { get; private set; }
private long _requestId;
/// <summary>
/// Gets the next request id for sftp session.
/// </summary>
public uint NextRequestId
{
get
{
return (uint)Interlocked.Increment(ref _requestId);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SftpSession"/> class.
/// </summary>
/// <param name="session">The SSH session.</param>
/// <param name="operationTimeout">The operation timeout.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="sftpResponseFactory">The factory to create SFTP responses.</param>
public SftpSession(ISession session, int operationTimeout, Encoding encoding, ISftpResponseFactory sftpResponseFactory)
: base(session, "sftp", operationTimeout)
{
_encoding = encoding;
_sftpResponseFactory = sftpResponseFactory;
}
/// <summary>
/// Changes the current working directory to the specified path.
/// </summary>
/// <param name="path">The new working directory.</param>
public void ChangeDirectory(string path)
{
var fullPath = GetCanonicalPath(path);
var handle = RequestOpenDir(fullPath);
RequestClose(handle);
WorkingDirectory = fullPath;
}
internal void SendMessage(SftpMessage sftpMessage)
{
var data = sftpMessage.GetBytes();
SendData(data);
}
/// <summary>
/// Resolves a given path into an absolute path on the server.
/// </summary>
/// <param name="path">The path to resolve.</param>
/// <returns>
/// The absolute path.
/// </returns>
public string GetCanonicalPath(string path)
{
var fullPath = GetFullRemotePath(path);
var canonizedPath = string.Empty;
var realPathFiles = RequestRealPath(fullPath, nullOnError: true);
if (realPathFiles != null)
{
canonizedPath = realPathFiles[0].Key;
}
if (!string.IsNullOrEmpty(canonizedPath))
{
return canonizedPath;
}
// Check for special cases
if (fullPath.EndsWith("/.", StringComparison.OrdinalIgnoreCase) ||
fullPath.EndsWith("/..", StringComparison.OrdinalIgnoreCase) ||
fullPath.Equals("/", StringComparison.OrdinalIgnoreCase) ||
#if NET || NETSTANDARD2_1_OR_GREATER
fullPath.IndexOf('/', StringComparison.OrdinalIgnoreCase) < 0)
#else
fullPath.IndexOf('/') < 0)
#endif // NET || NETSTANDARD2_1_OR_GREATER
{
return fullPath;
}
var pathParts = fullPath.Split('/');
#if NET || NETSTANDARD2_1_OR_GREATER
var partialFullPath = string.Join('/', pathParts, 0, pathParts.Length - 1);
#else
var partialFullPath = string.Join("/", pathParts, 0, pathParts.Length - 1);
#endif // NET || NETSTANDARD2_1_OR_GREATER
if (string.IsNullOrEmpty(partialFullPath))
{
partialFullPath = "/";
}
realPathFiles = RequestRealPath(partialFullPath, nullOnError: true);
if (realPathFiles != null)
{
canonizedPath = realPathFiles[0].Key;
}
if (string.IsNullOrEmpty(canonizedPath))
{
return fullPath;
}
var slash = string.Empty;
if (canonizedPath[canonizedPath.Length - 1] != '/')
{
slash = "/";
}
return string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", canonizedPath, slash, pathParts[pathParts.Length - 1]);
}
/// <summary>
/// Asynchronously resolves a given path into an absolute path on the server.
/// </summary>
/// <param name="path">The path to resolve.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>
/// A task representing the absolute path.
/// </returns>
public async Task<string> GetCanonicalPathAsync(string path, CancellationToken cancellationToken)
{
var fullPath = GetFullRemotePath(path);
var canonizedPath = string.Empty;
var realPathFiles = await RequestRealPathAsync(fullPath, nullOnError: true, cancellationToken).ConfigureAwait(false);
if (realPathFiles != null)
{
canonizedPath = realPathFiles[0].Key;
}
if (!string.IsNullOrEmpty(canonizedPath))
{
return canonizedPath;
}
// Check for special cases
if (fullPath.EndsWith("/.", StringComparison.Ordinal) ||
fullPath.EndsWith("/..", StringComparison.Ordinal) ||
fullPath.Equals("/", StringComparison.Ordinal) ||
#if NET || NETSTANDARD2_1_OR_GREATER
fullPath.IndexOf('/', StringComparison.Ordinal) < 0)
#else
fullPath.IndexOf('/') < 0)
#endif // NET || NETSTANDARD2_1_OR_GREATER
{
return fullPath;
}
var pathParts = fullPath.Split('/');
#if NET || NETSTANDARD2_1_OR_GREATER
var partialFullPath = string.Join('/', pathParts);
#else
var partialFullPath = string.Join("/", pathParts);
#endif // NET || NETSTANDARD2_1_OR_GREATER
if (string.IsNullOrEmpty(partialFullPath))
{
partialFullPath = "/";
}
realPathFiles = await RequestRealPathAsync(partialFullPath, nullOnError: true, cancellationToken).ConfigureAwait(false);
if (realPathFiles != null)
{
canonizedPath = realPathFiles[0].Key;
}
if (string.IsNullOrEmpty(canonizedPath))
{
return fullPath;
}
var slash = string.Empty;
if (canonizedPath[canonizedPath.Length - 1] != '/')
{
slash = "/";
}
return canonizedPath + slash + pathParts[pathParts.Length - 1];
}
/// <summary>
/// Creates an <see cref="ISftpFileReader"/> for reading the content of the file represented by a given <paramref name="handle"/>.
/// </summary>
/// <param name="handle">The handle of the file to read.</param>
/// <param name="sftpSession">The SFTP session.</param>
/// <param name="chunkSize">The maximum number of bytes to read with each chunk.</param>
/// <param name="maxPendingReads">The maximum number of pending reads.</param>
/// <param name="fileSize">The size of the file or <see langword="null"/> when the size could not be determined.</param>
/// <param name="offset">The offset to resume from.</param>
/// <returns>
/// An <see cref="ISftpFileReader"/> for reading the content of the file represented by the
/// specified <paramref name="handle"/>.
/// </returns>
public ISftpFileReader CreateFileReader(byte[] handle, ISftpSession sftpSession, uint chunkSize, int maxPendingReads, long? fileSize, ulong offset = 0)
{
return new SftpFileReader(handle, sftpSession, chunkSize, maxPendingReads, fileSize, offset);
}
internal string GetFullRemotePath(string path)
{
var fullPath = path;
if (!string.IsNullOrEmpty(path) && path[0] != '/' && WorkingDirectory != null)
{
if (WorkingDirectory[WorkingDirectory.Length - 1] == '/')
{
fullPath = WorkingDirectory + path;
}
else
{
fullPath = WorkingDirectory + '/' + path;
}
}
return fullPath;
}
protected override void OnChannelOpen()
{
SendMessage(new SftpInitRequest(MaximumSupportedVersion));
WaitOnHandle(_sftpVersionConfirmed, OperationTimeout);
if (ProtocolVersion is > MaximumSupportedVersion or < MinimumSupportedVersion)
{
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Server SFTP version {0} is not supported.", ProtocolVersion));
}
// Resolve current directory
WorkingDirectory = RequestRealPath(".")[0].Key;
}
protected override void OnDataReceived(byte[] data)
{
const int packetLengthByteCount = 4;
const int sftpMessageTypeByteCount = 1;
const int minimumChannelDataLength = packetLengthByteCount + sftpMessageTypeByteCount;
var offset = 0;
var count = data.Length;
// improve performance and reduce GC pressure by not buffering channel data if the received
// chunk contains the complete packet data.
//
// for this, the buffer should be empty and the chunk should contain at least the packet length
// and the type of the SFTP message
if (_data.Count == 0)
{
while (count >= minimumChannelDataLength)
{
// extract packet length
var packetDataLength = data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 |
data[offset + 3];
var packetTotalLength = packetDataLength + packetLengthByteCount;
// check if complete packet data (or more) is available
if (count >= packetTotalLength)
{
// load and process SFTP message
if (!TryLoadSftpMessage(data, offset + packetLengthByteCount, packetDataLength))
{
return;
}
// remove processed bytes from the number of bytes to process as the channel
// data we received may contain (part of) another message
count -= packetTotalLength;
// move offset beyond bytes we just processed
offset += packetTotalLength;
}
else
{
// we don't have a complete message
break;
}
}
// check if there is channel data left to process or buffer
if (count == 0)
{
return;
}
// check if we processed part of the channel data we received
if (offset > 0)
{
// add (remaining) channel data to internal data holder
var remainingChannelData = new byte[count];
Buffer.BlockCopy(data, offset, remainingChannelData, 0, count);
_data.AddRange(remainingChannelData);
}
else
{
// add (remaining) channel data to internal data holder
_data.AddRange(data);
}
// skip further processing as we'll need a new chunk to complete the message
return;
}
// add (remaining) channel data to internal data holder
_data.AddRange(data);
while (_data.Count >= minimumChannelDataLength)
{
// extract packet length
var packetDataLength = _data[0] << 24 | _data[1] << 16 | _data[2] << 8 | _data[3];
var packetTotalLength = packetDataLength + packetLengthByteCount;
// check if complete packet data is available
if (_data.Count < packetTotalLength)
{
// wait for complete message to arrive first
break;
}
// create buffer to hold packet data
var packetData = new byte[packetDataLength];
// copy packet data and bytes for length to array
_data.CopyTo(packetLengthByteCount, packetData, 0, packetDataLength);
// remove loaded data and bytes for length from _data holder
if (_data.Count == packetTotalLength)
{
// the only buffered data is the data we're processing
_data.Clear();
}
else
{
// remove only the data we're processing
_data.RemoveRange(0, packetTotalLength);
}
// load and process SFTP message
if (!TryLoadSftpMessage(packetData, 0, packetDataLength))
{
break;
}
}
}
private bool TryLoadSftpMessage(byte[] packetData, int offset, int count)
{
// Create SFTP message
var response = _sftpResponseFactory.Create(ProtocolVersion, packetData[offset], _encoding);
// Load message data into it
response.Load(packetData, offset + 1, count - 1);
try
{
if (response is SftpVersionResponse versionResponse)
{
ProtocolVersion = versionResponse.Version;
_supportedExtensions = versionResponse.Extentions;
_ = _sftpVersionConfirmed.Set();
}
else
{
HandleResponse(response as SftpResponse);
}
return true;
}
catch (Exception exp)
{
RaiseError(exp);
return false;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
var sftpVersionConfirmed = _sftpVersionConfirmed;
if (sftpVersionConfirmed != null)
{
_sftpVersionConfirmed = null;
sftpVersionConfirmed.Dispose();
}
}
}
private void SendRequest(SftpRequest request)
{
lock (_requests)
{
_requests.Add(request.RequestId, request);
}
SendMessage(request);
}
/// <summary>
/// Performs SSH_FXP_OPEN request.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="flags">The flags.</param>
/// <param name="nullOnError">If set to <see langword="true"/> returns <see langword="null"/> instead of throwing an exception.</param>
/// <returns>File handle.</returns>
public byte[] RequestOpen(string path, Flags flags, bool nullOnError = false)
{
byte[] handle = null;
SshException exception = null;
using (var wait = new AutoResetEvent(initialState: false))
{
var request = new SftpOpenRequest(ProtocolVersion,
NextRequestId,
path,
_encoding,
flags,
response =>
{
handle = response.Handle;
_ = wait.Set();
},
response =>
{
exception = GetSftpException(response);
_ = wait.Set();
});
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
if (!nullOnError && exception is not null)
{
throw exception;
}
return handle;
}
/// <summary>
/// Asynchronously performs a <c>SSH_FXP_OPEN</c> request.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="flags">The flags.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>
/// A task that represents the asynchronous <c>SSH_FXP_OPEN</c> request. The value of its
/// <see cref="Task{Task}.Result"/> contains the file handle of the specified path.
/// </returns>
public async Task<byte[]> RequestOpenAsync(string path, Flags flags, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var tcs = new TaskCompletionSource<byte[]>(TaskCreationOptions.RunContinuationsAsynchronously);
#if NET || NETSTANDARD2_1_OR_GREATER
await using (cancellationToken.Register(s => ((TaskCompletionSource<byte[]>)s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
#else
using (cancellationToken.Register(s => ((TaskCompletionSource<byte[]>)s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
#endif // NET || NETSTANDARD2_1_OR_GREATER
{
SendRequest(new SftpOpenRequest(ProtocolVersion,
NextRequestId,
path,
_encoding,
flags,
response => tcs.TrySetResult(response.Handle),
response => tcs.TrySetException(GetSftpException(response))));
return await tcs.Task.ConfigureAwait(false);
}
}
/// <summary>
/// Performs SSH_FXP_OPEN request.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="flags">The flags.</param>
/// <param name="callback">The <see cref="AsyncCallback"/> delegate that is executed when <see cref="BeginOpen(string, Flags, AsyncCallback, object)"/> completes.</param>
/// <param name="state">An object that contains any additional user-defined data.</param>
/// <returns>
/// A <see cref="SftpOpenAsyncResult"/> that represents the asynchronous call.
/// </returns>
public SftpOpenAsyncResult BeginOpen(string path, Flags flags, AsyncCallback callback, object state)
{
var asyncResult = new SftpOpenAsyncResult(callback, state);
var request = new SftpOpenRequest(ProtocolVersion,
NextRequestId,
path,
_encoding,
flags,
response =>
{
asyncResult.SetAsCompleted(response.Handle, completedSynchronously: false);
},
response =>
{
asyncResult.SetAsCompleted(GetSftpException(response), completedSynchronously: false);
});
SendRequest(request);
return asyncResult;
}
/// <summary>
/// Handles the end of an asynchronous open.
/// </summary>
/// <param name="asyncResult">An <see cref="SftpOpenAsyncResult"/> that represents an asynchronous call.</param>
/// <returns>
/// A <see cref="byte"/> array representing a file handle.
/// </returns>
/// <remarks>
/// If all available data has been read, the <see cref="EndOpen(SftpOpenAsyncResult)"/> method completes
/// immediately and returns zero bytes.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="asyncResult"/> is <see langword="null"/>.</exception>
public byte[] EndOpen(SftpOpenAsyncResult asyncResult)
{
if (asyncResult is null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
if (asyncResult.EndInvokeCalled)
{
throw new InvalidOperationException("EndOpen has already been called.");
}
if (asyncResult.IsCompleted)
{
return asyncResult.EndInvoke();
}
using (var waitHandle = asyncResult.AsyncWaitHandle)
{
WaitOnHandle(waitHandle, OperationTimeout);
return asyncResult.EndInvoke();
}
}
/// <summary>
/// Performs SSH_FXP_CLOSE request.
/// </summary>
/// <param name="handle">The handle.</param>
public void RequestClose(byte[] handle)
{
SshException exception = null;
using (var wait = new AutoResetEvent(initialState: false))
{
var request = new SftpCloseRequest(ProtocolVersion,
NextRequestId,
handle,
response =>
{
exception = GetSftpException(response);
_ = wait.Set();
});
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
if (exception is not null)
{
throw exception;
}
}
/// <summary>
/// Performs a <c>SSH_FXP_CLOSE</c> request.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>
/// A task that represents the asynchronous <c>SSH_FXP_CLOSE</c> request.
/// </returns>
public async Task RequestCloseAsync(byte[] handle, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
SendRequest(new SftpCloseRequest(ProtocolVersion,
NextRequestId,
handle,
response =>
{
if (response.StatusCode == StatusCodes.Ok)
{
_ = tcs.TrySetResult(true);
}
else
{
_ = tcs.TrySetException(GetSftpException(response));
}
}));
// Only check for cancellation after the SftpCloseRequest was sent
cancellationToken.ThrowIfCancellationRequested();
#if NET || NETSTANDARD2_1_OR_GREATER
await using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
#else
using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
#endif // NET || NETSTANDARD2_1_OR_GREATER
{
_ = await tcs.Task.ConfigureAwait(false);
}
}
/// <summary>
/// Performs SSH_FXP_CLOSE request.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="callback">The <see cref="AsyncCallback"/> delegate that is executed when <see cref="BeginClose(byte[], AsyncCallback, object)"/> completes.</param>
/// <param name="state">An object that contains any additional user-defined data.</param>
/// <returns>
/// A <see cref="SftpCloseAsyncResult"/> that represents the asynchronous call.
/// </returns>
public SftpCloseAsyncResult BeginClose(byte[] handle, AsyncCallback callback, object state)
{
var asyncResult = new SftpCloseAsyncResult(callback, state);
var request = new SftpCloseRequest(ProtocolVersion,
NextRequestId,
handle,
response =>
{
asyncResult.SetAsCompleted(GetSftpException(response), completedSynchronously: false);
});
SendRequest(request);
return asyncResult;
}
/// <summary>
/// Handles the end of an asynchronous close.
/// </summary>
/// <param name="asyncResult">An <see cref="SftpCloseAsyncResult"/> that represents an asynchronous call.</param>
/// <exception cref="ArgumentNullException"><paramref name="asyncResult"/> is <see langword="null"/>.</exception>
public void EndClose(SftpCloseAsyncResult asyncResult)
{
if (asyncResult is null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
if (asyncResult.EndInvokeCalled)
{
throw new InvalidOperationException("EndClose has already been called.");
}
if (asyncResult.IsCompleted)
{
asyncResult.EndInvoke();
}
else
{
using (var waitHandle = asyncResult.AsyncWaitHandle)
{
WaitOnHandle(waitHandle, OperationTimeout);
asyncResult.EndInvoke();
}
}
}
/// <summary>
/// Begins an asynchronous read using a SSH_FXP_READ request.
/// </summary>
/// <param name="handle">The handle to the file to read from.</param>
/// <param name="offset">The offset in the file to start reading from.</param>
/// <param name="length">The number of bytes to read.</param>
/// <param name="callback">The <see cref="AsyncCallback"/> delegate that is executed when <see cref="BeginRead(byte[], ulong, uint, AsyncCallback, object)"/> completes.</param>
/// <param name="state">An object that contains any additional user-defined data.</param>
/// <returns>
/// A <see cref="SftpReadAsyncResult"/> that represents the asynchronous call.
/// </returns>
public SftpReadAsyncResult BeginRead(byte[] handle, ulong offset, uint length, AsyncCallback callback, object state)
{
var asyncResult = new SftpReadAsyncResult(callback, state);
var request = new SftpReadRequest(ProtocolVersion,
NextRequestId,
handle,
offset,
length,
response =>
{
asyncResult.SetAsCompleted(response.Data, completedSynchronously: false);
},
response =>
{
if (response.StatusCode != StatusCodes.Eof)
{
asyncResult.SetAsCompleted(GetSftpException(response), completedSynchronously: false);
}
else
{
asyncResult.SetAsCompleted(Array.Empty<byte>(), completedSynchronously: false);
}
});
SendRequest(request);
return asyncResult;
}
/// <summary>
/// Handles the end of an asynchronous read.
/// </summary>
/// <param name="asyncResult">An <see cref="SftpReadAsyncResult"/> that represents an asynchronous call.</param>
/// <returns>
/// A <see cref="byte"/> array representing the data read.
/// </returns>
/// <remarks>
/// If all available data has been read, the <see cref="EndRead(SftpReadAsyncResult)"/> method completes
/// immediately and returns zero bytes.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="asyncResult"/> is <see langword="null"/>.</exception>
public byte[] EndRead(SftpReadAsyncResult asyncResult)
{
if (asyncResult is null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
if (asyncResult.EndInvokeCalled)
{
throw new InvalidOperationException("EndRead has already been called.");
}
if (asyncResult.IsCompleted)
{
return asyncResult.EndInvoke();
}
using (var waitHandle = asyncResult.AsyncWaitHandle)
{
WaitOnHandle(waitHandle, OperationTimeout);
return asyncResult.EndInvoke();
}
}
/// <summary>
/// Performs SSH_FXP_READ request.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="offset">The offset.</param>
/// <param name="length">The length.</param>
/// <returns>
/// The data that was read, or an empty array when the end of the file was reached.
/// </returns>
public byte[] RequestRead(byte[] handle, ulong offset, uint length)
{
SshException exception = null;
byte[] data = null;
using (var wait = new AutoResetEvent(initialState: false))
{
var request = new SftpReadRequest(ProtocolVersion,
NextRequestId,
handle,
offset,
length,
response =>
{
data = response.Data;
_ = wait.Set();
},
response =>
{
if (response.StatusCode != StatusCodes.Eof)
{
exception = GetSftpException(response);
}
else
{
data = Array.Empty<byte>();
}
_ = wait.Set();
});
SendRequest(request);
WaitOnHandle(wait, OperationTimeout);
}
if (exception is not null)
{
throw exception;
}
return data;
}
/// <summary>
/// Asynchronously performs a <c>SSH_FXP_READ</c> request.
/// </summary>
/// <param name="handle">The handle to the file to read from.</param>
/// <param name="offset">The offset in the file to start reading from.</param>
/// <param name="length">The number of bytes to read.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>
/// A task that represents the asynchronous <c>SSH_FXP_READ</c> request. The value of
/// its <see cref="Task{Task}.Result"/> contains the data read from the file, or an empty
/// array when the end of the file is reached.
/// </returns>
public async Task<byte[]> RequestReadAsync(byte[] handle, ulong offset, uint length, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var tcs = new TaskCompletionSource<byte[]>(TaskCreationOptions.RunContinuationsAsynchronously);
#if NET || NETSTANDARD2_1_OR_GREATER
await using (cancellationToken.Register(s => ((TaskCompletionSource<byte[]>)s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
#else
using (cancellationToken.Register(s => ((TaskCompletionSource<byte[]>)s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
#endif // NET || NETSTANDARD2_1_OR_GREATER
{
SendRequest(new SftpReadRequest(ProtocolVersion,
NextRequestId,
handle,
offset,
length,
response => tcs.TrySetResult(response.Data),
response =>
{
if (response.StatusCode == StatusCodes.Eof)
{
_ = tcs.TrySetResult(Array.Empty<byte>());
}
else
{
_ = tcs.TrySetException(GetSftpException(response));
}
}));
return await tcs.Task.ConfigureAwait(false);
}
}
/// <summary>
/// Performs SSH_FXP_WRITE request.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="serverOffset">The the zero-based offset (in bytes) relative to the beginning of the file that the write must start at.</param>
/// <param name="data">The buffer holding the data to write.</param>
/// <param name="offset">the zero-based offset in <paramref name="data" /> at which to begin taking bytes to write.</param>
/// <param name="length">The length (in bytes) of the data to write.</param>
/// <param name="wait">The wait event handle if needed.</param>
/// <param name="writeCompleted">The callback to invoke when the write has completed.</param>
public void RequestWrite(byte[] handle,
ulong serverOffset,
byte[] data,
int offset,
int length,
AutoResetEvent wait,
Action<SftpStatusResponse> writeCompleted = null)
{
SshException exception = null;
var request = new SftpWriteRequest(ProtocolVersion,
NextRequestId,
handle,
serverOffset,
data,
offset,
length,
response =>
{
writeCompleted?.Invoke(response);
exception = GetSftpException(response);
if (wait != null)
{
_ = wait.Set();
}
});
SendRequest(request);
if (wait is not null)
{
WaitOnHandle(wait, OperationTimeout);
}
if (exception is not null)
{
throw exception;
}
}
/// <summary>
/// Asynchronouly performs a <c>SSH_FXP_WRITE</c> request.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="serverOffset">The the zero-based offset (in bytes) relative to the beginning of the file that the write must start at.</param>
/// <param name="data">The buffer holding the data to write.</param>
/// <param name="offset">the zero-based offset in <paramref name="data" /> at which to begin taking bytes to write.</param>
/// <param name="length">The length (in bytes) of the data to write.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>
/// A task that represents the asynchronous <c>SSH_FXP_WRITE</c> request.
/// </returns>
public async Task RequestWriteAsync(byte[] handle, ulong serverOffset, byte[] data, int offset, int length, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
#if NET || NETSTANDARD2_1_OR_GREATER
await using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false).ConfigureAwait(continueOnCapturedContext: false))
#else
using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetCanceled(cancellationToken), tcs, useSynchronizationContext: false))
#endif // NET || NETSTANDARD2_1_OR_GREATER
{
SendRequest(new SftpWriteRequest(ProtocolVersion,
NextRequestId,
handle,
serverOffset,
data,
offset,
length,
response =>
{
if (response.StatusCode == StatusCodes.Ok)
{
_ = tcs.TrySetResult(true);
}
else
{
_ = tcs.TrySetException(GetSftpException(response));
}
}));
_ = await tcs.Task.ConfigureAwait(false);
}
}