SocketAbstraction.cs 15 KB

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