2
0

Session.NET.cs 7.0 KB

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