| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252 | using System;using System.Linq;using System.Net;using System.Net.Sockets;using System.Threading;using Renci.SshNet.Common;using Renci.SshNet.Messages.Connection;namespace Renci.SshNet.Channels{    /// <summary>    /// Implements "direct-tcpip" SSH channel.    /// </summary>    internal partial class ChannelDirectTcpip : Channel    {        public EventWaitHandle _channelEof = new AutoResetEvent(false);        private EventWaitHandle _channelOpen = new AutoResetEvent(false);        private EventWaitHandle _channelData = new AutoResetEvent(false);        private Socket _socket;        /// <summary>        /// Gets the type of the channel.        /// </summary>        /// <value>        /// The type of the channel.        /// </value>        public override ChannelTypes ChannelType        {            get { return ChannelTypes.DirectTcpip; }        }        /// <summary>        /// Initializes a new instance of the <see cref="ChannelDirectTcpip"/> class.        /// </summary>        public ChannelDirectTcpip()        {        }        public void Open(string remoteHost, uint port, Socket socket)        {            this._socket = socket;            var ep = socket.RemoteEndPoint as IPEndPoint;            if (!this.IsConnected)            {                throw new SshException("Session is not connected.");            }            //  Open channel            this.SendMessage(new ChannelOpenMessage(this.LocalChannelNumber, this.LocalWindowSize, this.PacketSize,                                                        new DirectTcpipChannelInfo(remoteHost, port, ep.Address.ToString(), (uint)ep.Port)));            //  Wait for channel to open            this.WaitHandle(this._channelOpen);        }        /// <summary>        /// Binds channel to remote host.        /// </summary>        public void Bind()        {            //  Cannot bind if channel is not open            if (!this.IsOpen)                return;            //  Start reading data from the port and send to channel            Exception exception = null;            try            {                var buffer = new byte[this.PacketSize - 9];                while (this._socket != null && this._socket.CanRead())                {                    try                    {                        var read = 0;                        this.InternalSocketReceive(buffer, ref read);                        if (read > 0)                        {                            this.SendMessage(new ChannelDataMessage(this.RemoteChannelNumber, buffer.Take(read).ToArray()));                        }                        else                        {                            break;                        }                    }                    catch (SocketException exp)                    {                        if (exp.SocketErrorCode == SocketError.WouldBlock ||                            exp.SocketErrorCode == SocketError.IOPending ||                            exp.SocketErrorCode == SocketError.NoBufferSpaceAvailable)                        {                            // socket buffer is probably empty, wait and try again                            Thread.Sleep(30);                        }                        else if (exp.SocketErrorCode == SocketError.ConnectionAborted || exp.SocketErrorCode == SocketError.ConnectionReset)                        {                            break;                        }                        else                            throw;  // throw any other error                    }                }            }            catch (Exception exp)            {                exception = exp;            }            //  Channel was open and we MUST receive EOF notification,             //  data transfer can take longer then connection specified timeout            //  If listener thread is finished then socket was closed            System.Threading.WaitHandle.WaitAny(new WaitHandle[] { this._channelEof });            //  Close socket if still open            if (this._socket != null)            {                this._socket.Dispose();                this._socket = null;            }            if (exception != null)                throw exception;        }        public override void Close()        {            //  Close socket if still open            if (this._socket != null)            {                this._socket.Dispose();                this._socket = null;            }            //  Send EOF message first when channel need to be closed            this.SendMessage(new ChannelEofMessage(this.RemoteChannelNumber));            base.Close();        }        /// <summary>        /// Called when channel data is received.        /// </summary>        /// <param name="data">The data.</param>        protected override void OnData(byte[] data)        {            base.OnData(data);            this.InternalSocketSend(data);        }        /// <summary>        /// Called when channel is opened by the server.        /// </summary>        /// <param name="remoteChannelNumber">The remote channel number.</param>        /// <param name="initialWindowSize">Initial size of the window.</param>        /// <param name="maximumPacketSize">Maximum size of the packet.</param>        protected override void OnOpenConfirmation(uint remoteChannelNumber, uint initialWindowSize, uint maximumPacketSize)        {            base.OnOpenConfirmation(remoteChannelNumber, initialWindowSize, maximumPacketSize);            this._channelOpen.Set();        }        protected override void OnOpenFailure(uint reasonCode, string description, string language)        {            base.OnOpenFailure(reasonCode, description, language);            this._channelOpen.Set();        }        /// <summary>        /// Called when channel has no more data to receive.        /// </summary>        protected override void OnEof() {	        base.OnEof();            EventWaitHandle channelEof = this._channelEof;            if (channelEof != null)                channelEof.Set();        }        protected override void OnClose()        {            base.OnClose();            EventWaitHandle channelEof = this._channelEof;            if (channelEof != null)                channelEof.Set();        }        protected override void OnErrorOccured(Exception exp)        {            base.OnErrorOccured(exp);            //  If error occured, no more data can be received            EventWaitHandle channelEof = this._channelEof;            if (channelEof != null)                channelEof.Set();        }        protected override void OnDisconnected()        {            base.OnDisconnected();            //  If disconnected, no more data can be received            EventWaitHandle channelEof = this._channelEof;            if (channelEof != null)                channelEof.Set();        }        partial void ExecuteThread(Action action);        partial void InternalSocketReceive(byte[] buffer, ref int read);        partial void InternalSocketSend(byte[] data);        protected override void Dispose(bool disposing)        {            if (this._socket != null)            {                this._socket.Dispose();                this._socket = null;            }            if (this._channelEof != null)            {                this._channelEof.Dispose();                this._channelEof = null;            }            if (this._channelOpen != null)            {                this._channelOpen.Dispose();                this._channelOpen = null;            }            if (this._channelData != null)            {                this._channelData.Dispose();                this._channelData = null;            }            base.Dispose(disposing);        }    }}
 |