ChannelDirectTcpip.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Renci.SshClient.Common;
  8. using Renci.SshClient.Messages.Connection;
  9. namespace Renci.SshClient.Channels
  10. {
  11. /// <summary>
  12. /// Implements "direct-tcpip" SSH channel.
  13. /// </summary>
  14. internal class ChannelDirectTcpip : Channel
  15. {
  16. public EventWaitHandle _channelEof = new AutoResetEvent(false);
  17. private EventWaitHandle _channelOpen = new AutoResetEvent(false);
  18. private EventWaitHandle _channelData = new AutoResetEvent(false);
  19. private Socket _socket;
  20. /// <summary>
  21. /// Gets the type of the channel.
  22. /// </summary>
  23. /// <value>
  24. /// The type of the channel.
  25. /// </value>
  26. public override ChannelTypes ChannelType
  27. {
  28. get { return ChannelTypes.DirectTcpip; }
  29. }
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="ChannelDirectTcpip"/> class.
  32. /// </summary>
  33. public ChannelDirectTcpip()
  34. : base()
  35. {
  36. }
  37. /// <summary>
  38. /// Binds channel to specified remote host.
  39. /// </summary>
  40. /// <param name="remoteHost">The remote host.</param>
  41. /// <param name="port">The port.</param>
  42. /// <param name="socket">The socket.</param>
  43. public void Bind(string remoteHost, uint port, Socket socket)
  44. {
  45. this._socket = socket;
  46. IPEndPoint ep = socket.RemoteEndPoint as IPEndPoint;
  47. if (!this.IsConnected)
  48. {
  49. throw new SshException("Session is not connected.");
  50. }
  51. // Open channel
  52. this.SendMessage(new ChannelOpenMessage(this.LocalChannelNumber, this.LocalWindowSize, this.PacketSize,
  53. new DirectTcpipChannelInfo(remoteHost, port, ep.Address.ToString(), (uint)ep.Port)));
  54. // Wait for channel to open
  55. this.WaitHandle(this._channelOpen);
  56. // Start reading data from the port and send to channel
  57. EventWaitHandle readerTaskError = new AutoResetEvent(false);
  58. var readerTask = Task.Factory.StartNew(() =>
  59. {
  60. try
  61. {
  62. var buffer = new byte[this.PacketSize - 9];
  63. while (this._socket.Connected || this.IsConnected)
  64. {
  65. try
  66. {
  67. var read = this._socket.Receive(buffer);
  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)
  87. {
  88. break;
  89. }
  90. else
  91. throw; // throw any other error
  92. }
  93. }
  94. }
  95. catch (Exception)
  96. {
  97. readerTaskError.Set();
  98. throw;
  99. }
  100. });
  101. // Channel was open and we MUST receive EOF notification,
  102. // data transfer can take longer then connection specified timeout
  103. System.Threading.WaitHandle.WaitAny(new WaitHandle[] { this._channelEof, readerTaskError });
  104. this._socket.Dispose();
  105. this._socket = null;
  106. // Wait for task to finish and will throw any errors if any
  107. readerTask.Wait();
  108. }
  109. /// <summary>
  110. /// Called when channel data is received.
  111. /// </summary>
  112. /// <param name="data">The data.</param>
  113. protected override void OnData(byte[] data)
  114. {
  115. base.OnData(data);
  116. this._socket.Send(data, 0, data.Length, SocketFlags.None);
  117. }
  118. /// <summary>
  119. /// Called when channel is opened by the server.
  120. /// </summary>
  121. /// <param name="remoteChannelNumber">The remote channel number.</param>
  122. /// <param name="initialWindowSize">Initial size of the window.</param>
  123. /// <param name="maximumPacketSize">Maximum size of the packet.</param>
  124. protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)
  125. {
  126. base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);
  127. this._channelOpen.Set();
  128. }
  129. /// <summary>
  130. /// Called when channel has no more data to receive.
  131. /// </summary>
  132. protected override void OnEof()
  133. {
  134. base.OnEof();
  135. this._channelEof.Set();
  136. }
  137. protected override void Dispose(bool disposing)
  138. {
  139. if (this._socket != null)
  140. {
  141. this._socket.Dispose();
  142. this._socket = null;
  143. }
  144. if (this._channelEof != null)
  145. {
  146. this._channelEof.Dispose();
  147. this._channelEof = null;
  148. }
  149. if (this._channelOpen != null)
  150. {
  151. this._channelOpen.Dispose();
  152. this._channelOpen = null;
  153. }
  154. if (this._channelData != null)
  155. {
  156. this._channelData.Dispose();
  157. this._channelData = null;
  158. }
  159. base.Dispose(disposing);
  160. }
  161. }
  162. }