| | | 1 | | using System; |
| | | 2 | | using System.Globalization; |
| | | 3 | | using System.Net; |
| | | 4 | | using System.Net.Sockets; |
| | | 5 | | using System.Threading; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | |
| | | 8 | | using Renci.SshNet.Common; |
| | | 9 | | using Renci.SshNet.Messages.Transport; |
| | | 10 | | |
| | | 11 | | namespace Renci.SshNet.Abstractions |
| | | 12 | | { |
| | | 13 | | internal static class SocketAbstraction |
| | | 14 | | { |
| | | 15 | | public static bool CanRead(Socket socket) |
| | 0 | 16 | | { |
| | 0 | 17 | | if (socket.Connected) |
| | 0 | 18 | | { |
| | 0 | 19 | | return socket.Poll(-1, SelectMode.SelectRead) && socket.Available > 0; |
| | | 20 | | } |
| | | 21 | | |
| | 0 | 22 | | return false; |
| | 0 | 23 | | } |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Returns a value indicating whether the specified <see cref="Socket"/> can be used |
| | | 27 | | /// to send data. |
| | | 28 | | /// </summary> |
| | | 29 | | /// <param name="socket">The <see cref="Socket"/> to check.</param> |
| | | 30 | | /// <returns> |
| | | 31 | | /// <see langword="true"/> if <paramref name="socket"/> can be written to; otherwise, <see langword="false"/>. |
| | | 32 | | /// </returns> |
| | | 33 | | public static bool CanWrite(Socket socket) |
| | 53126 | 34 | | { |
| | 53126 | 35 | | if (socket != null && socket.Connected) |
| | 53040 | 36 | | { |
| | 53040 | 37 | | return socket.Poll(-1, SelectMode.SelectWrite); |
| | | 38 | | } |
| | | 39 | | |
| | 86 | 40 | | return false; |
| | 53126 | 41 | | } |
| | | 42 | | |
| | | 43 | | public static Socket Connect(IPEndPoint remoteEndpoint, TimeSpan connectTimeout) |
| | 21 | 44 | | { |
| | 21 | 45 | | var socket = new Socket(remoteEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true |
| | 21 | 46 | | ConnectCore(socket, remoteEndpoint, connectTimeout, ownsSocket: true); |
| | 21 | 47 | | return socket; |
| | 21 | 48 | | } |
| | | 49 | | |
| | | 50 | | public static void Connect(Socket socket, IPEndPoint remoteEndpoint, TimeSpan connectTimeout) |
| | 2262 | 51 | | { |
| | 2262 | 52 | | ConnectCore(socket, remoteEndpoint, connectTimeout, ownsSocket: false); |
| | 2178 | 53 | | } |
| | | 54 | | |
| | | 55 | | public static async Task ConnectAsync(Socket socket, IPEndPoint remoteEndpoint, CancellationToken cancellationTo |
| | 2 | 56 | | { |
| | 2 | 57 | | await socket.ConnectAsync(remoteEndpoint, cancellationToken).ConfigureAwait(false); |
| | 2 | 58 | | } |
| | | 59 | | |
| | | 60 | | private static void ConnectCore(Socket socket, IPEndPoint remoteEndpoint, TimeSpan connectTimeout, bool ownsSock |
| | 2283 | 61 | | { |
| | | 62 | | #if FEATURE_SOCKET_EAP |
| | 2283 | 63 | | var connectCompleted = new ManualResetEvent(initialState: false); |
| | 2283 | 64 | | var args = new SocketAsyncEventArgs |
| | 2283 | 65 | | { |
| | 2283 | 66 | | UserToken = connectCompleted, |
| | 2283 | 67 | | RemoteEndPoint = remoteEndpoint |
| | 2283 | 68 | | }; |
| | 2283 | 69 | | args.Completed += ConnectCompleted; |
| | | 70 | | |
| | 2283 | 71 | | if (socket.ConnectAsync(args)) |
| | 2102 | 72 | | { |
| | 2102 | 73 | | if (!connectCompleted.WaitOne(connectTimeout)) |
| | 24 | 74 | | { |
| | | 75 | | // avoid ObjectDisposedException in ConnectCompleted |
| | 24 | 76 | | args.Completed -= ConnectCompleted; |
| | 24 | 77 | | if (ownsSocket) |
| | 0 | 78 | | { |
| | | 79 | | // dispose Socket |
| | 0 | 80 | | socket.Dispose(); |
| | 0 | 81 | | } |
| | | 82 | | |
| | | 83 | | // dispose ManualResetEvent |
| | 24 | 84 | | connectCompleted.Dispose(); |
| | | 85 | | |
| | | 86 | | // dispose SocketAsyncEventArgs |
| | 24 | 87 | | args.Dispose(); |
| | | 88 | | |
| | 24 | 89 | | throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture, |
| | 24 | 90 | | "Connection failed to establish within {0:F0} m |
| | 24 | 91 | | connectTimeout.TotalMilliseconds)); |
| | | 92 | | } |
| | 2078 | 93 | | } |
| | | 94 | | |
| | | 95 | | // dispose ManualResetEvent |
| | 2259 | 96 | | connectCompleted.Dispose(); |
| | | 97 | | |
| | 2259 | 98 | | if (args.SocketError != SocketError.Success) |
| | 60 | 99 | | { |
| | 60 | 100 | | var socketError = (int) args.SocketError; |
| | | 101 | | |
| | 60 | 102 | | if (ownsSocket) |
| | 0 | 103 | | { |
| | | 104 | | // dispose Socket |
| | 0 | 105 | | socket.Dispose(); |
| | 0 | 106 | | } |
| | | 107 | | |
| | | 108 | | // dispose SocketAsyncEventArgs |
| | 60 | 109 | | args.Dispose(); |
| | | 110 | | |
| | 60 | 111 | | throw new SocketException(socketError); |
| | | 112 | | } |
| | | 113 | | |
| | | 114 | | // dispose SocketAsyncEventArgs |
| | 2199 | 115 | | args.Dispose(); |
| | | 116 | | #elif FEATURE_SOCKET_APM |
| | | 117 | | var connectResult = socket.BeginConnect(remoteEndpoint, null, null); |
| | | 118 | | if (!connectResult.AsyncWaitHandle.WaitOne(connectTimeout, false)) |
| | | 119 | | throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture, |
| | | 120 | | "Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds)); |
| | | 121 | | socket.EndConnect(connectResult); |
| | | 122 | | #elif FEATURE_SOCKET_TAP |
| | | 123 | | if (!socket.ConnectAsync(remoteEndpoint).Wait(connectTimeout)) |
| | | 124 | | throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture, |
| | | 125 | | "Connection failed to establish within {0:F0} milliseconds.", connectTimeout.TotalMilliseconds)); |
| | | 126 | | #else |
| | | 127 | | #error Connecting to a remote endpoint is not implemented. |
| | | 128 | | #endif |
| | 2199 | 129 | | } |
| | | 130 | | |
| | | 131 | | public static void ClearReadBuffer(Socket socket) |
| | 0 | 132 | | { |
| | 0 | 133 | | var timeout = TimeSpan.FromMilliseconds(500); |
| | 0 | 134 | | var buffer = new byte[256]; |
| | | 135 | | int bytesReceived; |
| | | 136 | | |
| | | 137 | | do |
| | 0 | 138 | | { |
| | 0 | 139 | | bytesReceived = ReadPartial(socket, buffer, 0, buffer.Length, timeout); |
| | 0 | 140 | | } |
| | 0 | 141 | | while (bytesReceived > 0); |
| | 0 | 142 | | } |
| | | 143 | | |
| | | 144 | | public static int ReadPartial(Socket socket, byte[] buffer, int offset, int size, TimeSpan timeout) |
| | 0 | 145 | | { |
| | 0 | 146 | | socket.ReceiveTimeout = (int) timeout.TotalMilliseconds; |
| | | 147 | | |
| | | 148 | | try |
| | 0 | 149 | | { |
| | 0 | 150 | | return socket.Receive(buffer, offset, size, SocketFlags.None); |
| | | 151 | | } |
| | 0 | 152 | | catch (SocketException ex) |
| | 0 | 153 | | { |
| | 0 | 154 | | if (ex.SocketErrorCode == SocketError.TimedOut) |
| | 0 | 155 | | { |
| | 0 | 156 | | throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture, |
| | 0 | 157 | | "Socket read operation has timed out after {0:F |
| | 0 | 158 | | timeout.TotalMilliseconds)); |
| | | 159 | | } |
| | | 160 | | |
| | 0 | 161 | | throw; |
| | | 162 | | } |
| | 0 | 163 | | } |
| | | 164 | | |
| | | 165 | | public static void ReadContinuous(Socket socket, byte[] buffer, int offset, int size, Action<byte[], int, int> p |
| | 48 | 166 | | { |
| | | 167 | | // do not time-out receive |
| | 48 | 168 | | socket.ReceiveTimeout = 0; |
| | | 169 | | |
| | 56 | 170 | | while (socket.Connected) |
| | 56 | 171 | | { |
| | | 172 | | try |
| | 56 | 173 | | { |
| | 56 | 174 | | var bytesRead = socket.Receive(buffer, offset, size, SocketFlags.None); |
| | 48 | 175 | | if (bytesRead == 0) |
| | 40 | 176 | | { |
| | 40 | 177 | | break; |
| | | 178 | | } |
| | | 179 | | |
| | 8 | 180 | | processReceivedBytesAction(buffer, offset, bytesRead); |
| | 8 | 181 | | } |
| | 8 | 182 | | catch (SocketException ex) |
| | 8 | 183 | | { |
| | 8 | 184 | | if (IsErrorResumable(ex.SocketErrorCode)) |
| | 0 | 185 | | { |
| | 0 | 186 | | continue; |
| | | 187 | | } |
| | | 188 | | |
| | | 189 | | #pragma warning disable IDE0010 // Add missing cases |
| | 8 | 190 | | switch (ex.SocketErrorCode) |
| | | 191 | | { |
| | | 192 | | case SocketError.ConnectionAborted: |
| | | 193 | | case SocketError.ConnectionReset: |
| | | 194 | | // connection was closed |
| | 8 | 195 | | return; |
| | | 196 | | case SocketError.Interrupted: |
| | | 197 | | // connection was closed because FIN/ACK was not received in time after |
| | | 198 | | // shutting down the (send part of the) socket |
| | 0 | 199 | | return; |
| | | 200 | | default: |
| | 0 | 201 | | throw; // throw any other error |
| | | 202 | | } |
| | | 203 | | #pragma warning restore IDE0010 // Add missing cases |
| | | 204 | | } |
| | 8 | 205 | | } |
| | 48 | 206 | | } |
| | | 207 | | |
| | | 208 | | /// <summary> |
| | | 209 | | /// Reads a byte from the specified <see cref="Socket"/>. |
| | | 210 | | /// </summary> |
| | | 211 | | /// <param name="socket">The <see cref="Socket"/> to read from.</param> |
| | | 212 | | /// <param name="timeout">Specifies the amount of time after which the call will time out.</param> |
| | | 213 | | /// <returns> |
| | | 214 | | /// The byte read, or <c>-1</c> if the socket was closed. |
| | | 215 | | /// </returns> |
| | | 216 | | /// <exception cref="SshOperationTimeoutException">The read operation timed out.</exception> |
| | | 217 | | /// <exception cref="SocketException">The read failed.</exception> |
| | | 218 | | public static int ReadByte(Socket socket, TimeSpan timeout) |
| | 249 | 219 | | { |
| | 249 | 220 | | var buffer = new byte[1]; |
| | 249 | 221 | | if (Read(socket, buffer, 0, 1, timeout) == 0) |
| | 22 | 222 | | { |
| | 22 | 223 | | return -1; |
| | | 224 | | } |
| | | 225 | | |
| | 195 | 226 | | return buffer[0]; |
| | 217 | 227 | | } |
| | | 228 | | |
| | | 229 | | /// <summary> |
| | | 230 | | /// Sends a byte using the specified <see cref="Socket"/>. |
| | | 231 | | /// </summary> |
| | | 232 | | /// <param name="socket">The <see cref="Socket"/> to write to.</param> |
| | | 233 | | /// <param name="value">The value to send.</param> |
| | | 234 | | /// <exception cref="SocketException">The write failed.</exception> |
| | | 235 | | public static void SendByte(Socket socket, byte value) |
| | 150 | 236 | | { |
| | 150 | 237 | | var buffer = new[] { value }; |
| | 150 | 238 | | Send(socket, buffer, 0, 1); |
| | 150 | 239 | | } |
| | | 240 | | |
| | | 241 | | /// <summary> |
| | | 242 | | /// Receives data from a bound <see cref="Socket"/>. |
| | | 243 | | /// </summary> |
| | | 244 | | /// <param name="socket">The <see cref="Socket"/> to read from.</param> |
| | | 245 | | /// <param name="size">The number of bytes to receive.</param> |
| | | 246 | | /// <param name="timeout">Specifies the amount of time after which the call will time out.</param> |
| | | 247 | | /// <returns> |
| | | 248 | | /// The bytes received. |
| | | 249 | | /// </returns> |
| | | 250 | | /// <remarks> |
| | | 251 | | /// If no data is available for reading, the <see cref="Read(Socket, int, TimeSpan)"/> method will |
| | | 252 | | /// block until data is available or the time-out value is exceeded. If the time-out value is exceeded, the |
| | | 253 | | /// <see cref="Read(Socket, int, TimeSpan)"/> call will throw a <see cref="SshOperationTimeoutException"/>. |
| | | 254 | | /// If you are in non-blocking mode, and there is no data available in the in the protocol stack buffer, the |
| | | 255 | | /// <see cref="Read(Socket, int, TimeSpan)"/> method will complete immediately and throw a <see cref="SocketExce |
| | | 256 | | /// </remarks> |
| | | 257 | | public static byte[] Read(Socket socket, int size, TimeSpan timeout) |
| | 30 | 258 | | { |
| | 30 | 259 | | var buffer = new byte[size]; |
| | 30 | 260 | | _ = Read(socket, buffer, 0, size, timeout); |
| | 30 | 261 | | return buffer; |
| | 30 | 262 | | } |
| | | 263 | | |
| | | 264 | | /// <summary> |
| | | 265 | | /// Receives data from a bound <see cref="Socket"/> into a receive buffer. |
| | | 266 | | /// </summary> |
| | | 267 | | /// <param name="socket">The <see cref="Socket"/> to read from.</param> |
| | | 268 | | /// <param name="buffer">An array of type <see cref="byte"/> that is the storage location for the received data. |
| | | 269 | | /// <param name="offset">The position in <paramref name="buffer"/> parameter to store the received data.</param> |
| | | 270 | | /// <param name="size">The number of bytes to receive.</param> |
| | | 271 | | /// <param name="readTimeout">The maximum time to wait until <paramref name="size"/> bytes have been received.</ |
| | | 272 | | /// <returns> |
| | | 273 | | /// The number of bytes received. |
| | | 274 | | /// </returns> |
| | | 275 | | /// <remarks> |
| | | 276 | | /// <para> |
| | | 277 | | /// If no data is available for reading, the <see cref="Read(Socket, byte[], int, int, TimeSpan)"/> method will |
| | | 278 | | /// block until data is available or the time-out value is exceeded. If the time-out value is exceeded, the |
| | | 279 | | /// <see cref="Read(Socket, byte[], int, int, TimeSpan)"/> call will throw a <see cref="SshOperationTimeoutExcep |
| | | 280 | | /// </para> |
| | | 281 | | /// <para> |
| | | 282 | | /// If you are in non-blocking mode, and there is no data available in the in the protocol stack buffer, the |
| | | 283 | | /// <see cref="Read(Socket, byte[], int, int, TimeSpan)"/> method will complete immediately and throw a <see cre |
| | | 284 | | /// </para> |
| | | 285 | | /// </remarks> |
| | | 286 | | public static int Read(Socket socket, byte[] buffer, int offset, int size, TimeSpan readTimeout) |
| | 156307 | 287 | | { |
| | 156307 | 288 | | var totalBytesRead = 0; |
| | 156307 | 289 | | var totalBytesToRead = size; |
| | | 290 | | |
| | 156307 | 291 | | socket.ReceiveTimeout = (int) readTimeout.TotalMilliseconds; |
| | | 292 | | |
| | | 293 | | do |
| | 156599 | 294 | | { |
| | | 295 | | try |
| | 156599 | 296 | | { |
| | 156599 | 297 | | var bytesRead = socket.Receive(buffer, offset + totalBytesRead, totalBytesToRead - totalBytesRead, S |
| | 156480 | 298 | | if (bytesRead == 0) |
| | 109 | 299 | | { |
| | 109 | 300 | | return 0; |
| | | 301 | | } |
| | | 302 | | |
| | 156371 | 303 | | totalBytesRead += bytesRead; |
| | 156371 | 304 | | } |
| | 119 | 305 | | catch (SocketException ex) |
| | 119 | 306 | | { |
| | 119 | 307 | | if (IsErrorResumable(ex.SocketErrorCode)) |
| | 0 | 308 | | { |
| | 0 | 309 | | ThreadAbstraction.Sleep(30); |
| | 0 | 310 | | continue; |
| | | 311 | | } |
| | | 312 | | |
| | 119 | 313 | | if (ex.SocketErrorCode == SocketError.TimedOut) |
| | 87 | 314 | | { |
| | 87 | 315 | | throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture, |
| | 87 | 316 | | "Socket read operation has timed out after {0:F0} millise |
| | 87 | 317 | | readTimeout.TotalMilliseconds)); |
| | | 318 | | } |
| | | 319 | | |
| | 32 | 320 | | throw; |
| | | 321 | | } |
| | 156371 | 322 | | } |
| | 156371 | 323 | | while (totalBytesRead < totalBytesToRead); |
| | | 324 | | |
| | 156079 | 325 | | return totalBytesRead; |
| | 156188 | 326 | | } |
| | | 327 | | |
| | | 328 | | public static Task<int> ReadAsync(Socket socket, byte[] buffer, int offset, int length, CancellationToken cancel |
| | 42 | 329 | | { |
| | 42 | 330 | | return socket.ReceiveAsync(buffer, offset, length, cancellationToken); |
| | 42 | 331 | | } |
| | | 332 | | |
| | | 333 | | public static void Send(Socket socket, byte[] data) |
| | 2070 | 334 | | { |
| | 2070 | 335 | | Send(socket, data, 0, data.Length); |
| | 2070 | 336 | | } |
| | | 337 | | |
| | | 338 | | public static void Send(Socket socket, byte[] data, int offset, int size) |
| | 55386 | 339 | | { |
| | 55386 | 340 | | var totalBytesSent = 0; // how many bytes are already sent |
| | 55386 | 341 | | var totalBytesToSend = size; |
| | | 342 | | |
| | | 343 | | do |
| | 55386 | 344 | | { |
| | | 345 | | try |
| | 55386 | 346 | | { |
| | 55386 | 347 | | var bytesSent = socket.Send(data, offset + totalBytesSent, totalBytesToSend - totalBytesSent, Socket |
| | 55386 | 348 | | if (bytesSent == 0) |
| | 0 | 349 | | { |
| | 0 | 350 | | throw new SshConnectionException("An established connection was aborted by the server.", |
| | 0 | 351 | | DisconnectReason.ConnectionLost); |
| | | 352 | | } |
| | | 353 | | |
| | 55386 | 354 | | totalBytesSent += bytesSent; |
| | 55386 | 355 | | } |
| | 0 | 356 | | catch (SocketException ex) |
| | 0 | 357 | | { |
| | 0 | 358 | | if (IsErrorResumable(ex.SocketErrorCode)) |
| | 0 | 359 | | { |
| | | 360 | | // socket buffer is probably full, wait and try again |
| | 0 | 361 | | ThreadAbstraction.Sleep(30); |
| | 0 | 362 | | } |
| | | 363 | | else |
| | 0 | 364 | | { |
| | 0 | 365 | | throw; // any serious error occurr |
| | | 366 | | } |
| | 0 | 367 | | } |
| | 55386 | 368 | | } |
| | 55386 | 369 | | while (totalBytesSent < totalBytesToSend); |
| | 55386 | 370 | | } |
| | | 371 | | |
| | | 372 | | public static bool IsErrorResumable(SocketError socketError) |
| | 127 | 373 | | { |
| | | 374 | | #pragma warning disable IDE0010 // Add missing cases |
| | 127 | 375 | | switch (socketError) |
| | | 376 | | { |
| | | 377 | | case SocketError.WouldBlock: |
| | | 378 | | case SocketError.IOPending: |
| | | 379 | | case SocketError.NoBufferSpaceAvailable: |
| | 0 | 380 | | return true; |
| | | 381 | | default: |
| | 127 | 382 | | return false; |
| | | 383 | | } |
| | | 384 | | #pragma warning restore IDE0010 // Add missing cases |
| | 127 | 385 | | } |
| | | 386 | | |
| | | 387 | | #if FEATURE_SOCKET_EAP |
| | | 388 | | private static void ConnectCompleted(object sender, SocketAsyncEventArgs e) |
| | 2078 | 389 | | { |
| | 2078 | 390 | | var eventWaitHandle = (ManualResetEvent) e.UserToken; |
| | 2078 | 391 | | _ = eventWaitHandle?.Set(); |
| | 2078 | 392 | | } |
| | | 393 | | #endif // FEATURE_SOCKET_EAP |
| | | 394 | | } |
| | | 395 | | } |