Session.NET.cs 7.8 KB

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