Session.NET.cs 7.5 KB

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