Example #1
0
        public async Task <LoopSession> Start()
        {
            int?port;

            ReceiverService loop =
                new ReceiverBuilder()
                .WithDefinition(new LoopMessages())
                .Build(hooks);

            TcpSocket client = pool.New();
            TcpSocket server = pool.New();

            client.Bind();
            server.Bind(out port);
            server.Listen(1);

            IPEndPoint             endpoint = new IPEndPoint(IPAddress.Loopback, port.Value);
            Task <TcpSocketAccept> accept   = server.Accept();

            client.Connect(endpoint, null);

            PeerHash          peer     = PeerHash.Random();
            TcpSocketAccept   accepted = await accept;
            NetworkConnection receiver = pool.Create(accepted.Connection, NetworkDirection.Incoming, accepted.GetRemote());

            loop.StartProcessing(peer, receiver);
            return(new LoopSession(client, loop));
        }
Example #2
0
        public async Task CanHandleTerminatedStream()
        {
            IPAddress  localhost = IPAddress.Loopback;
            IPEndPoint endpoint  = new IPEndPoint(localhost, 1234);

            using (CompletionThread worker = new CompletionThread())
            {
                SocketFactory factory = new SocketFactory(worker);

                using (TcpSocket server = factory.Tcp())
                    using (TcpSocket socket = factory.Tcp())
                    {
                        socket.Bind();
                        worker.Start();

                        server.Bind(endpoint.Port);
                        server.Listen(1);

                        Task <TcpSocketAccept> acceptable = server.Accept();
                        await socket.Connect(endpoint);

                        TcpSocketAccept accepted = await acceptable;
                        accepted.Connection.Dispose();

                        byte[]        buffer = new byte[10];
                        TcpSocketSend sent   = await socket.Send(buffer);

                        Assert.That(sent.Status, Is.EqualTo(SocketStatus.OK));
                    }
            }
        }
Example #3
0
        public async Task ShouldTriggerConnectionSentWhenSentSomeBytes()
        {
            NetworkDirection       direction = NetworkDirection.Outgoing;
            NetworkOutgoingMessage message   = new RandomMessage(113);

            using (NetworkFixture fixture = new NetworkFixture())
                using (TcpSocket host = fixture.Pool.New())
                    using (TcpSocket socket = fixture.Pool.New())
                    {
                        TcpSocketInfo info     = host.BindAndInfo();
                        int           port     = info.Endpoint.Port;
                        IPEndPoint    endpoint = new IPEndPoint(IPAddress.Loopback, port);

                        socket.Bind();
                        host.Listen(10);
                        host.Accept(null);

                        await socket.Connect(endpoint);

                        NetworkConnection connection = fixture.Pool.Create(socket, direction, endpoint);
                        Trigger           handler    = Trigger.Bind(ref fixture.Hooks.OnConnectionSent, data =>
                        {
                            data.Remote.Should().Be(NetworkAddress.Parse(endpoint));
                            data.Connection.Should().Be(connection);
                            data.Bytes.Should().Be(message.Length);
                        });

                        connection.Send(message);
                        handler.Wait().Should().BeTrue();
                    }
        }
Example #4
0
        public async Task CanObtainAcceptedRemoteEndpointUsingTasks()
        {
            using (CompletionThread worker = new CompletionThread())
            {
                IPEndPoint    endpoint;
                SocketFactory factory = new SocketFactory(worker);

                using (TcpSocket server = factory.Tcp())
                    using (TcpSocket client = factory.Tcp())
                    {
                        worker.Start();
                        client.Bind();

                        server.Bind(IPAddress.Loopback);
                        server.Listen(1);

                        endpoint = server.Info().Endpoint;

                        Task <TcpSocketAccept> accepting = server.Accept();
                        await client.Connect(endpoint);

                        TcpSocketAccept accepted = await accepting;
                        IPEndPoint      remote   = accepted.GetRemote();

                        Assert.That(remote.Address, Is.EqualTo(endpoint.Address));
                        Assert.That(remote.Port, Is.Not.EqualTo(endpoint.Port));
                        Assert.That(remote.Port, Is.Not.Zero);
                    }
            }
        }
Example #5
0
        ///<summary>Processes a SOCKS request from a client.</summary>
        ///<param name="Request">The request to process.</param>
        protected override async Task ProcessRequest(byte[] Request)
        {
            int Ret;

            try
            {
                if (Request[0] == 1)
                { // CONNECT
                    IPAddress RemoteIP;
                    int       RemotePort = Request[1] * 256 + Request[2];
                    Ret      = Array.IndexOf(Request, (byte)0, 7);
                    Username = Encoding.ASCII.GetString(Request, 7, Ret - 7);
                    if (Request[3] == 0 && Request[4] == 0 && Request[5] == 0 && Request[6] != 0)
                    {// Use remote DNS
                        Ret      = Array.IndexOf(Request, (byte)0, Ret + 1);
                        RemoteIP = Dns.GetHostAddressesAsync(Encoding.ASCII.GetString(Request, Username.Length + 8, Ret - Username.Length - 8)).Result[0];
                    }
                    else
                    { //Do not use remote DNS
                        RemoteIP = IPAddress.Parse(Request[3].ToString() + "." + Request[4].ToString() + "." + Request[5].ToString() + "." + Request[6].ToString());
                    }
                    RemoteConnection = new TcpSocket(RemoteIP.AddressFamily, false);
                    try
                    {
                        await RemoteConnection.ConnectAsync(new IPEndPoint(RemoteIP, RemotePort));
                        await OnConnected(null);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace);
                        await OnConnected(ex);
                    }
                }
                else if (Request[0] == 2)
                { // BIND
                    byte[] Reply   = new byte[8];
                    long   LocalIP = BitConverter.ToInt64(Listener.GetLocalExternalIP().Result.GetAddressBytes(), 0);
                    AcceptSocket = new TcpSocket(IPAddress.Any.AddressFamily, false);
                    AcceptSocket.Bind(new IPEndPoint(IPAddress.Any, 0));
                    AcceptSocket.Listen(50);
                    RemoteBindIP = IPAddress.Parse(Request[3].ToString() + "." + Request[4].ToString() + "." + Request[5].ToString() + "." + Request[6].ToString());
                    Reply[0]     = 0;                                                                         //Reply version 0
                    Reply[1]     = 90;                                                                        //Everything is ok :)
                    Reply[2]     = (byte)(Math.Floor(((IPEndPoint)AcceptSocket.LocalEndPoint).Port / 256.0)); //Port/1
                    Reply[3]     = (byte)(((IPEndPoint)AcceptSocket.LocalEndPoint).Port % 256);               //Port/2
                    Reply[4]     = (byte)((LocalIP % 256));                                                   //IP Address/1
                    Reply[5]     = (byte)(Math.Floor((LocalIP % 65536) / 256.0));                             //IP Address/2
                    Reply[6]     = (byte)(Math.Floor((LocalIP % 16777216) / 65536.0));                        //IP Address/3
                    Reply[7]     = (byte)(Math.Floor(LocalIP / 16777216.0));                                  //IP Address/4
                    await Connection.SendAsync(Reply, async (int x) => { await OnStartAccept(); });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace);
                await Dispose(ReplyCode.RequestRejected1);
            }
        }
Example #6
0
        public ConnectorSession(NetworkPool pool, PeerConnector connector)
        {
            int?port;

            this.connector = connector;
            this.server    = pool.New();

            server.Bind(out port);
            server.Listen(1);

            endpoint = new IPEndPoint(IPAddress.Loopback, port.Value);
        }
Example #7
0
        public void Start()
        {
            assignedPort = configuration.Port.Bind(socket);

            if (assignedPort == null)
            {
                hooks.CallListenerFailed(configuration, assignedPort.Value, $"Binding to the requested port failed.");
            }
            else
            {
                socket.Listen(8);
                socket.Accept(OnAccept);

                hooks.CallListenerStarted(configuration, assignedPort.Value);
            }
        }
Example #8
0
        ///<summary>Starts listening on the selected IP address and port.</summary>
        ///<exception cref="SocketException">There was an error while creating the listening socket.</exception>
        public async void Start()
        {
            try
            {
                ListenSocket = new TcpSocket(Address.AddressFamily, this.Secure);
                ListenSocket.Bind(new IPEndPoint(Address, Port));
                ListenSocket.Listen(50);

                SocketConnection socket = await ListenSocket.AcceptAsync();

                await this.OnAccept(socket);
            }
            catch (Exception ex)
            {
                Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace);
                this.Dispose();
                throw new SocketException();
            }
        }
Example #9
0
        public async Task ShouldTriggerConnectionReceivedWhenReceivedSomeBytes()
        {
            NetworkDirection       direction = NetworkDirection.Outgoing;
            NetworkOutgoingMessage message   = new RandomMessage(113);

            using (NetworkFixture fixture = new NetworkFixture())
                using (TcpSocket host = fixture.Pool.New())
                    using (TcpSocket socket = fixture.Pool.New())
                    {
                        TcpSocketInfo info     = host.BindAndInfo();
                        int           port     = info.Endpoint.Port;
                        IPEndPoint    endpoint = new IPEndPoint(IPAddress.Loopback, port);

                        socket.Bind();
                        host.Listen(10);

                        Task <TcpSocketAccept> task = host.Accept();
                        await socket.Connect(endpoint);

                        TcpSocketAccept accept = await task;

                        NetworkConnection connection = fixture.Pool.Create(socket, direction, endpoint);
                        NetworkBlock      block      = new NetworkBlock(new byte[1024], 0, message.Length);

                        Trigger handler = Trigger.Bind(ref fixture.Hooks.OnConnectionReceived, data =>
                        {
                            data.Remote.Should().Be(NetworkAddress.Parse(endpoint));
                            data.Connection.Should().NotBeNull();
                            data.Bytes.Should().Be(message.Length);
                        });

                        connection.Receive(new NullReceiver());
                        message.ToBytes(block);

                        block.With((buffer, offset, count) =>
                        {
                            accept.Connection.Send(new SocketBuffer(buffer, offset, count), null);
                        });

                        handler.Wait().Should().BeTrue();
                    }
        }
Example #10
0
        public async Task ShouldTriggerConnectionTerminatedWhenSending()
        {
            NetworkDirection direction = NetworkDirection.Outgoing;

            using (NetworkFixture fixture = new NetworkFixture())
                using (TcpSocket host = fixture.Pool.New())
                    using (TcpSocket socket = fixture.Pool.New())
                    {
                        TcpSocketInfo info     = host.BindAndInfo();
                        int           port     = info.Endpoint.Port;
                        IPEndPoint    endpoint = new IPEndPoint(IPAddress.Loopback, port);

                        socket.Bind();
                        host.Listen(10);

                        Task <TcpSocketAccept> task    = host.Accept();
                        TcpSocketConnect       connect = await socket.Connect(endpoint);

                        TcpSocketAccept accept = await task;

                        connect.Status.Should().Be(SocketStatus.OK);
                        accept.Status.Should().Be(SocketStatus.OK);
                        accept.Connection.Dispose();

                        NetworkConnection connection = fixture.Pool.Create(socket, direction, endpoint);
                        Trigger           handler    = Trigger.Bind(ref fixture.Hooks.OnConnectionTerminated, data =>
                        {
                            data.Remote.Should().Be(NetworkAddress.Parse(endpoint));
                            data.Connection.Should().NotBeNull();
                        });

                        for (int i = 0; i < 10; i++)
                        {
                            connection.Send(new OneByteMessage());
                        }

                        handler.Wait().Should().BeTrue();
                    }
        }
Example #11
0
        public async Task <NegotiatorFixturePair> Create()
        {
            int?port;

            TcpSocket host   = pool.New();
            TcpSocket client = pool.New();

            client.Bind();
            host.Bind(out port);
            host.Listen(1);

            Task <TcpSocketAccept>  accept  = host.Accept();
            Task <TcpSocketConnect> connect = client.Connect(port.Value);

            TcpSocketAccept  accepted  = await accept;
            TcpSocketConnect connected = await connect;

            NetworkConnection local  = pool.Create(connected.Socket, NetworkDirection.Outgoing, connected.Endpoint);
            NetworkConnection remote = pool.Create(accepted.Connection, NetworkDirection.Incoming, accepted.GetRemote());

            return(new NegotiatorFixturePair(local, remote));
        }
Example #12
0
 public void Start()
 {
     socket.Listen(10);
     socket.Accept(OnAccepted);
 }
Example #13
0
        ///<summary>Processes a received query.</summary>
        ///<param name="Query">The query to process.</param>
        private async Task ProcessQuery(byte[] Query)
        {
            try
            {
                Request request = null;
                Request.ParseRequest(Query, out request);
                switch (request.Command)
                {
                case Command.Connect:     //CONNECT
                    IPAddress RemoteIP   = request.DstAddr;
                    int       RemotePort = 0;
                    if (Query[3] == 1)
                    {
                        RemoteIP   = IPAddress.Parse(Query[4].ToString() + "." + Query[5].ToString() + "." + Query[6].ToString() + "." + Query[7].ToString());
                        RemotePort = Query[8] * 256 + Query[9];
                    }
                    else if (Query[3] == 3)
                    {
                        if (RemoteIP == null)
                        {
                            RemoteIP = Dns.GetHostAddressesAsync(Encoding.ASCII.GetString(Query, 5, Query[4])).Result[0];
                        }
                        RemotePort = Query[4] + 5;
                        RemotePort = Query[RemotePort] * 256 + Query[RemotePort + 1];
                    }
                    RemoteConnection = new TcpSocket(RemoteIP.AddressFamily, false);
                    try
                    {
                        await RemoteConnection.ConnectAsync(new IPEndPoint(RemoteIP, RemotePort));
                        await OnConnected(null);
                    }
                    catch (SocketException ex)
                    {
                        Console.WriteLine("[WARN] SocketError=" + ex.SocketErrorCode + "\r\n");
                        await OnConnected(ex);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace);
                        await OnConnected(ex);
                    }
                    break;

                case Command.Bind:     //BIND
                    byte[] Reply   = new byte[10];
                    long   LocalIP = BitConverter.ToInt64(Listener.GetLocalExternalIP().Result.GetAddressBytes(), 0);
                    AcceptSocket = new TcpSocket(IPAddress.Any.AddressFamily, false);
                    AcceptSocket.Bind(new IPEndPoint(IPAddress.Any, 0));
                    AcceptSocket.Listen(50);
                    Reply[0] = 5;                                                                         //Version 5
                    Reply[1] = 0;                                                                         //Everything is ok :)
                    Reply[2] = 0;                                                                         //Reserved
                    Reply[3] = 1;                                                                         //We're going to send a IPv4 address
                    Reply[4] = (byte)((LocalIP % 256));                                                   //IP Address/1
                    Reply[5] = (byte)((LocalIP % 65536) / 256);                                           //IP Address/2
                    Reply[6] = (byte)((LocalIP % 16777216) / 65536);                                      //IP Address/3
                    Reply[7] = (byte)(Math.Floor(LocalIP / 16777216.0));                                  //IP Address/4
                    Reply[8] = (byte)(Math.Floor(((IPEndPoint)AcceptSocket.LocalEndPoint).Port / 256.0)); //Port/1
                    Reply[9] = (byte)(((IPEndPoint)AcceptSocket.LocalEndPoint).Port % 256);               //Port/2
                    await Connection.SendAsync(Reply, async (int x) => { await this.OnStartAccept(); });

                    break;

                case Command.UdpAssociate:     //UDP ASSOCIATE

                    if (request.DstAddr.Equals(IPAddress.Any) && request.DstPort == 0)
                    {
                        request.DstPort = FreePort.FindNextAvailableUDPPort(4200);
                        if (request.DstPort == 0)
                        {
                            await Dispose(ReplyCode.SocksFailure);

                            return;
                        }
                    }
                    if (request.DstAddr.Equals(IPAddress.Any))
                    {
                        request.DstAddr = ((IPEndPoint)Connection.LocalEndPoint).Address;
                    }
                    UdpClientEndPoint = new IPEndPoint(request.DstAddr, request.DstPort);
                    LocalBindEndPoint = new IPEndPoint(((IPEndPoint)(Connection.LocalEndPoint)).Address, request.DstPort);
                    var reply = request.CreateReply(LocalBindEndPoint.Address, LocalBindEndPoint.Port);
                    await Connection.SendAsync(reply.ToBytes(), async (int x) => { await this.StartUdpReceive(); });

                    break;

                default:
                    await Dispose(ReplyCode.UnsupportedCommand);

                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[WARN] " + ex.Message + "\r\n" + ex.StackTrace);
                await Dispose(ReplyCode.SocksFailure);
            }
        }