Session.SilverlightShared.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Threading;
  8. using Renci.SshNet.Common;
  9. using Renci.SshNet.Messages.Transport;
  10. namespace Renci.SshNet
  11. {
  12. public partial class Session
  13. {
  14. private const byte Null = 0x00;
  15. private const byte CarriageReturn = 0x0d;
  16. private const byte LineFeed = 0x0a;
  17. private readonly AutoResetEvent _connectEvent = new AutoResetEvent(false);
  18. private readonly AutoResetEvent _sendEvent = new AutoResetEvent(false);
  19. private readonly AutoResetEvent _receiveEvent = new AutoResetEvent(false);
  20. /// <summary>
  21. /// Gets a value indicating whether the socket is connected.
  22. /// </summary>
  23. /// <param name="isConnected"><c>true</c> if the socket is connected; otherwise, <c>false</c></param>
  24. partial void IsSocketConnected(ref bool isConnected)
  25. {
  26. isConnected = (_socket != null && _socket.Connected);
  27. }
  28. /// <summary>
  29. /// Establishes a socket connection to the specified host and port.
  30. /// </summary>
  31. /// <param name="host">The host name of the server to connect to.</param>
  32. /// <param name="port">The port to connect to.</param>
  33. /// <exception cref="SshOperationTimeoutException">The connection failed to establish within the configured <see cref="Renci.SshNet.ConnectionInfo.Timeout"/>.</exception>
  34. /// <exception cref="SocketException">An error occurred trying to establish the connection.</exception>
  35. partial void SocketConnect(string host, int port)
  36. {
  37. var timeout = ConnectionInfo.Timeout;
  38. var ipAddress = host.GetIPAddress();
  39. var ep = new IPEndPoint(ipAddress, port);
  40. _socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  41. var args = CreateSocketAsyncEventArgs(_connectEvent);
  42. if (_socket.ConnectAsync(args))
  43. {
  44. if (!_connectEvent.WaitOne(timeout))
  45. throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
  46. "Connection failed to establish within {0:F0} milliseconds.", timeout.TotalMilliseconds));
  47. }
  48. if (args.SocketError != SocketError.Success)
  49. throw new SocketException((int) args.SocketError);
  50. }
  51. /// <summary>
  52. /// Closes the socket.
  53. /// </summary>
  54. /// <remarks>
  55. /// This method will wait up to <c>10</c> seconds to send any remaining data.
  56. /// </remarks>
  57. partial void SocketDisconnect()
  58. {
  59. _socket.Close(10);
  60. }
  61. /// <summary>
  62. /// Performs a blocking read on the socket until a line is read.
  63. /// </summary>
  64. /// <param name="response">The line read from the socket, or <c>null</c> when the remote server has shutdown and all data has been received.</param>
  65. /// <param name="timeout">A <see cref="TimeSpan"/> that represents the time to wait until a line is read.</param>
  66. /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception>
  67. /// <exception cref="SocketException">An error occurred when trying to access the socket.</exception>
  68. partial void SocketReadLine(ref string response, TimeSpan timeout)
  69. {
  70. var encoding = new ASCIIEncoding();
  71. var buffer = new List<byte>();
  72. var data = new byte[1];
  73. // read data one byte at a time to find end of line and leave any unhandled information in the buffer
  74. // to be processed by subsequent invocations
  75. do
  76. {
  77. var args = CreateSocketAsyncEventArgs(_receiveEvent, data, 0, data.Length);
  78. if (_socket.ReceiveAsync(args))
  79. {
  80. if (!_receiveEvent.WaitOne(timeout))
  81. throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
  82. "Socket read operation has timed out after {0:F0} milliseconds.", timeout.TotalMilliseconds));
  83. }
  84. if (args.SocketError != SocketError.Success)
  85. throw new SocketException((int) args.SocketError);
  86. if (args.BytesTransferred == 0)
  87. // the remote server shut down the socket
  88. break;
  89. buffer.Add(data[0]);
  90. }
  91. while (!(buffer.Count > 0 && (buffer[buffer.Count - 1] == LineFeed || buffer[buffer.Count - 1] == Null)));
  92. if (buffer.Count == 0)
  93. response = null;
  94. else if (buffer.Count == 1 && buffer[buffer.Count - 1] == 0x00)
  95. // return an empty version string if the buffer consists of only a 0x00 character
  96. response = string.Empty;
  97. else if (buffer.Count > 1 && buffer[buffer.Count - 2] == CarriageReturn)
  98. // strip trailing CRLF
  99. response = encoding.GetString(buffer.ToArray(), 0, buffer.Count - 2);
  100. else if (buffer.Count > 1 && buffer[buffer.Count - 1] == LineFeed)
  101. // strip trailing LF
  102. response = encoding.GetString(buffer.ToArray(), 0, buffer.Count - 1);
  103. else
  104. response = encoding.GetString(buffer.ToArray(), 0, buffer.Count);
  105. }
  106. /// <summary>
  107. /// Performs a blocking read on the socket until <paramref name="length"/> bytes are received.
  108. /// </summary>
  109. /// <param name="length">The number of bytes to read.</param>
  110. /// <param name="buffer">The buffer to read to.</param>
  111. /// <param name="timeout">A <see cref="TimeSpan"/> that represents the time to wait until <paramref name="length"/> bytes a read.</param>
  112. /// <exception cref="SshConnectionException">The socket is closed.</exception>
  113. /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception>
  114. /// <exception cref="SocketException">The read failed.</exception>
  115. partial void SocketRead(int length, ref byte[] buffer, TimeSpan timeout)
  116. {
  117. var totalBytesReceived = 0; // how many bytes are already received
  118. do
  119. {
  120. var args = CreateSocketAsyncEventArgs(_receiveEvent, buffer, totalBytesReceived,
  121. length - totalBytesReceived);
  122. if (_socket.ReceiveAsync(args))
  123. {
  124. if (!_receiveEvent.WaitOne(timeout))
  125. throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
  126. "Socket read operation has timed out after {0:F0} milliseconds.", timeout.TotalMilliseconds));
  127. }
  128. switch (args.SocketError)
  129. {
  130. case SocketError.WouldBlock:
  131. case SocketError.IOPending:
  132. case SocketError.NoBufferSpaceAvailable:
  133. // socket buffer is probably full, wait and try again
  134. Thread.Sleep(30);
  135. break;
  136. case SocketError.Success:
  137. var bytesReceived = args.BytesTransferred;
  138. if (bytesReceived > 0)
  139. {
  140. totalBytesReceived += bytesReceived;
  141. continue;
  142. }
  143. if (_isDisconnecting)
  144. throw new SshConnectionException(
  145. "An established connection was aborted by the software in your host machine.",
  146. DisconnectReason.ConnectionLost);
  147. throw new SshConnectionException("An established connection was aborted by the server.",
  148. DisconnectReason.ConnectionLost);
  149. default:
  150. throw new SocketException((int) args.SocketError);
  151. }
  152. } while (totalBytesReceived < length);
  153. }
  154. /// <summary>
  155. /// Writes the specified data to the server.
  156. /// </summary>
  157. /// <param name="data">The data to write to the server.</param>
  158. /// <exception cref="SshOperationTimeoutException">The write has timed-out.</exception>
  159. /// <exception cref="SocketException">The write failed.</exception>
  160. partial void SocketWrite(byte[] data)
  161. {
  162. var timeout = ConnectionInfo.Timeout;
  163. var totalBytesSent = 0; // how many bytes are already sent
  164. var totalBytesToSend = data.Length;
  165. do
  166. {
  167. var args = CreateSocketAsyncEventArgs(_sendEvent, data, 0, totalBytesToSend - totalBytesSent);
  168. if (_socket.SendAsync(args))
  169. {
  170. if (!_sendEvent.WaitOne(timeout))
  171. throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
  172. "Socket write operation has timed out after {0:F0} milliseconds.", timeout.TotalMilliseconds));
  173. }
  174. switch (args.SocketError)
  175. {
  176. case SocketError.WouldBlock:
  177. case SocketError.IOPending:
  178. case SocketError.NoBufferSpaceAvailable:
  179. // socket buffer is probably full, wait and try again
  180. Thread.Sleep(30);
  181. break;
  182. case SocketError.Success:
  183. totalBytesSent += args.BytesTransferred;
  184. break;
  185. default:
  186. throw new SocketException((int) args.SocketError);
  187. }
  188. } while (totalBytesSent < totalBytesToSend);
  189. }
  190. partial void ExecuteThread(Action action)
  191. {
  192. ThreadPool.QueueUserWorkItem(o => action());
  193. }
  194. partial void InternalRegisterMessage(string messageName)
  195. {
  196. lock (_messagesMetadata)
  197. {
  198. foreach (var item in from m in _messagesMetadata where m.Name == messageName select m)
  199. {
  200. item.Enabled = true;
  201. item.Activated = true;
  202. }
  203. }
  204. }
  205. partial void InternalUnRegisterMessage(string messageName)
  206. {
  207. lock (_messagesMetadata)
  208. {
  209. foreach (var item in from m in _messagesMetadata where m.Name == messageName select m)
  210. {
  211. item.Enabled = false;
  212. item.Activated = false;
  213. }
  214. }
  215. }
  216. private SocketAsyncEventArgs CreateSocketAsyncEventArgs(EventWaitHandle waitHandle)
  217. {
  218. var args = new SocketAsyncEventArgs();
  219. args.UserToken = _socket;
  220. args.RemoteEndPoint = _socket.RemoteEndPoint;
  221. args.Completed += (sender, eventArgs) => waitHandle.Set();
  222. return args;
  223. }
  224. private SocketAsyncEventArgs CreateSocketAsyncEventArgs(EventWaitHandle waitHandle, byte[] data, int offset, int count)
  225. {
  226. var args = CreateSocketAsyncEventArgs(waitHandle);
  227. args.SetBuffer(data, offset, count);
  228. return args;
  229. }
  230. }
  231. }