ChannelDirectTcpip.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 = this._socket.Receive(buffer);
  69. if (read > 0)
  70. {
  71. this.SendMessage(new ChannelDataMessage(this.RemoteChannelNumber, buffer.Take(read).ToArray()));
  72. }
  73. else
  74. {
  75. break;
  76. }
  77. }
  78. catch (SocketException exp)
  79. {
  80. if (exp.SocketErrorCode == SocketError.WouldBlock ||
  81. exp.SocketErrorCode == SocketError.IOPending ||
  82. exp.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  83. {
  84. // socket buffer is probably empty, wait and try again
  85. Thread.Sleep(30);
  86. }
  87. else if (exp.SocketErrorCode == SocketError.ConnectionAborted)
  88. {
  89. break;
  90. }
  91. else
  92. throw; // throw any other error
  93. }
  94. }
  95. }
  96. catch (Exception exp)
  97. {
  98. readerTaskError.Set();
  99. exception = exp;
  100. }
  101. finally
  102. {
  103. readerTaskCompleted.Set();
  104. }
  105. });
  106. // Channel was open and we MUST receive EOF notification,
  107. // data transfer can take longer then connection specified timeout
  108. System.Threading.WaitHandle.WaitAny(new WaitHandle[] { this._channelEof, readerTaskError });
  109. this._socket.Dispose();
  110. this._socket = null;
  111. // Wait for task to finish and will throw any errors if any
  112. readerTaskCompleted.WaitOne();
  113. if (exception != null)
  114. throw exception;
  115. }
  116. /// <summary>
  117. /// Called when channel data is received.
  118. /// </summary>
  119. /// <param name="data">The data.</param>
  120. protected override void OnData(byte[] data)
  121. {
  122. base.OnData(data);
  123. this._socket.Send(data, 0, data.Length, SocketFlags.None);
  124. }
  125. /// <summary>
  126. /// Called when channel is opened by the server.
  127. /// </summary>
  128. /// <param name="remoteChannelNumber">The remote channel number.</param>
  129. /// <param name="initialWindowSize">Initial size of the window.</param>
  130. /// <param name="maximumPacketSize">Maximum size of the packet.</param>
  131. protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
  132. {
  133. base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
  134. this._channelOpen.Set();
  135. }
  136. /// <summary>
  137. /// Called when channel has no more data to receive.
  138. /// </summary>
  139. protected override void OnEof()
  140. {
  141. base.OnEof();
  142. this._channelEof.Set();
  143. }
  144. partial void ExecuteThread(Action action);
  145. protected override void Dispose(bool disposing)
  146. {
  147. if (this._socket != null)
  148. {
  149. this._socket.Dispose();
  150. this._socket = null;
  151. }
  152. if (this._channelEof != null)
  153. {
  154. this._channelEof.Dispose();
  155. this._channelEof = null;
  156. }
  157. if (this._channelOpen != null)
  158. {
  159. this._channelOpen.Dispose();
  160. this._channelOpen = null;
  161. }
  162. if (this._channelData != null)
  163. {
  164. this._channelData.Dispose();
  165. this._channelData = null;
  166. }
  167. base.Dispose(disposing);
  168. }
  169. }
  170. }