ChannelDirectTcpip.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 : ClientChannel
  14. {
  15. private 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. {
  34. }
  35. public void Open(string remoteHost, uint port, Socket socket)
  36. {
  37. this._socket = socket;
  38. var ep = socket.RemoteEndPoint as IPEndPoint;
  39. if (!this.IsConnected)
  40. {
  41. throw new SshException("Session is not connected.");
  42. }
  43. // Open channel
  44. this.SendMessage(new ChannelOpenMessage(this.LocalChannelNumber, this.LocalWindowSize, this.LocalPacketSize,
  45. new DirectTcpipChannelInfo(remoteHost, port, ep.Address.ToString(), (uint)ep.Port)));
  46. // Wait for channel to open
  47. this.WaitOnHandle(this._channelOpen);
  48. }
  49. /// <summary>
  50. /// Binds channel to remote host.
  51. /// </summary>
  52. public void Bind()
  53. {
  54. // Cannot bind if channel is not open
  55. if (!this.IsOpen)
  56. return;
  57. // Start reading data from the port and send to channel
  58. Exception exception = null;
  59. try
  60. {
  61. var buffer = new byte[this.RemotePacketSize];
  62. while (this._socket != null && this._socket.CanRead())
  63. {
  64. try
  65. {
  66. var read = 0;
  67. this.InternalSocketReceive(buffer, ref read);
  68. if (read > 0)
  69. {
  70. this.SendMessage(new ChannelDataMessage(this.RemoteChannelNumber, buffer.Take(read).ToArray()));
  71. }
  72. else
  73. {
  74. break;
  75. }
  76. }
  77. catch (SocketException exp)
  78. {
  79. if (exp.SocketErrorCode == SocketError.WouldBlock ||
  80. exp.SocketErrorCode == SocketError.IOPending ||
  81. exp.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  82. {
  83. // socket buffer is probably empty, wait and try again
  84. Thread.Sleep(30);
  85. }
  86. else if (exp.SocketErrorCode == SocketError.ConnectionAborted || exp.SocketErrorCode == SocketError.ConnectionReset)
  87. {
  88. break;
  89. }
  90. else
  91. throw; // throw any other error
  92. }
  93. }
  94. }
  95. catch (Exception exp)
  96. {
  97. exception = exp;
  98. }
  99. // Channel was open and we MUST receive EOF notification,
  100. // data transfer can take longer than connection specified timeout
  101. // If listener thread is finished then socket was closed
  102. WaitHandle.WaitAny(new WaitHandle[] {_channelEof});
  103. // Close socket if still open
  104. if (this._socket != null)
  105. {
  106. this._socket.Dispose();
  107. this._socket = null;
  108. }
  109. if (exception != null)
  110. throw exception;
  111. }
  112. public override void Close()
  113. {
  114. // Close socket if still open
  115. if (this._socket != null)
  116. {
  117. this._socket.Dispose();
  118. this._socket = null;
  119. }
  120. // Send EOF message first when channel need to be closed
  121. this.SendMessage(new ChannelEofMessage(this.RemoteChannelNumber));
  122. base.Close();
  123. }
  124. /// <summary>
  125. /// Called when channel data is received.
  126. /// </summary>
  127. /// <param name="data">The data.</param>
  128. protected override void OnData(byte[] data)
  129. {
  130. base.OnData(data);
  131. this.InternalSocketSend(data);
  132. }
  133. /// <summary>
  134. /// Called when channel is opened by the server.
  135. /// </summary>
  136. /// <param name="remoteChannelNumber">The remote channel number.</param>
  137. /// <param name="initialWindowSize">Initial size of the window.</param>
  138. /// <param name="maximumPacketSize">Maximum size of the packet.</param>
  139. protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
  140. {
  141. base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
  142. this._channelOpen.Set();
  143. }
  144. protected override void OnOpenFailure(uint reasonCode, string description, string language)
  145. {
  146. base.OnOpenFailure(reasonCode, description, language);
  147. this._channelOpen.Set();
  148. }
  149. /// <summary>
  150. /// Called when channel has no more data to receive.
  151. /// </summary>
  152. protected override void OnEof() {
  153. base.OnEof();
  154. var channelEof = this._channelEof;
  155. if (channelEof != null)
  156. channelEof.Set();
  157. }
  158. protected override void OnClose()
  159. {
  160. base.OnClose();
  161. var channelEof = this._channelEof;
  162. if (channelEof != null)
  163. channelEof.Set();
  164. }
  165. protected override void OnErrorOccured(Exception exp)
  166. {
  167. base.OnErrorOccured(exp);
  168. // If error occured, no more data can be received
  169. var channelEof = this._channelEof;
  170. if (channelEof != null)
  171. channelEof.Set();
  172. }
  173. protected override void OnDisconnected()
  174. {
  175. base.OnDisconnected();
  176. // If disconnected, no more data can be received
  177. var channelEof = this._channelEof;
  178. if (channelEof != null)
  179. channelEof.Set();
  180. }
  181. partial void ExecuteThread(Action action);
  182. partial void InternalSocketReceive(byte[] buffer, ref int read);
  183. partial void InternalSocketSend(byte[] data);
  184. protected override void Dispose(bool disposing)
  185. {
  186. if (this._socket != null)
  187. {
  188. this._socket.Dispose();
  189. this._socket = null;
  190. }
  191. if (this._channelEof != null)
  192. {
  193. this._channelEof.Dispose();
  194. this._channelEof = null;
  195. }
  196. if (this._channelOpen != null)
  197. {
  198. this._channelOpen.Dispose();
  199. this._channelOpen = null;
  200. }
  201. if (this._channelData != null)
  202. {
  203. this._channelData.Dispose();
  204. this._channelData = null;
  205. }
  206. base.Dispose(disposing);
  207. }
  208. }
  209. }