ChannelDirectTcpip.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 remote host.
  52. /// </summary>
  53. public void Bind()
  54. {
  55. // Cannot bind if channel is not open
  56. if (!this.IsOpen)
  57. return;
  58. // Start reading data from the port and send to channel
  59. var readerTaskCompleted = new ManualResetEvent(false);
  60. Exception exception = null;
  61. this.ExecuteThread(() =>
  62. {
  63. try
  64. {
  65. var buffer = new byte[this.PacketSize - 9];
  66. while (this._socket.Connected || this.IsConnected)
  67. {
  68. try
  69. {
  70. var read = 0;
  71. this.InternalSocketReceive(buffer, ref read);
  72. if (read > 0)
  73. {
  74. this.SendMessage(new ChannelDataMessage(this.RemoteChannelNumber, buffer.Take(read).ToArray()));
  75. }
  76. else
  77. {
  78. break;
  79. }
  80. }
  81. catch (SocketException exp)
  82. {
  83. if (exp.SocketErrorCode == SocketError.WouldBlock ||
  84. exp.SocketErrorCode == SocketError.IOPending ||
  85. exp.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  86. {
  87. // socket buffer is probably empty, wait and try again
  88. Thread.Sleep(30);
  89. }
  90. else if (exp.SocketErrorCode == SocketError.ConnectionAborted || exp.SocketErrorCode == SocketError.ConnectionReset)
  91. {
  92. break;
  93. }
  94. else
  95. throw; // throw any other error
  96. }
  97. }
  98. }
  99. catch (Exception exp)
  100. {
  101. exception = exp;
  102. }
  103. finally
  104. {
  105. readerTaskCompleted.Set();
  106. }
  107. });
  108. // Channel was open and we MUST receive EOF notification,
  109. // data transfer can take longer then connection specified timeout
  110. // If listener thread is finished then socket was closed
  111. System.Threading.WaitHandle.WaitAny(new WaitHandle[] { this._channelEof, readerTaskCompleted });
  112. this._socket.Dispose();
  113. this._socket = null;
  114. if (exception != null)
  115. throw exception;
  116. }
  117. public override void Close()
  118. {
  119. // Send EOF message first when channel need to be closed
  120. this.SendMessage(new ChannelEofMessage(this.RemoteChannelNumber));
  121. base.Close();
  122. }
  123. /// <summary>
  124. /// Called when channel data is received.
  125. /// </summary>
  126. /// <param name="data">The data.</param>
  127. protected override void OnData(byte[] data)
  128. {
  129. base.OnData(data);
  130. this.InternalSocketSend(data);
  131. }
  132. /// <summary>
  133. /// Called when channel is opened by the server.
  134. /// </summary>
  135. /// <param name="remoteChannelNumber">The remote channel number.</param>
  136. /// <param name="initialWindowSize">Initial size of the window.</param>
  137. /// <param name="maximumPacketSize">Maximum size of the packet.</param>
  138. protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
  139. {
  140. base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
  141. this._channelOpen.Set();
  142. }
  143. protected override void OnOpenFailure(uint reasonCode, string description, string language)
  144. {
  145. base.OnOpenFailure(reasonCode, description, language);
  146. this._channelOpen.Set();
  147. }
  148. /// <summary>
  149. /// Called when channel has no more data to receive.
  150. /// </summary>
  151. protected override void OnEof()
  152. {
  153. base.OnEof();
  154. this._channelEof.Set();
  155. }
  156. protected override void OnClose()
  157. {
  158. base.OnClose();
  159. this._channelEof.Set();
  160. }
  161. partial void ExecuteThread(Action action);
  162. partial void InternalSocketReceive(byte[] buffer, ref int read);
  163. partial void InternalSocketSend(byte[] data);
  164. protected override void Dispose(bool disposing)
  165. {
  166. if (this._socket != null)
  167. {
  168. this._socket.Dispose();
  169. this._socket = null;
  170. }
  171. if (this._channelEof != null)
  172. {
  173. this._channelEof.Dispose();
  174. this._channelEof = null;
  175. }
  176. if (this._channelOpen != null)
  177. {
  178. this._channelOpen.Dispose();
  179. this._channelOpen = null;
  180. }
  181. if (this._channelData != null)
  182. {
  183. this._channelData.Dispose();
  184. this._channelData = null;
  185. }
  186. base.Dispose(disposing);
  187. }
  188. }
  189. }