ChannelDirectTcpip.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. using Renci.SshNet.Common;
  7. using Renci.SshNet.Messages.Connection;
  8. namespace Renci.SshNet.Channels
  9. {
  10. /// <summary>
  11. /// Implements "direct-tcpip" SSH channel.
  12. /// </summary>
  13. internal partial class ChannelDirectTcpip : Channel
  14. {
  15. public EventWaitHandle _channelEof = new AutoResetEvent(false);
  16. private EventWaitHandle _channelOpen = new AutoResetEvent(false);
  17. private EventWaitHandle _channelData = new AutoResetEvent(false);
  18. private Socket _socket;
  19. /// <summary>
  20. /// Gets the type of the channel.
  21. /// </summary>
  22. /// <value>
  23. /// The type of the channel.
  24. /// </value>
  25. public override ChannelTypes ChannelType
  26. {
  27. get { return ChannelTypes.DirectTcpip; }
  28. }
  29. /// <summary>
  30. /// Initializes a new instance of the <see cref="ChannelDirectTcpip"/> class.
  31. /// </summary>
  32. public ChannelDirectTcpip()
  33. : base()
  34. {
  35. }
  36. public void Open(string remoteHost, uint port, Socket socket)
  37. {
  38. this._socket = socket;
  39. IPEndPoint ep = socket.RemoteEndPoint as IPEndPoint;
  40. if (!this.IsConnected)
  41. {
  42. throw new SshException("Session is not connected.");
  43. }
  44. // Open channel
  45. this.SendMessage(new ChannelOpenMessage(this.LocalChannelNumber, this.LocalWindowSize, this.PacketSize,
  46. new DirectTcpipChannelInfo(remoteHost, port, ep.Address.ToString(), (uint)ep.Port)));
  47. // Wait for channel to open
  48. this.WaitHandle(this._channelOpen);
  49. }
  50. /// <summary>
  51. /// Binds channel to specified remote host.
  52. /// </summary>
  53. /// <param name="remoteHost">The remote host.</param>
  54. /// <param name="port">The port.</param>
  55. /// <param name="socket">The socket.</param>
  56. public void Bind()
  57. {
  58. // Cannot bind if channel is not open
  59. if (!this.IsOpen)
  60. return;
  61. // Start reading data from the port and send to channel
  62. var readerTaskCompleted = new ManualResetEvent(false);
  63. Exception exception = null;
  64. this.ExecuteThread(() =>
  65. {
  66. try
  67. {
  68. var buffer = new byte[this.PacketSize - 9];
  69. while (this._socket.Connected || this.IsConnected)
  70. {
  71. try
  72. {
  73. var read = 0;
  74. this.InternalSocketReceive(buffer, ref read);
  75. if (read > 0)
  76. {
  77. this.SendMessage(new ChannelDataMessage(this.RemoteChannelNumber, buffer.Take(read).ToArray()));
  78. }
  79. else
  80. {
  81. break;
  82. }
  83. }
  84. catch (SocketException exp)
  85. {
  86. if (exp.SocketErrorCode == SocketError.WouldBlock ||
  87. exp.SocketErrorCode == SocketError.IOPending ||
  88. exp.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  89. {
  90. // socket buffer is probably empty, wait and try again
  91. Thread.Sleep(30);
  92. }
  93. else if (exp.SocketErrorCode == SocketError.ConnectionAborted || exp.SocketErrorCode == SocketError.ConnectionReset)
  94. {
  95. break;
  96. }
  97. else
  98. throw; // throw any other error
  99. }
  100. }
  101. }
  102. catch (Exception exp)
  103. {
  104. exception = exp;
  105. }
  106. finally
  107. {
  108. readerTaskCompleted.Set();
  109. }
  110. });
  111. // Channel was open and we MUST receive EOF notification,
  112. // data transfer can take longer then connection specified timeout
  113. // If listener thread is finished then socket was closed
  114. System.Threading.WaitHandle.WaitAny(new WaitHandle[] { this._channelEof, readerTaskCompleted });
  115. this._socket.Dispose();
  116. this._socket = null;
  117. if (exception != null)
  118. throw exception;
  119. }
  120. public override void Close()
  121. {
  122. // Send EOF message first when channel need to be closed
  123. this.SendMessage(new ChannelEofMessage(this.RemoteChannelNumber));
  124. base.Close();
  125. }
  126. /// <summary>
  127. /// Called when channel data is received.
  128. /// </summary>
  129. /// <param name="data">The data.</param>
  130. protected override void OnData(byte[] data)
  131. {
  132. base.OnData(data);
  133. this.InternalSocketSend(data);
  134. }
  135. /// <summary>
  136. /// Called when channel is opened by the server.
  137. /// </summary>
  138. /// <param name="remoteChannelNumber">The remote channel number.</param>
  139. /// <param name="initialWindowSize">Initial size of the window.</param>
  140. /// <param name="maximumPacketSize">Maximum size of the packet.</param>
  141. protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
  142. {
  143. base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
  144. this._channelOpen.Set();
  145. }
  146. protected override void OnOpenFailure(uint reasonCode, string description, string language)
  147. {
  148. base.OnOpenFailure(reasonCode, description, language);
  149. this._channelOpen.Set();
  150. }
  151. /// <summary>
  152. /// Called when channel has no more data to receive.
  153. /// </summary>
  154. protected override void OnEof()
  155. {
  156. base.OnEof();
  157. this._channelEof.Set();
  158. }
  159. protected override void OnClose()
  160. {
  161. base.OnClose();
  162. this._channelEof.Set();
  163. }
  164. partial void ExecuteThread(Action action);
  165. partial void InternalSocketReceive(byte[] buffer, ref int read);
  166. partial void InternalSocketSend(byte[] data);
  167. protected override void Dispose(bool disposing)
  168. {
  169. if (this._socket != null)
  170. {
  171. this._socket.Dispose();
  172. this._socket = null;
  173. }
  174. if (this._channelEof != null)
  175. {
  176. this._channelEof.Dispose();
  177. this._channelEof = null;
  178. }
  179. if (this._channelOpen != null)
  180. {
  181. this._channelOpen.Dispose();
  182. this._channelOpen = null;
  183. }
  184. if (this._channelData != null)
  185. {
  186. this._channelData.Dispose();
  187. this._channelData = null;
  188. }
  189. base.Dispose(disposing);
  190. }
  191. }
  192. }