Ejemplo n.º 1
0
        partial void InternalStart()
        {
            InitializePendingChannelCountdown();

            var ip = IPAddress.Any;

            if (!string.IsNullOrEmpty(BoundHost))
            {
                ip = DnsAbstraction.GetHostAddresses(BoundHost)[0];
            }

            var ep = new IPEndPoint(ip, (int)BoundPort);

            _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay = true
            };
            _listener.Bind(ep);
            _listener.Listen(5);

            Session.ErrorOccured += Session_ErrorOccured;
            Session.Disconnected += Session_Disconnected;

            // consider port started when we're listening for inbound connections
            _status = ForwardedPortStatus.Started;

            StartAccept(null);
        }
Ejemplo n.º 2
0
        partial void InternalStart()
        {
            var addr = DnsAbstraction.GetHostAddresses(BoundHost)[0];
            var ep   = new IPEndPoint(addr, (int)BoundPort);

            _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay = true
            };
            _listener.Bind(ep);
            _listener.Listen(5);

            // update bound port (in case original was passed as zero)
            BoundPort = (uint)((IPEndPoint)_listener.LocalEndPoint).Port;

            Session.ErrorOccured += Session_ErrorOccured;
            Session.Disconnected += Session_Disconnected;

            InitializePendingChannelCountdown();

            // consider port started when we're listening for inbound connections
            _status = ForwardedPortStatus.Started;

            StartAccept(null);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ForwardedPortRemote"/> class.
 /// </summary>
 /// <param name="boundHost">The bound host.</param>
 /// <param name="boundPort">The bound port.</param>
 /// <param name="host">The host.</param>
 /// <param name="port">The port.</param>
 public ForwardedPortRemote(string boundHost, uint boundPort, string host, uint port)
     : this(DnsAbstraction.GetHostAddresses(boundHost)[0],
            boundPort,
            DnsAbstraction.GetHostAddresses(host)[0],
            port)
 {
 }
Ejemplo n.º 4
0
        partial void InternalStart()
        {
            var addr = DnsAbstraction.GetHostAddresses(BoundHost)[0];
            var ep   = new IPEndPoint(addr, (int)BoundPort);

            _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            // TODO: decide if we want to have blocking socket
#if FEATURE_SOCKET_SETSOCKETOPTION
            _listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
#endif // FEATURE_SOCKET_SETSOCKETOPTION
            _listener.Bind(ep);
            _listener.Listen(1);

            // update bound port (in case original was passed as zero)
            BoundPort = (uint)((IPEndPoint)_listener.LocalEndPoint).Port;

            Session.ErrorOccured += Session_ErrorOccured;
            Session.Disconnected += Session_Disconnected;

            _listenerTaskCompleted = new ManualResetEvent(false);

            ThreadAbstraction.ExecuteThread(() =>
            {
                try
                {
#if FEATURE_SOCKET_EAP
                    _stoppingListener = new ManualResetEvent(false);
                    StartAccept();
                    _stoppingListener.WaitOne();
#elif FEATURE_SOCKET_APM
                    while (true)
                    {
                        // accept new inbound connection
                        var asyncResult = _listener.BeginAccept(AcceptCallback, _listener);
                        // wait for the connection to be established
                        asyncResult.AsyncWaitHandle.WaitOne();
                    }
#elif FEATURE_SOCKET_TAP
#error Accepting new socket connections is not implemented.
#else
#error Accepting new socket connections is not implemented.
#endif
                }
                catch (ObjectDisposedException)
                {
                    // BeginAccept will throw an ObjectDisposedException when the
                    // socket is closed
                }
                catch (Exception ex)
                {
                    RaiseExceptionEvent(ex);
                }
                finally
                {
                    // mark listener stopped
                    _listenerTaskCompleted.Set();
                }
            });
        }
        public void ShouldReturnSingleIpv6AddressWhenHostNameOrAddressIsValidIpv6Address()
        {
            const string hostNameOrAddress = "2001:0:9d38:90d7:384f:2133:ab3d:d152";

            var addresses = DnsAbstraction.GetHostAddresses(hostNameOrAddress);

            Assert.IsNotNull(addresses);
            Assert.AreEqual(1, addresses.Length);
            Assert.AreEqual(AddressFamily.InterNetworkV6, addresses[0].AddressFamily);
            Assert.AreEqual(IPAddress.Parse(hostNameOrAddress), addresses[0]);
        }
        public void ShouldReturnSingleIpv4AddressWhenHostNameOrAddressIsValidIpv4Address()
        {
            const string hostNameOrAddress = "1.2.3.4";

            var addresses = DnsAbstraction.GetHostAddresses(hostNameOrAddress);

            Assert.IsNotNull(addresses);
            Assert.AreEqual(1, addresses.Length);
            Assert.AreEqual(AddressFamily.InterNetwork, addresses[0].AddressFamily);
            Assert.AreEqual(IPAddress.Parse(hostNameOrAddress), addresses[0]);
        }
        public void ShouldThrowArgumentNullExceptionWhenHostNameOrAddressIsNull()
        {
            const string hostNameOrAddress = null;

            try
            {
                DnsAbstraction.GetHostAddresses(hostNameOrAddress);
                Assert.Fail();
            }
            catch (ArgumentNullException)
            {
            }
        }
Ejemplo n.º 8
0
        private static byte[] GetSocks4DestinationAddress(string hostname)
        {
            var addresses = DnsAbstraction.GetHostAddresses(hostname);

            for (var i = 0; i < addresses.Length; i++)
            {
                var address = addresses[i];
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    return(address.GetAddressBytes());
                }
            }

            throw new ProxyException(string.Format("SOCKS4 only supports IPv4. No such address found for '{0}'.", hostname));
        }
        public void ShouldThrowSocketExceptionWhenHostIsNotFound()
        {
            const string hostNameOrAddress = "surelydoesnotexist.OrAmIWrong";

            try
            {
                var addresses = DnsAbstraction.GetHostAddresses(hostNameOrAddress);
                Assert.Fail(addresses.ToString());
            }
            catch (SocketException ex)
            {
                Assert.IsNull(ex.InnerException);
                Assert.AreEqual(SocketError.HostNotFound, ex.SocketErrorCode);
            }
        }
        public void ShouldThrowArgumentNullExceptionWhenHostNameOrAddressIsNull()
        {
            const string hostNameOrAddress = null;

            try
            {
                DnsAbstraction.GetHostAddresses(hostNameOrAddress);
                Assert.Fail();
            }
            catch (ArgumentNullException ex)
            {
                Assert.IsNull(ex.InnerException);
                Assert.AreEqual("hostNameOrAddress", ex.ParamName);
            }
        }
        public void ShouldReturnHostAddressesOfLocalHostWhenHostNameOrAddressIsEmpty()
        {
            const string hostNameOrAddress = "";

            var addresses = DnsAbstraction.GetHostAddresses(hostNameOrAddress);

            Assert.IsNotNull(addresses);

#if !SILVERLIGHT
            var hostEntry = Dns.GetHostEntry(Dns.GetHostName());
            Assert.IsNotNull(hostEntry);

            Assert.AreEqual(hostEntry.AddressList.Length, addresses.Length);
            for (var i = 0; i < hostEntry.AddressList.Length; i++)
            {
                Assert.AreEqual(hostEntry.AddressList[i], addresses[i]);
            }
#endif
        }
Ejemplo n.º 12
0
        private static byte[] GetSocks5DestinationAddress(string hostname, out byte addressType)
        {
            var ip = DnsAbstraction.GetHostAddresses(hostname)[0];

            byte[] address;

            switch (ip.AddressFamily)
            {
            case AddressFamily.InterNetwork:
                addressType = 0x01;     // IPv4
                address     = ip.GetAddressBytes();
                break;

            case AddressFamily.InterNetworkV6:
                addressType = 0x04;     // IPv6
                address     = ip.GetAddressBytes();
                break;

            default:
                throw new ProxyException(string.Format("SOCKS5: IP address '{0}' is not supported.", ip));
            }

            return(address);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Establishes a socket connection to the specified host and port.
        /// </summary>
        /// <param name="host">The host name of the server to connect to.</param>
        /// <param name="port">The port to connect to.</param>
        /// <param name="timeout">The maximum time to wait for the connection to be established.</param>
        /// <exception cref="SshOperationTimeoutException">The connection failed to establish within the configured <see cref="ConnectionInfo.Timeout"/>.</exception>
        /// <exception cref="SocketException">An error occurred trying to establish the connection.</exception>
        protected Socket SocketConnect(string host, int port, TimeSpan timeout)
        {
            var ipAddress = DnsAbstraction.GetHostAddresses(host)[0];
            var ep        = new IPEndPoint(ipAddress, port);

            DiagnosticAbstraction.Log(string.Format("Initiating connection to '{0}:{1}'.", host, port));

            var socket = SocketFactory.Create(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                SocketAbstraction.Connect(socket, ep, timeout);

                const int socketBufferSize = 2 * Session.MaximumSshPacketSize;
                socket.SendBufferSize    = socketBufferSize;
                socket.ReceiveBufferSize = socketBufferSize;
                return(socket);
            }
            catch (Exception)
            {
                socket.Dispose();
                throw;
            }
        }
Ejemplo n.º 14
0
        partial void InternalStart()
        {
            var ip = IPAddress.Any;

            if (!string.IsNullOrEmpty(BoundHost))
            {
                ip = DnsAbstraction.GetHostAddresses(BoundHost)[0];
            }

            var ep = new IPEndPoint(ip, (int)BoundPort);

            _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            // TODO: decide if we want to have blocking socket
#if FEATURE_SOCKET_SETSOCKETOPTION
            _listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
            _listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
#endif //FEATURE_SOCKET_SETSOCKETOPTION
            _listener.Bind(ep);
            _listener.Listen(5);

            Session.ErrorOccured += Session_ErrorOccured;
            Session.Disconnected += Session_Disconnected;

            _listenerCompleted = new ManualResetEvent(false);

            ThreadAbstraction.ExecuteThread(() =>
            {
                try
                {
#if FEATURE_SOCKET_EAP
                    _stoppingListener = new ManualResetEvent(false);

                    StartAccept();

                    _stoppingListener.WaitOne();
#elif FEATURE_SOCKET_APM
                    while (true)
                    {
                        // accept new inbound connection
                        var asyncResult = _listener.BeginAccept(AcceptCallback, _listener);
                        // wait for the connection to be established
                        asyncResult.AsyncWaitHandle.WaitOne();
                    }
                }
                catch (ObjectDisposedException)
                {
                    // BeginAccept will throw an ObjectDisposedException when the
                    // socket is closed
#elif FEATURE_SOCKET_TAP
#error Accepting new socket connections is not implemented.
#else
#error Accepting new socket connections is not implemented.
#endif
                }
                catch (Exception ex)
                {
                    RaiseExceptionEvent(ex);
                }
                finally
                {
                    if (Session != null)
                    {
                        Session.ErrorOccured -= Session_ErrorOccured;
                        Session.Disconnected -= Session_Disconnected;
                    }

                    // mark listener stopped
                    _listenerCompleted.Set();
                }
            });
        }
Ejemplo n.º 15
0
        partial void InternalStart()
        {
            var ip = IPAddress.Any;

            if (!string.IsNullOrEmpty(BoundHost))
            {
                ip = DnsAbstraction.GetHostAddresses(BoundHost)[0];
            }

            var ep = new IPEndPoint(ip, (int)BoundPort);

            _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            // TODO: decide if we want to have blocking socket
#if FEATURE_SOCKET_SETSOCKETOPTION
            _listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
            _listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
#endif //FEATURE_SOCKET_SETSOCKETOPTION
            _listener.Bind(ep);
            _listener.Listen(5);

            Session.ErrorOccured += Session_ErrorOccured;
            Session.Disconnected += Session_Disconnected;

            _listenerCompleted = new ManualResetEvent(false);

            ThreadAbstraction.ExecuteThread(() =>
            {
                try
                {
#if FEATURE_SOCKET_EAP
                    StartAccept();
#elif FEATURE_SOCKET_APM
                    _listener.BeginAccept(AcceptCallback, _listener);
#elif FEATURE_SOCKET_TAP
#error Accepting new socket connections is not implemented.
#else
#error Accepting new socket connections is not implemented.
#endif

                    // wait until listener is stopped
                    _listenerCompleted.WaitOne();
                }
                catch (ObjectDisposedException)
                {
                    // BeginAccept / AcceptAsync will throw an ObjectDisposedException when the
                    // server is closed before the listener has started accepting connections.
                    //
                    // As we start accepting connection on a separate thread, this is possible
                    // when the listener is stopped right after it was started.

                    // mark listener stopped
                    _listenerCompleted.Set();
                }
                catch (Exception ex)
                {
                    RaiseExceptionEvent(ex);

                    // mark listener stopped
                    _listenerCompleted.Set();
                }
                finally
                {
                    if (Session != null)
                    {
                        Session.ErrorOccured -= Session_ErrorOccured;
                        Session.Disconnected -= Session_Disconnected;
                    }
                }
            });
        }