Session.NET.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. using System.Linq;
  2. using System;
  3. using System.Net.Sockets;
  4. using System.Net;
  5. using Renci.SshNet.Common;
  6. using System.Threading;
  7. using Renci.SshNet.Messages.Transport;
  8. using System.Diagnostics;
  9. using System.Collections.Generic;
  10. namespace Renci.SshNet
  11. {
  12. public partial class Session
  13. {
  14. private readonly TraceSource _log =
  15. #if DEBUG
  16. new TraceSource("SshNet.Logging", SourceLevels.All);
  17. #else
  18. new TraceSource("SshNet.Logging");
  19. #endif
  20. /// <summary>
  21. /// Gets a value indicating whether the socket is connected.
  22. /// </summary>
  23. /// <value>
  24. /// <c>true</c> if the socket is connected; otherwise, <c>false</c>.
  25. /// </value>
  26. partial void IsSocketConnected(ref bool isConnected)
  27. {
  28. isConnected = (_socket != null && _socket.Connected);
  29. if (isConnected)
  30. {
  31. var connectionClosedOrDataAvailable = _socket.Poll(1000, SelectMode.SelectRead);
  32. isConnected = !(connectionClosedOrDataAvailable && _socket.Available == 0);
  33. }
  34. }
  35. partial void SocketConnect(string host, int port)
  36. {
  37. const int socketBufferSize = 2 * MaximumSshPacketSize;
  38. var addr = host.GetIPAddress();
  39. var ep = new IPEndPoint(addr, port);
  40. this._socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  41. this._socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
  42. this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, socketBufferSize);
  43. this._socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, socketBufferSize);
  44. this.Log(string.Format("Initiating connect to '{0}:{1}'.", this.ConnectionInfo.Host, this.ConnectionInfo.Port));
  45. // Connect socket with specified timeout
  46. var connectResult = this._socket.BeginConnect(ep, null, null);
  47. if (!connectResult.AsyncWaitHandle.WaitOne(this.ConnectionInfo.Timeout, false))
  48. {
  49. throw new SshOperationTimeoutException("Connection Could Not Be Established");
  50. }
  51. this._socket.EndConnect(connectResult);
  52. }
  53. partial void SocketDisconnect()
  54. {
  55. _socket.Disconnect(true);
  56. }
  57. partial void SocketReadLine(ref string response)
  58. {
  59. var encoding = new ASCIIEncoding();
  60. // Read data one byte at a time to find end of line and leave any unhandled information in the buffer to be processed later
  61. var buffer = new List<byte>();
  62. var data = new byte[1];
  63. do
  64. {
  65. var asyncResult = this._socket.BeginReceive(data, 0, data.Length, SocketFlags.None, null, null);
  66. if (!asyncResult.AsyncWaitHandle.WaitOne(this.ConnectionInfo.Timeout))
  67. throw new SshOperationTimeoutException("Socket read operation has timed out");
  68. var received = this._socket.EndReceive(asyncResult);
  69. // If zero bytes received then exit
  70. if (received == 0)
  71. break;
  72. buffer.Add(data[0]);
  73. }
  74. while (!(buffer.Count > 0 && (buffer[buffer.Count - 1] == 0x0A || buffer[buffer.Count - 1] == 0x00)));
  75. // Return an empty version string if the buffer consists of a 0x00 character.
  76. if (buffer.Count > 0 && buffer[buffer.Count - 1] == 0x00)
  77. {
  78. response = string.Empty;
  79. }
  80. else if (buffer.Count > 1 && buffer[buffer.Count - 2] == 0x0D)
  81. response = encoding.GetString(buffer.Take(buffer.Count - 2).ToArray());
  82. else
  83. response = encoding.GetString(buffer.Take(buffer.Count - 1).ToArray());
  84. }
  85. /// <summary>
  86. /// Function to read <paramref name="length"/> amount of data before returning, or throwing an exception.
  87. /// </summary>
  88. /// <param name="length">The amount wanted.</param>
  89. /// <param name="buffer">The buffer to read to.</param>
  90. /// <exception cref="SshConnectionException">Happens when the socket is closed.</exception>
  91. /// <exception cref="Exception">Unhandled exception.</exception>
  92. partial void SocketRead(int length, ref byte[] buffer)
  93. {
  94. var receivedTotal = 0; // how many bytes is already received
  95. do
  96. {
  97. try
  98. {
  99. var receivedBytes = this._socket.Receive(buffer, receivedTotal, length - receivedTotal, SocketFlags.None);
  100. if (receivedBytes > 0)
  101. {
  102. receivedTotal += receivedBytes;
  103. continue;
  104. }
  105. // 2012-09-11: Kenneth_aa
  106. // When Disconnect or Dispose is called, this throws SshConnectionException(), which...
  107. // 1 - goes up to ReceiveMessage()
  108. // 2 - up again to MessageListener()
  109. // which is where there is a catch-all exception block so it can notify event listeners.
  110. // 3 - MessageListener then again calls RaiseError().
  111. // There the exception is checked for the exception thrown here (ConnectionLost), and if it matches it will not call Session.SendDisconnect().
  112. //
  113. // Adding a check for this._isDisconnecting causes ReceiveMessage() to throw SshConnectionException: "Bad packet length {0}".
  114. //
  115. if (_isDisconnecting)
  116. throw new SshConnectionException("An established connection was aborted by the software in your host machine.", DisconnectReason.ConnectionLost);
  117. throw new SshConnectionException("An established connection was aborted by the server.", DisconnectReason.ConnectionLost);
  118. }
  119. catch (SocketException exp)
  120. {
  121. if (exp.SocketErrorCode == SocketError.ConnectionAborted)
  122. {
  123. buffer = new byte[length];
  124. this.Disconnect();
  125. return;
  126. }
  127. if (exp.SocketErrorCode == SocketError.WouldBlock ||
  128. exp.SocketErrorCode == SocketError.IOPending ||
  129. exp.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  130. {
  131. // socket buffer is probably empty, wait and try again
  132. Thread.Sleep(30);
  133. }
  134. else
  135. throw; // any serious error occurred
  136. }
  137. } while (receivedTotal < length);
  138. }
  139. partial void SocketWrite(byte[] data)
  140. {
  141. var sent = 0; // how many bytes is already sent
  142. var length = data.Length;
  143. do
  144. {
  145. try
  146. {
  147. sent += this._socket.Send(data, sent, length - sent, SocketFlags.None);
  148. }
  149. catch (SocketException ex)
  150. {
  151. if (ex.SocketErrorCode == SocketError.WouldBlock ||
  152. ex.SocketErrorCode == SocketError.IOPending ||
  153. ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  154. {
  155. // socket buffer is probably full, wait and try again
  156. Thread.Sleep(30);
  157. }
  158. else
  159. throw; // any serious error occurr
  160. }
  161. } while (sent < length);
  162. }
  163. [Conditional("DEBUG")]
  164. partial void Log(string text)
  165. {
  166. this._log.TraceEvent(TraceEventType.Verbose, 1, text);
  167. }
  168. }
  169. }