Session.NET.cs 8.1 KB

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