-
-
Notifications
You must be signed in to change notification settings - Fork 946
/
Copy pathSocketAbstraction.cs
721 lines (639 loc) · 27 KB
/
SocketAbstraction.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
using System;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Renci.SshNet.Common;
using Renci.SshNet.Messages.Transport;
namespace Renci.SshNet.Abstractions
{
internal static class SocketAbstraction
{
public static bool CanRead(Socket socket)
{
if (socket.Connected)
{
#if FEATURE_SOCKET_POLL
return socket.Poll(-1, SelectMode.SelectRead) && socket.Available > 0;
#else
return true;
#endif // FEATURE_SOCKET_POLL
}
return false;
}
/// <summary>
/// Returns a value indicating whether the specified <see cref="Socket"/> can be used
/// to send data.
/// </summary>
/// <param name="socket">The <see cref="Socket"/> to check.</param>
/// <returns>
/// <c>true</c> if <paramref name="socket"/> can be written to; otherwise, <c>false</c>.
/// </returns>
public static bool CanWrite(Socket socket)
{
if (socket != null && socket.Connected)
{
#if FEATURE_SOCKET_POLL
return socket.Poll(-1, SelectMode.SelectWrite);
#else
return true;
#endif // FEATURE_SOCKET_POLL
}
return false;
}
public static Socket Connect(IPEndPoint remoteEndpoint, TimeSpan connectTimeout)
{
var socket = new Socket(remoteEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
ConnectCore(socket, remoteEndpoint, connectTimeout, true);
return socket;
}
#if FEATURE_UNIX_SOCKETS
public static Socket Connect(UnixDomainSocketEndPoint remoteEndpoint, TimeSpan connectTimeout)
{
var socket = new Socket(remoteEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Unspecified);
ConnectCore(socket, remoteEndpoint, connectTimeout, true);
return socket;
}
#endif
public static void Connect(Socket socket, IPEndPoint remoteEndpoint, TimeSpan connectTimeout)
{
ConnectCore(socket, remoteEndpoint, connectTimeout, false);
}
private static void ConnectCore(Socket socket, EndPoint remoteEndpoint, TimeSpan connectTimeout, bool ownsSocket)
{
#if FEATURE_SOCKET_EAP
var connectCompleted = new ManualResetEvent(false);
var args = new SocketAsyncEventArgs
{
UserToken = connectCompleted,
RemoteEndPoint = remoteEndpoint
};
args.Completed += ConnectCompleted;
if (socket.ConnectAsync(args))
{
if (!connectCompleted.WaitOne(connectTimeout))
{
// avoid ObjectDisposedException in ConnectCompleted
args.Completed -= ConnectCompleted;
if (ownsSocket)
{
// dispose Socket
socket.Dispose();
}
// dispose ManualResetEvent
connectCompleted.Dispose();
// dispose SocketAsyncEventArgs
args.Dispose();
throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
"Connection failed to establish within {0:F0} milliseconds.",
connectTimeout.TotalMilliseconds));
}
}
// dispose ManualResetEvent
connectCompleted.Dispose();
if (args.SocketError != SocketError.Success)
{
var socketError = (int) args.SocketError;
if (ownsSocket)
{
// dispose Socket
socket.Dispose();
}
// dispose SocketAsyncEventArgs
args.Dispose();
throw new SocketException(socketError);
}
// dispose SocketAsyncEventArgs
args.Dispose();
#elif FEATURE_SOCKET_APM
var connectResult = socket.BeginConnect(remoteEndpoint, null, null);
if (!connectResult.AsyncWaitHandle.WaitOne(connectTimeout, false))
throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
"Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds));
socket.EndConnect(connectResult);
#elif FEATURE_SOCKET_TAP
if (!socket.ConnectAsync(remoteEndpoint).Wait(connectTimeout))
throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
"Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds));
#else
#error Connecting to a remote endpoint is not implemented.
#endif
}
public static void ClearReadBuffer(Socket socket)
{
var timeout = TimeSpan.FromMilliseconds(500);
var buffer = new byte[256];
int bytesReceived;
do
{
bytesReceived = ReadPartial(socket, buffer, 0, buffer.Length, timeout);
}
while (bytesReceived > 0);
}
public static int ReadPartial(Socket socket, byte[] buffer, int offset, int size, TimeSpan timeout)
{
#if FEATURE_SOCKET_SYNC
socket.ReceiveTimeout = (int) timeout.TotalMilliseconds;
try
{
return socket.Receive(buffer, offset, size, SocketFlags.None);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.TimedOut)
throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
"Socket read operation has timed out after {0:F0} milliseconds.", timeout.TotalMilliseconds));
throw;
}
#elif FEATURE_SOCKET_EAP
var receiveCompleted = new ManualResetEvent(false);
var sendReceiveToken = new PartialSendReceiveToken(socket, receiveCompleted);
var args = new SocketAsyncEventArgs
{
RemoteEndPoint = socket.RemoteEndPoint,
UserToken = sendReceiveToken
};
args.Completed += ReceiveCompleted;
args.SetBuffer(buffer, offset, size);
try
{
if (socket.ReceiveAsync(args))
{
if (!receiveCompleted.WaitOne(timeout))
throw new SshOperationTimeoutException(
string.Format(
CultureInfo.InvariantCulture,
"Socket read operation has timed out after {0:F0} milliseconds.",
timeout.TotalMilliseconds));
}
else
{
sendReceiveToken.Process(args);
}
if (args.SocketError != SocketError.Success)
throw new SocketException((int) args.SocketError);
return args.BytesTransferred;
}
finally
{
// initialize token to avoid the waithandle getting used after it's disposed
args.UserToken = null;
args.Dispose();
receiveCompleted.Dispose();
}
#else
#error Receiving data from a Socket is not implemented.
#endif
}
public static void ReadContinuous(Socket socket, byte[] buffer, int offset, int size, Action<byte[], int, int> processReceivedBytesAction)
{
#if FEATURE_SOCKET_SYNC
// do not time-out receive
socket.ReceiveTimeout = 0;
while (socket.Connected)
{
try
{
var bytesRead = socket.Receive(buffer, offset, size, SocketFlags.None);
if (bytesRead == 0)
break;
processReceivedBytesAction(buffer, offset, bytesRead);
}
catch (SocketException ex)
{
if (IsErrorResumable(ex.SocketErrorCode))
continue;
switch (ex.SocketErrorCode)
{
case SocketError.ConnectionAborted:
case SocketError.ConnectionReset:
// connection was closed
return;
case SocketError.Interrupted:
// connection was closed because FIN/ACK was not received in time after
// shutting down the (send part of the) socket
return;
default:
throw; // throw any other error
}
}
}
#elif FEATURE_SOCKET_EAP
var completionWaitHandle = new ManualResetEvent(false);
var readToken = new ContinuousReceiveToken(socket, processReceivedBytesAction, completionWaitHandle);
var args = new SocketAsyncEventArgs
{
RemoteEndPoint = socket.RemoteEndPoint,
UserToken = readToken
};
args.Completed += ReceiveCompleted;
args.SetBuffer(buffer, offset, size);
if (!socket.ReceiveAsync(args))
{
ReceiveCompleted(null, args);
}
completionWaitHandle.WaitOne();
completionWaitHandle.Dispose();
if (readToken.Exception != null)
throw readToken.Exception;
#else
#error Receiving data from a Socket is not implemented.
#endif
}
/// <summary>
/// Reads a byte from the specified <see cref="Socket"/>.
/// </summary>
/// <param name="socket">The <see cref="Socket"/> to read from.</param>
/// <param name="timeout">Specifies the amount of time after which the call will time out.</param>
/// <returns>
/// The byte read, or <c>-1</c> if the socket was closed.
/// </returns>
/// <exception cref="SshOperationTimeoutException">The read operation timed out.</exception>
/// <exception cref="SocketException">The read failed.</exception>
public static int ReadByte(Socket socket, TimeSpan timeout)
{
var buffer = new byte[1];
if (Read(socket, buffer, 0, 1, timeout) == 0)
return -1;
return buffer[0];
}
/// <summary>
/// Sends a byte using the specified <see cref="Socket"/>.
/// </summary>
/// <param name="socket">The <see cref="Socket"/> to write to.</param>
/// <param name="value">The value to send.</param>
/// <exception cref="SocketException">The write failed.</exception>
public static void SendByte(Socket socket, byte value)
{
var buffer = new[] {value};
Send(socket, buffer, 0, 1);
}
/// <summary>
/// Receives data from a bound <see cref="Socket"/>.
/// </summary>
/// <param name="socket"></param>
/// <param name="size">The number of bytes to receive.</param>
/// <param name="timeout">Specifies the amount of time after which the call will time out.</param>
/// <returns>
/// The bytes received.
/// </returns>
/// <remarks>
/// If no data is available for reading, the <see cref="Read(Socket, int, TimeSpan)"/> method will
/// block until data is available or the time-out value is exceeded. If the time-out value is exceeded, the
/// <see cref="Read(Socket, int, TimeSpan)"/> call will throw a <see cref="SshOperationTimeoutException"/>.
/// If you are in non-blocking mode, and there is no data available in the in the protocol stack buffer, the
/// <see cref="Read(Socket, int, TimeSpan)"/> method will complete immediately and throw a <see cref="SocketException"/>.
/// </remarks>
public static byte[] Read(Socket socket, int size, TimeSpan timeout)
{
var buffer = new byte[size];
Read(socket, buffer, 0, size, timeout);
return buffer;
}
/// <summary>
/// Receives data from a bound <see cref="Socket"/> into a receive buffer.
/// </summary>
/// <param name="socket"></param>
/// <param name="buffer">An array of type <see cref="byte"/> that is the storage location for the received data. </param>
/// <param name="offset">The position in <paramref name="buffer"/> parameter to store the received data.</param>
/// <param name="size">The number of bytes to receive.</param>
/// <param name="readTimeout">The maximum time to wait until <paramref name="size"/> bytes have been received.</param>
/// <returns>
/// The number of bytes received.
/// </returns>
/// <remarks>
/// <para>
/// If no data is available for reading, the <see cref="Read(Socket, byte[], int, int, TimeSpan)"/> method will
/// block until data is available or the time-out value is exceeded. If the time-out value is exceeded, the
/// <see cref="Read(Socket, byte[], int, int, TimeSpan)"/> call will throw a <see cref="SshOperationTimeoutException"/>.
/// </para>
/// <para>
/// If you are in non-blocking mode, and there is no data available in the in the protocol stack buffer, the
/// <see cref="Read(Socket, byte[], int, int, TimeSpan)"/> method will complete immediately and throw a <see cref="SocketException"/>.
/// </para>
/// </remarks>
public static int Read(Socket socket, byte[] buffer, int offset, int size, TimeSpan readTimeout)
{
#if FEATURE_SOCKET_SYNC
var totalBytesRead = 0;
var totalBytesToRead = size;
socket.ReceiveTimeout = (int)readTimeout.TotalMilliseconds;
do
{
try
{
var bytesRead = socket.Receive(buffer, offset + totalBytesRead, totalBytesToRead - totalBytesRead, SocketFlags.None);
if (bytesRead == 0)
return 0;
totalBytesRead += bytesRead;
}
catch (SocketException ex)
{
if (IsErrorResumable(ex.SocketErrorCode))
{
ThreadAbstraction.Sleep(30);
continue;
}
if (ex.SocketErrorCode == SocketError.TimedOut)
throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
"Socket read operation has timed out after {0:F0} milliseconds.", readTimeout.TotalMilliseconds));
throw;
}
}
while (totalBytesRead < totalBytesToRead);
return totalBytesRead;
#elif FEATURE_SOCKET_EAP
var receiveCompleted = new ManualResetEvent(false);
var sendReceiveToken = new BlockingSendReceiveToken(socket, buffer, offset, size, receiveCompleted);
var args = new SocketAsyncEventArgs
{
UserToken = sendReceiveToken,
RemoteEndPoint = socket.RemoteEndPoint
};
args.Completed += ReceiveCompleted;
args.SetBuffer(buffer, offset, size);
try
{
if (socket.ReceiveAsync(args))
{
if (!receiveCompleted.WaitOne(readTimeout))
throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
"Socket read operation has timed out after {0:F0} milliseconds.", readTimeout.TotalMilliseconds));
}
else
{
sendReceiveToken.Process(args);
}
if (args.SocketError != SocketError.Success)
throw new SocketException((int) args.SocketError);
return sendReceiveToken.TotalBytesTransferred;
}
finally
{
// initialize token to avoid the waithandle getting used after it's disposed
args.UserToken = null;
args.Dispose();
receiveCompleted.Dispose();
}
#else
#error Receiving data from a Socket is not implemented.
#endif
}
public static void Send(Socket socket, byte[] data)
{
Send(socket, data, 0, data.Length);
}
public static void Send(Socket socket, byte[] data, int offset, int size)
{
#if FEATURE_SOCKET_SYNC
var totalBytesSent = 0; // how many bytes are already sent
var totalBytesToSend = size;
do
{
try
{
var bytesSent = socket.Send(data, offset + totalBytesSent, totalBytesToSend - totalBytesSent, SocketFlags.None);
if (bytesSent == 0)
throw new SshConnectionException("An established connection was aborted by the server.",
DisconnectReason.ConnectionLost);
totalBytesSent += bytesSent;
}
catch (SocketException ex)
{
if (IsErrorResumable(ex.SocketErrorCode))
{
// socket buffer is probably full, wait and try again
ThreadAbstraction.Sleep(30);
}
else
throw; // any serious error occurr
}
} while (totalBytesSent < totalBytesToSend);
#elif FEATURE_SOCKET_EAP
var sendCompleted = new ManualResetEvent(false);
var sendReceiveToken = new BlockingSendReceiveToken(socket, data, offset, size, sendCompleted);
var socketAsyncSendArgs = new SocketAsyncEventArgs
{
RemoteEndPoint = socket.RemoteEndPoint,
UserToken = sendReceiveToken
};
socketAsyncSendArgs.SetBuffer(data, offset, size);
socketAsyncSendArgs.Completed += SendCompleted;
try
{
if (socket.SendAsync(socketAsyncSendArgs))
{
if (!sendCompleted.WaitOne())
throw new SocketException((int) SocketError.TimedOut);
}
else
{
sendReceiveToken.Process(socketAsyncSendArgs);
}
if (socketAsyncSendArgs.SocketError != SocketError.Success)
throw new SocketException((int) socketAsyncSendArgs.SocketError);
if (sendReceiveToken.TotalBytesTransferred == 0)
throw new SshConnectionException("An established connection was aborted by the server.",
DisconnectReason.ConnectionLost);
}
finally
{
// initialize token to avoid the completion waithandle getting used after it's disposed
socketAsyncSendArgs.UserToken = null;
socketAsyncSendArgs.Dispose();
sendCompleted.Dispose();
}
#else
#error Sending data to a Socket is not implemented.
#endif
}
public static bool IsErrorResumable(SocketError socketError)
{
switch (socketError)
{
case SocketError.WouldBlock:
case SocketError.IOPending:
case SocketError.NoBufferSpaceAvailable:
return true;
default:
return false;
}
}
#if FEATURE_SOCKET_EAP
private static void ConnectCompleted(object sender, SocketAsyncEventArgs e)
{
var eventWaitHandle = (ManualResetEvent) e.UserToken;
if (eventWaitHandle != null)
eventWaitHandle.Set();
}
#endif // FEATURE_SOCKET_EAP
#if FEATURE_SOCKET_EAP && !FEATURE_SOCKET_SYNC
private static void ReceiveCompleted(object sender, SocketAsyncEventArgs e)
{
var sendReceiveToken = (Token) e.UserToken;
if (sendReceiveToken != null)
sendReceiveToken.Process(e);
}
private static void SendCompleted(object sender, SocketAsyncEventArgs e)
{
var sendReceiveToken = (Token) e.UserToken;
if (sendReceiveToken != null)
sendReceiveToken.Process(e);
}
private interface Token
{
void Process(SocketAsyncEventArgs args);
}
private class BlockingSendReceiveToken : Token
{
public BlockingSendReceiveToken(Socket socket, byte[] buffer, int offset, int size, EventWaitHandle completionWaitHandle)
{
_socket = socket;
_buffer = buffer;
_offset = offset;
_bytesToTransfer = size;
_completionWaitHandle = completionWaitHandle;
}
public void Process(SocketAsyncEventArgs args)
{
if (args.SocketError == SocketError.Success)
{
TotalBytesTransferred += args.BytesTransferred;
if (TotalBytesTransferred == _bytesToTransfer)
{
// finished transferring specified bytes
_completionWaitHandle.Set();
return;
}
if (args.BytesTransferred == 0)
{
// remote server closed the connection
_completionWaitHandle.Set();
return;
}
_offset += args.BytesTransferred;
args.SetBuffer(_buffer, _offset, _bytesToTransfer - TotalBytesTransferred);
ResumeOperation(args);
return;
}
if (IsErrorResumable(args.SocketError))
{
ThreadAbstraction.Sleep(30);
ResumeOperation(args);
return;
}
// we're dealing with a (fatal) error
_completionWaitHandle.Set();
}
private void ResumeOperation(SocketAsyncEventArgs args)
{
switch (args.LastOperation)
{
case SocketAsyncOperation.Receive:
_socket.ReceiveAsync(args);
break;
case SocketAsyncOperation.Send:
_socket.SendAsync(args);
break;
}
}
private readonly int _bytesToTransfer;
public int TotalBytesTransferred { get; private set; }
private readonly EventWaitHandle _completionWaitHandle;
private readonly Socket _socket;
private readonly byte[] _buffer;
private int _offset;
}
private class PartialSendReceiveToken : Token
{
public PartialSendReceiveToken(Socket socket, EventWaitHandle completionWaitHandle)
{
_socket = socket;
_completionWaitHandle = completionWaitHandle;
}
public void Process(SocketAsyncEventArgs args)
{
if (args.SocketError == SocketError.Success)
{
_completionWaitHandle.Set();
return;
}
if (IsErrorResumable(args.SocketError))
{
ThreadAbstraction.Sleep(30);
ResumeOperation(args);
return;
}
// we're dealing with a (fatal) error
_completionWaitHandle.Set();
}
private void ResumeOperation(SocketAsyncEventArgs args)
{
switch (args.LastOperation)
{
case SocketAsyncOperation.Receive:
_socket.ReceiveAsync(args);
break;
case SocketAsyncOperation.Send:
_socket.SendAsync(args);
break;
}
}
private readonly EventWaitHandle _completionWaitHandle;
private readonly Socket _socket;
}
private class ContinuousReceiveToken : Token
{
public ContinuousReceiveToken(Socket socket, Action<byte[], int, int> processReceivedBytesAction, EventWaitHandle completionWaitHandle)
{
_socket = socket;
_processReceivedBytesAction = processReceivedBytesAction;
_completionWaitHandle = completionWaitHandle;
}
public Exception Exception { get; private set; }
public void Process(SocketAsyncEventArgs args)
{
if (args.SocketError == SocketError.Success)
{
if (args.BytesTransferred == 0)
{
// remote socket was closed
_completionWaitHandle.Set();
return;
}
_processReceivedBytesAction(args.Buffer, args.Offset, args.BytesTransferred);
ResumeOperation(args);
return;
}
if (IsErrorResumable(args.SocketError))
{
ThreadAbstraction.Sleep(30);
ResumeOperation(args);
return;
}
if (args.SocketError != SocketError.OperationAborted)
{
Exception = new SocketException((int) args.SocketError);
}
// we're dealing with a (fatal) error
_completionWaitHandle.Set();
}
private void ResumeOperation(SocketAsyncEventArgs args)
{
switch (args.LastOperation)
{
case SocketAsyncOperation.Receive:
_socket.ReceiveAsync(args);
break;
case SocketAsyncOperation.Send:
_socket.SendAsync(args);
break;
}
}
private readonly EventWaitHandle _completionWaitHandle;
private readonly Socket _socket;
private readonly Action<byte[], int, int> _processReceivedBytesAction;
}
#endif // FEATURE_SOCKET_EAP && !FEATURE_SOCKET_SYNC
}
}