示例#1
0
        public async Task DoubleConnectTest()
        {
            TcpSocket sock = new TcpSocket();
            await sock.ConnectAsync("localhost", 1002);

            var result = await sock.ConnectAsync("localhost", 1002);

            Assert.AreEqual(result, SocketStatus.Error);
        }
示例#2
0
    private async void TryConnectToController(string ipAddress, int port)
    {
        if (controllerClientSocket != null)
        {
            TextToaster.Toast("Cannot connect to multiple controllers at once.");
            return;
        }

        ++connectingCount;

        var random = new System.Random();
        int userId = random.Next();

        IPAddress controllerIpAddress;

        if (!IPAddress.TryParse(ipAddress, out controllerIpAddress))
        {
            TextToaster.Toast($"Failed to parse {ipAddress} as an IP address.");
            --connectingCount;
            return;
        }

        var controllerEndPoint = new IPEndPoint(controllerIpAddress, port);

        var tcpSocket = new TcpSocket(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp));

        if (await tcpSocket.ConnectAsync(controllerEndPoint))
        {
            controllerClientSocket = new ControllerClientSocket(userId, tcpSocket);
        }

        --connectingCount;
    }
        public void RejectHugePacket()
        {
            using (TcpListener listener = new TcpListener(1024))
            {
                listener.Blocking = true;
                listener.Listen(PORT);

                TcpSocket clientSock       = new TcpSocket();
                var       connectionResult = clientSock.ConnectAsync("localhost", PORT).Result;

                var status = listener.Accept(out TcpSocket serverSock);
                Assert.AreEqual(SocketStatus.Done, status);

                var largePacket = new NetPacket();
                largePacket.WriteBytes(new byte[8192], true);

                while (clientSock.Send(largePacket) != SocketStatus.Done)
                {
                    ;
                }

                Assert.AreEqual(SocketStatus.Disconnected, serverSock.Receive(largePacket));

                Assert.IsFalse(serverSock.Connected);

                clientSock.Dispose();
                serverSock.Dispose();
                largePacket.Dispose();
            }
        }
示例#4
0
        public void NoConnectTest()
        {
            TcpSocket sock   = new TcpSocket();
            var       result = sock.ConnectAsync("localhost", 1002).Result;

            Assert.AreEqual(result, SocketStatus.Error);
        }
    private async void TryConnectToController()
    {
        if (controllerClient != null)
        {
            textToaster.Toast("A controller is already connected.");
            return;
        }

        if (!ConnectWindowVisibility)
        {
            textToaster.Toast("Cannot try connecting to more than one remote machine.");
            return;
        }

        ConnectWindowVisibility = false;

        var random = new System.Random();
        int userId = random.Next();

        var tcpSocket = new TcpSocket(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp));

        if (await tcpSocket.ConnectAsync(IPAddress.Loopback, ControllerMessages.PORT))
        {
            textToaster.Toast("connected");
            controllerClient = new ControllerClient(userId, tcpSocket);
        }
        else
        {
            textToaster.Toast("not connected");
        }


        ConnectWindowVisibility = true;
    }
    private async void TryConnectToController(string ipAddress, int port)
    {
        if (controllerClientSocket != null)
        {
            TextToaster.Toast("Cannot connect to multiple controllers at once.");
            return;
        }

        if (!IPAddress.TryParse(ipAddress, out IPAddress controllerIpAddress))
        {
            TextToaster.Toast($"Failed to parse {ipAddress} as an IP address.");
            return;
        }

        Interlocked.Increment(ref connectingCount);
        var controllerEndPoint = new IPEndPoint(controllerIpAddress, port);

        var tcpSocket = new TcpSocket(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp));

        try
        {
            if (await tcpSocket.ConnectAsync(controllerEndPoint))
            {
                controllerClientSocket = new ControllerClientSocket(viewerId, tcpSocket);
            }
        }
        catch (TcpSocketException e)
        {
            TextToaster.Toast($"Failed not connect to the controller: {e.Message}");
        }

        Interlocked.Decrement(ref connectingCount);
    }
示例#7
0
        public void SocketDisposeTest()
        {
            TcpSocket sock = new TcpSocket();

            sock.Dispose();

            Assert.CatchAsync <ObjectDisposedException>(() => { return(sock.ConnectAsync("localhost", 1002).AsTask()); });
        }
示例#8
0
        public void SocketCloseTest()
        {
            TcpSocket sock = new TcpSocket();

            sock.Close();

            Assert.DoesNotThrowAsync(() => { return(sock.ConnectAsync("localhost", 1002).AsTask()); });
        }
示例#9
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);
            }
        }
        // [Test]
        public void StressTest()
        {
            TcpListener listener = new TcpListener();

            listener.Listen(PORT);

            TcpSocket clientSock       = new TcpSocket();
            var       connectionResult = clientSock.ConnectAsync("localhost", PORT).Result;

            var status = listener.Accept(out TcpSocket serverSock);

            for (int i = 0; i < 1000000; i++)
            {
                NetPacket packet = new NetPacket();

                var messageTo = Guid.NewGuid().ToString();
                packet.WriteString(messageTo);
                while (serverSock.Send(packet) != SocketStatus.Done)
                {
                    ;
                }

                packet.Clear();

                while (clientSock.Receive(packet) != SocketStatus.Done)
                {
                    ;
                }

                Assert.AreEqual(messageTo, packet.ReadString());
                packet.ResetWrite();

                packet.WriteString($"Message with code {messageTo} received.");
                while (clientSock.Send(packet) != SocketStatus.Done)
                {
                    ;
                }

                packet.Clear();

                while (serverSock.Receive(packet) != SocketStatus.Done)
                {
                    ;
                }

                packet.Dispose();
            }

            listener.Dispose();
            clientSock.Dispose();
            serverSock.Dispose();
        }
        public async Task ConnectTest()
        {
            TcpListener listener = new TcpListener();

            listener.Listen(666);

            TcpSocket clientSock = new TcpSocket();
            await clientSock.ConnectAsync("localhost", PORT);

            var status = listener.Accept(out TcpSocket serverSock);

            Assert.AreEqual(status, SocketStatus.Done);
            Assert.NotNull(serverSock);

            listener.Stop();
            clientSock.Close();
            serverSock.Close();
        }
示例#12
0
 ///<summary>Starts connecting to the remote host.</summary>
 public override async Task StartHandshake()
 {
     try
     {
         DestinationSocket = new TcpSocket(MapTo.AddressFamily, this.Secure);
         await DestinationSocket.ConnectAsync(MapTo);
         await OnConnected();
     }
     catch (SocketException ex)
     {
         Console.WriteLine("connect error: " + ex.SocketErrorCode);
         Dispose();
     }
     catch (Exception ex)
     {
         Dispose();
     }
 }
示例#13
0
        static void client()
        {
            Console.Title = "Client";
            TcpSocket socket = new TcpSocket();
            socket.AsyncConnectionResult += (s, e) =>
            {
                if (e.Connected)
                {
                    Console.WriteLine("Client Connected!");
                    beginChat(false, socket);

                    while (true)
                    {
                        string msg = Console.ReadLine();

                        if (socket.Connected)
                        {
                            if (msg.ToLower() != "disconnect")
                            {
                                byte[] msgPayload = Encoding.ASCII.GetBytes(msg);

                                socket.SendAsync(msgPayload);
                            }
                            else
                            {
                                socket.Disconnect();
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Connection could not be made... Retrying in 2 seconds...");
                    client();
                }
            };
            socket.ConnectAsync(IPAddress.Loopback, 1000);
        }
        public void SendReceiveTest()
        {
            const string serverMessage = "HelloFromServer";
            const string clientMessage = "ResponseFromClient";

            using (TcpListener listener = new TcpListener())
            {
                listener.Blocking = true;
                listener.Listen(PORT);

                TcpSocket clientSock       = new TcpSocket();
                var       connectionResult = clientSock.ConnectAsync("localhost", PORT).Result;

                var status = listener.Accept(out TcpSocket serverSock);

                NetPacket packet       = new NetPacket();
                NetPacket clientPacket = new NetPacket();

                packet.WriteString(serverMessage);

                // Send message to client.
                Assert.AreEqual(SocketStatus.Done, serverSock.Send(packet));

                // Read message from server.
                Assert.AreEqual(SocketStatus.Done, clientSock.Receive(clientPacket));
                Assert.AreEqual(serverMessage, clientPacket.ReadString());

                // Send message back to server.
                clientPacket.Clear(SerializationMode.Writing);
                clientPacket.WriteString(clientMessage);
                Assert.AreEqual(SocketStatus.Done, clientSock.Send(clientPacket));

                // Read message from client.
                Assert.AreEqual(SocketStatus.Done, serverSock.Receive(packet));
                Assert.AreEqual(clientMessage, packet.ReadString());

                clientSock.Dispose();
                serverSock.Dispose();
                packet.Dispose();
                clientPacket.Dispose();
            }
        }
示例#15
0
 public Task <bool> ConnectAsync(IPEndPoint ipEndPoint)
 {
     return(socket.ConnectAsync(ipEndPoint));
 }
示例#16
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);
            }
        }
示例#17
0
        public async Task ConnectAsync()
        {
            if (IsConnected || isConnecting)
            {
                return;
            }

            lock (connectAsyncLock)
            {
                if (IsConnected || isConnecting)
                {
                    return;
                }
                isConnecting = true;
            }

            try
            {
                IPAddress[] ipAddresses;
                IPAddress   ip;
                if (IPAddress.TryParse(host, out ip))
                {
                    ipAddresses = new IPAddress[] { ip };
                }
                else
                {
                    trace.Debug("Resolving DNS for Host '{0}'", host);
                    ipAddresses = await GetHostAddressesAsync(host);
                }

                Exception exception = null;
                for (int i = 0; i < ipAddresses.Length; i++)
                {
                    if (ipAddresses[i] == null ||
                        (ipAddresses[i].AddressFamily == AddressFamily.InterNetwork && !Socket.OSSupportsIPv4) ||
                        (ipAddresses[i].AddressFamily == AddressFamily.InterNetworkV6 && !Socket.OSSupportsIPv6))
                    {
                        continue;
                    }

                    socket = new Socket(ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                    try
                    {
                        trace.Debug("Attempting to connect to {0}:{1}", ipAddresses[i].ToString(), port.ToString());
                        await TcpSocket.ConnectAsync(socket, ipAddresses[i], port);

                        trace.Debug("Successfully connected to {0}:{1}", ipAddresses[i].ToString(), port.ToString());
                        exception = null;
                        break;
                    }
                    catch (Exception e)
                    {
                        exception = e;
                        socket.Dispose();
                        socket = null;
                    }
                }

                if (socket == null)
                {
                    trace.Error(exception, "Error connecting to {0}", host);
                    throw exception ?? new SocketException((int)SocketError.AddressNotAvailable);
                }

                if (useTLS)
                {
                    trace.Debug("Starting TLS Authentication.");
                    sslStream = new SslStream(new NetworkStream(socket));
                    await sslStream.AuthenticateAsClientAsync(host, null, SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls, true); // TODO super-safe defaults, but need to parameterize

                    trace.Debug("Finished TLS Authentication.");
                }

                IsConnected = true;
            }
            finally
            {
                isConnecting = false;
            }
        }