ChannelDirectTcpip.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. /// <summary>
  37. /// Binds channel to specified remote host.
  38. /// </summary>
  39. /// <param name="remoteHost">The remote host.</param>
  40. /// <param name="port">The port.</param>
  41. /// <param name="socket">The socket.</param>
  42. public void Bind(string remoteHost, uint port, Socket socket)
  43. {
  44. this._socket = socket;
  45. IPEndPoint ep = socket.RemoteEndPoint as IPEndPoint;
  46. if (!this.IsConnected)
  47. {
  48. throw new SshException("Session is not connected.");
  49. }
  50. // Open channel
  51. this.SendMessage(new ChannelOpenMessage(this.LocalChannelNumber, this.LocalWindowSize, this.PacketSize,
  52. new DirectTcpipChannelInfo(remoteHost, port, ep.Address.ToString(), (uint)ep.Port)));
  53. // Wait for channel to open
  54. this.WaitHandle(this._channelOpen);
  55. // Start reading data from the port and send to channel
  56. EventWaitHandle readerTaskError = new AutoResetEvent(false);
  57. var readerTaskCompleted = new ManualResetEvent(false);
  58. Exception exception = null;
  59. this.ExecuteThread(() =>
  60. {
  61. try
  62. {
  63. var buffer = new byte[this.PacketSize - 9];
  64. while (this._socket.Connected || this.IsConnected)
  65. {
  66. try
  67. {
  68. var read = 0;
  69. this.InternalSocketReceive(buffer, ref read);
  70. if (read > 0)
  71. {
  72. this.SendMessage(new ChannelDataMessage(this.RemoteChannelNumber, buffer.Take(read).ToArray()));
  73. }
  74. else
  75. {
  76. break;
  77. }
  78. }
  79. catch (SocketException exp)
  80. {
  81. if (exp.SocketErrorCode == SocketError.WouldBlock ||
  82. exp.SocketErrorCode == SocketError.IOPending ||
  83. exp.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  84. {
  85. // socket buffer is probably empty, wait and try again
  86. Thread.Sleep(30);
  87. }
  88. else if (exp.SocketErrorCode == SocketError.ConnectionAborted)
  89. {
  90. break;
  91. }
  92. else
  93. throw; // throw any other error
  94. }
  95. }
  96. }
  97. catch (Exception exp)
  98. {
  99. readerTaskError.Set();
  100. exception = exp;
  101. }
  102. finally
  103. {
  104. readerTaskCompleted.Set();
  105. }
  106. });
  107. // Channel was open and we MUST receive EOF notification,
  108. // data transfer can take longer then connection specified timeout
  109. System.Threading.WaitHandle.WaitAny(new WaitHandle[] { this._channelEof, readerTaskError });
  110. this._socket.Dispose();
  111. this._socket = null;
  112. // Wait for task to finish and will throw any errors if any
  113. readerTaskCompleted.WaitOne();
  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. /// <summary>
  144. /// Called when channel has no more data to receive.
  145. /// </summary>
  146. protected override void OnEof()
  147. {
  148. base.OnEof();
  149. this._channelEof.Set();
  150. }
  151. partial void ExecuteThread(Action action);
  152. partial void InternalSocketReceive(byte[] buffer, ref int read);
  153. partial void InternalSocketSend(byte[] data);
  154. protected override void Dispose(bool disposing)
  155. {
  156. if (this._socket != null)
  157. {
  158. this._socket.Dispose();
  159. this._socket = null;
  160. }
  161. if (this._channelEof != null)
  162. {
  163. this._channelEof.Dispose();
  164. this._channelEof = null;
  165. }
  166. if (this._channelOpen != null)
  167. {
  168. this._channelOpen.Dispose();
  169. this._channelOpen = null;
  170. }
  171. if (this._channelData != null)
  172. {
  173. this._channelData.Dispose();
  174. this._channelData = null;
  175. }
  176. base.Dispose(disposing);
  177. }
  178. }
  179. }