Session.NET.cs 7.6 KB

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