Esempio n. 1
0
        private bool TestClient(string content, string ipEndPointAddress, out Socket s)
        {
            s = null;
            if (!IPEndPointHelper.TryParseEndPoint(ipEndPointAddress, out var ep, out var msg))
            {
                output.WriteLine(msg);
                return(false);
            }
            var result = false;

            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Connect(ep);
            byte[] buffer = new byte[4096];
            var    length = s.Receive(buffer);

            if (length == 0)
            {
                output.WriteLine("remote closed unexcepted");
                return(false);
            }
            if (Encoding.UTF8.GetString(buffer.Take(length).ToArray()) == content)
            {
                result = true;
            }
            else
            {
                output.WriteLine("received result not same");
            }
            return(result);
        }
Esempio n. 2
0
        private bool TestTCPServer(string testContent, string ipendpointandport, out Socket s)
        {
            s = null;
            if (!IPEndPointHelper.TryParseEndPoint(ipendpointandport, out var ep, out var msg))
            {
                output.WriteLine(msg);
                return(false);
            }

            IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();

            if (properties.GetActiveTcpListeners().Any(x => x.Address.Equals(ep.Address) && x.Port == ep.Port))
            {
                output.WriteLine("port has been used " + ep.Port);
                return(false);
            }


            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Bind(ep);
            s.Listen(10);
            s.AcceptAsync().ContinueWith(x =>
            {
                if (x.Exception == null)
                {
                    var ns = x.Result;
                    ns.Send(Encoding.UTF8.GetBytes(testContent));

                    //					ns.Shutdown(SocketShutdown.Send);
                    //					ns.Close();
                }
            });

            return(true);
        }
Esempio n. 3
0
        /// <summary>
        /// Tries to determine the true IP address of the client and the address of the proxy, if any. If the
        /// values have already been calculated and aren't going to change then this does nothing.
        /// </summary>
        private void DetermineClientAndProxyAddresses()
        {
            var translationBasis = String.Format("{0}-{1}", RemoteIpAddress, Headers["X-Forwarded-For"]);

            if (!String.Equals(translationBasis, Get <string>(EnvironmentKey.ClientIpAddressBasis)))
            {
                Set <string>(EnvironmentKey.ClientIpAddressBasis, translationBasis);

                var localOrLanRequest = IPEndPointHelper.IsLocalOrLanAddress(new IPEndPoint(ParseIpAddress(RemoteIpAddress), RemotePort.GetValueOrDefault()));
                var xff = localOrLanRequest ? Headers["X-Forwarded-For"] : null;

                if (!String.IsNullOrEmpty(xff))
                {
                    xff = xff.Split(',').Last().Trim();
                    IPAddress ipAddress;
                    if (!IPAddress.TryParse(xff, out ipAddress))
                    {
                        xff = null;
                    }
                }

                if (String.IsNullOrEmpty(xff))
                {
                    Set <string>(EnvironmentKey.ClientIpAddress, RemoteIpAddress);
                    Set <string>(EnvironmentKey.ProxyIpAddress, null);
                }
                else
                {
                    Set <string>(EnvironmentKey.ClientIpAddress, xff);
                    Set <string>(EnvironmentKey.ProxyIpAddress, RemoteIpAddress);
                }
            }
        }
Esempio n. 4
0
        private bool TestTTTService(string ip, int listenPortForService, string serviceListeningip, string testServerEPAddress, out TransferServer ts)
        {
            ts = null;
            var result = false;

            if (!IPEndPointHelper.TryParseEndPoint(ip + ":" + listenPortForService, out var ep, out var msg))
            {
                output.WriteLine(msg);
                return(result);
            }
            if (!IPEndPointHelper.TryParseEndPoint(serviceListeningip, out var listenEp, out var msg2))
            {
                output.WriteLine(msg2);
                return(result);
            }
            if (!IPEndPointHelper.TryParseEndPoint(testServerEPAddress, out var testServerEP, out var msg3))
            {
                output.WriteLine(msg3);
                return(result);
            }

            ts     = new TransferServer(listenEp, ep, testServerEP, new BaseLogger(new TestLogger(output)));
            result = true;
            return(result);
        }
        /// <summary>
        /// Tries to work out whether the request came through a reverse proxy and, related to that, whether the request came from the Internet.
        /// </summary>
        /// <param name="request"></param>
        /// <remarks>
        /// Only reverse proxies that have a local address can influence this, if an Internet request comes with XFF headers they're just ignored.
        /// The code only checks the address of the machine that used the proxy, so if the request came through two reverse proxies on the LAN
        /// then it will always look like a local machine made the request.
        /// </remarks>
        private void DetermineReverseProxyAndIsInternetRequest(IRequest request)
        {
            IsInternetRequest = !IPEndPointHelper.IsLocalOrLanAddress(request.RemoteEndPoint);

            if (!IsInternetRequest)
            {
                var xForwardedFor = Request.Headers["X-Forwarded-For"];
                if (xForwardedFor != null)
                {
                    ProxyAddress  = request.RemoteEndPoint.Address.ToString();
                    ClientAddress = xForwardedFor.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Last().Trim();

                    IPAddress clientIPAddress;
                    if (IPAddress.TryParse(ClientAddress, out clientIPAddress))
                    {
                        IsInternetRequest = !IPEndPointHelper.IsLocalOrLanAddress(new IPEndPoint(clientIPAddress, request.RemoteEndPoint.Port));
                    }
                    else
                    {
                        ClientAddress     = request.RemoteEndPoint.Address.ToString();
                        IsInternetRequest = true;
                    }
                }
            }
        }
Esempio n. 6
0
    public static IPEndPoint GetEndPointAddress(string address)
    {
        var a = address.Trim();

        // use deault if empty string

        if (string.IsNullOrEmpty(a))
        {
            return(G.DefaultServerEndPoint);
        }

        // use 192.168.0.num if *.num when local ip address is 192.168.0.~

        if (a.StartsWith("*."))
        {
            var end  = int.Parse(a.Substring(2));
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    var abytes = ip.GetAddressBytes();
                    abytes[abytes.Length - 1] = (byte)end;
                    return(new IPEndPoint(new IPAddress(abytes), G.DefaultServerEndPoint.Port));
                }
            }
        }

        return(IPEndPointHelper.Parse(address, G.DefaultServerEndPoint.Port));
    }
Esempio n. 7
0
        public IChannel Create(string address)
        {
            var type            = Type;
            var connectEndPoint = ConnectEndPoint;
            var connectToken    = ConnectToken;

            if (string.IsNullOrEmpty(address) == false)
            {
                var parts = address.Split('|'); // type|endpoint|{token}
                if (parts.Length < 2)
                {
                    throw new ArgumentException(nameof(address));
                }
                type            = (ChannelType)Enum.Parse(typeof(ChannelType), parts[0], true);
                connectEndPoint = IPEndPointHelper.Parse(parts[1]);
                connectToken    = parts.Length > 2 ? parts[2] : null;
            }

            switch (type)
            {
            case ChannelType.Tcp:
                var tcpChannel = new TcpChannel(CreateChannelLogger(), connectEndPoint, connectToken, PacketSerializer);
                InitializeChannel(tcpChannel);
                return(tcpChannel);

            case ChannelType.Udp:
                var udpChannel = new UdpChannel(CreateChannelLogger(), connectEndPoint, connectToken, PacketSerializer, (NetPeerConfiguration)UdpConfig);
                InitializeChannel(udpChannel);
                return(udpChannel);

            default:
                throw new InvalidOperationException("Unknown TransportType");
            }
        }
        public void IPEndPointHelper_IsLocalOrLanAddress_Returns_Correct_Values()
        {
            ExcelWorksheetData worksheet = new ExcelWorksheetData(TestContext);

            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(worksheet.String("IPAddress")), 0);

            Assert.AreEqual(worksheet.Bool("Expected"), IPEndPointHelper.IsLocalOrLanAddress(endPoint));
        }
        public async Task <OperationResult> UpdateRemoteMachinePriceTableAsync(Machine machine, IEnumerable <ProductRail> products)
        {
            //if (!IPAddress.TryParse(machine.IPEndPoint, out var ipAddr))
            if (!IPEndPointHelper.TryParse(machine.IPEndPoint, out var ipAddr))
            {
                return(OperationResult.Failed(OperationErrorFactory.FromWellKnowErrors(WellKnowErrors.InvalidMachineIPEndPoint)));
            }

            var productsArr = products.ToArray();

            using (var client = new TcpClient())
            {
                _logger.LogInformationIfEnabled(() => $"Connection to machine {machine}");
                _logger.LogInformationIfEnabled(() => $"Openning TCP connection in {ipAddr.Address}:{MACHINE_TCP_PORT}");
                await client.ConnectAsync(ipAddr.Address, MACHINE_TCP_PORT);


                var stream = client.GetStream();
                _logger.LogDebug("Got stream!");

                var productsCount = productsArr.Length;
                _logger.LogDebugIfEnabled(() => $"Sending {productsCount} products update.");

                var data = new byte[OFFSET.PRODUCTS + (productsCount * PRODUCT_SIZE)];

                data[OFFSET.INTENTION] = 0x02;
                data[OFFSET.COUNT]     = (byte)productsCount;

                for (int i = 0; i < productsCount; i++)
                {
                    var p = productsArr[i];
                    ToBytes(p).CopyTo(data, OFFSET.PRODUCTS + (i * PRODUCT_SIZE));
                }

                _logger.LogInformationIfEnabled(() => $"Awaiting...");
                await Task.Delay(500);

                _logger.LogTraceIfEnabled(() => $"Sending bulk update data: '{ByteHelper.ByteArrayToString(data)}'.");
                stream.Write(data, 0, data.Length);

                _logger.LogDebug("Ignoring response....");
                // var buffer = new byte[255];
                // var result = await stream.ReadAsync(buffer, 0, 255);
            }

            _logger.LogDebug("Returning OperationResult.Success.");
            return(OperationResult.Success);
        }
        /// <summary>
        /// Called on a background thread when a client connects.
        /// </summary>
        /// <param name="result"></param>
        private void IncomingTcpClient(IAsyncResult result)
        {
            TcpClient tcpClient = null;

            try {
                lock (_SyncLock) {
                    tcpClient = _Listener == null || _Disposed ? null : _Listener.EndAcceptTcpClient(result);
                }
            } catch (SocketException) {
                // Exception spam
            } catch (ObjectDisposedException) {
                // Exception spam
            } catch (InvalidOperationException) {
                // Exception spam
            } catch (ThreadAbortException) {
                // We can ignore this, it'll get re-thrown automatically on the end of the try. We don't want to report it.
            } catch (Exception ex) {
                OnExceptionCaught(new EventArgs <Exception>(ex));
            }

            if (tcpClient != null)
            {
                try {
                    Client client = null;
                    lock (_SyncLock) {
                        if (_Disposed)
                        {
                            client = null;
                        }
                        else
                        {
                            client = new Client()
                            {
                                TcpClient  = tcpClient,
                                IPEndPoint = tcpClient.Client.RemoteEndPoint as IPEndPoint,
                            };
                            if (client.IPEndPoint == null)
                            {
                                ((IDisposable)tcpClient).Dispose();
                                client = null;
                            }
                            else
                            {
                                tcpClient.NoDelay = IPEndPointHelper.IsLocalOrLanAddress(client.IPEndPoint);
                                _ConnectedClients.Add(client);
                            }
                        }
                    }

                    if (client != null)
                    {
                        OnClientConnected(new BroadcastEventArgs(client.IPEndPoint, 0, Port, EventFormat));
                    }
                } catch (ThreadAbortException) {
                    // We can ignore this, it'll get re-thrown automatically on the end of the try. We don't want to report it.
                } catch (Exception ex) {
                    OnExceptionCaught(new EventArgs <Exception>(ex));
                }
            }

            try {
                lock (_SyncLock) {
                    if (_Listener != null && !_Disposed)
                    {
                        _Listener.BeginAcceptTcpClient(IncomingTcpClient, null);
                    }
                }
            } catch (ThreadAbortException) {
                // We can ignore this, it'll get re-thrown automatically on the end of the try. We don't want to report it.
            } catch (Exception ex) {
                OnExceptionCaught(new EventArgs <Exception>(ex));
            }
        }