Esempio n. 1
0
        /// <summary>
        /// Reconnects a client after an error or if it's offline. Reconnecting, instead of creating a completely new connection,
        /// saves time.
        /// </summary>
        public async Task Reconnect()
        {
            try
            {
                this.secondTimer?.Dispose();
                this.secondTimer = null;

                if (this.state == MqttState.Connected)
                {
                    await this.DISCONNECT();
                }

                this.DisposeClient();
            }
            catch (Exception)
            {
                // Ignore
            }
            finally
            {
                this.secondTimer = null;
                this.client      = null;
            }

            this.state = MqttState.Offline;

            await this.BeginConnect();
        }
Esempio n. 2
0
        /// <summary>
        /// Reconnects a client after an error or if it's offline. Reconnecting, instead of creating a completely new connection,
        /// saves time.
        /// </summary>
        public void Reconnect()
        {
            try
            {
                if (this.secondTimer != null)
                {
                    this.secondTimer.Dispose();
                }

                if (this.state == MqttState.Connected)
                {
                    this.DISCONNECT();
                }

                this.DisposeClient();
            }
            catch (Exception)
            {
                // Ignore
            }
            finally
            {
                this.secondTimer = null;
                this.client      = null;
            }

            this.state = MqttState.Offline;

            Task.Run(this.BeginConnect);
        }
Esempio n. 3
0
		private Task Client_OnSent(object Sender, byte[] Buffer, int Offset, int Count)
		{
			if (this.HasSniffers)
				this.TransmitBinary(BinaryTcpClient.ToArray(Buffer, Offset, Count));

			return Task.FromResult<bool>(true);
		}
Esempio n. 4
0
        /// <summary>
        /// Connect to the remote host and port using a binary protocol over TCP.
        /// </summary>
        /// <param name="Sniffers">Sniffers</param>
        /// <returns>Binary TCP transport.</returns>
        public async Task <BinaryTcpClient> ConnectTcp(params ISniffer[] Sniffers)
        {
            BinaryTcpClient Client = new BinaryTcpClient(Sniffers);
            await Client.ConnectAsync(this.Host, this.port);

            return(Client);
        }
        /// <summary>
        /// Connects to a peer in the peer-to-peer network. If the remote end point resides behind the same firewall as the current application,
        /// a direct connection to the local peer is made, for improved performance.
        /// </summary>
        /// <param name="RemoteEndPoint">Remote End-point.</param>
        /// <returns>Peer connection</returns>
        public async Task <PeerConnection> ConnectToPeer(IPEndPoint RemoteEndPoint)
        {
            if (this.State != PeerToPeerNetworkState.Ready)
            {
                throw new IOException("Peer-to-peer network not ready.");
            }

            BinaryTcpClient Client          = new BinaryTcpClient();
            IPEndPoint      RemoteEndPoint2 = RemoteEndPoint;

            try
            {
                RemoteEndPoint2 = this.CheckLocalRemoteEndpoint(RemoteEndPoint);
                await Client.ConnectAsync(RemoteEndPoint2.Address, RemoteEndPoint2.Port, true);
            }
            catch (Exception ex)
            {
                Client.Dispose();
                System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex).Throw();
            }

            PeerConnection Result = new PeerConnection(Client, this, RemoteEndPoint2, this.encapsulatePackets);

            Result.StartIdleTimer();

            return(Result);
        }
 public ClientRequestHandler(BinaryTcpClient client,
                             string logsSourcePath, string logsDestPath,
                             ILogger logger)
 {
     this.client         = client;
     this.logsSourcePath = logsSourcePath;
     this.logsDestPath   = logsDestPath;
     this.logger         = logger;
 }
Esempio n. 7
0
        /// <summary>
        /// <see cref="IDisposable.Dispose"/>
        /// </summary>
        public void Dispose()
        {
            if (!this.disposed)
            {
                this.disposed = true;
                this.State    = Socks5State.Offline;

                this.client?.Dispose();
                this.client = null;
            }
        }
Esempio n. 8
0
 protected override void OnAcceptClient(BinaryTcpClient client)
 {
     logger.Log("Connection received");
     ThreadPool.QueueUserWorkItem(stateInfo =>
     {
         new ClientHandler(
             client, logSourcePath, logDestPath, logger)
         .HandleClient();
     });
     logger.Log("Created thread for user");
 }
        internal HttpClientConnection(HttpServer Server, BinaryTcpClient Client, bool Encrypted, params ISniffer[] Sniffers)
            : base(Sniffers)
        {
            this.server    = Server;
            this.client    = Client;
            this.encrypted = Encrypted;

            this.client.OnDisconnected += Client_OnDisconnected;
            this.client.OnError        += Client_OnError;
            this.client.OnReceived     += Client_OnReceived;
        }
Esempio n. 10
0
		/// <summary>
		/// <see cref="IDisposable.Dispose"/>
		/// </summary>
		public void Dispose()
		{
			if (!this.disposed)
			{
				this.disposed = true;
				Task _ = this.SetState(Socks5State.Offline);

				this.client?.Dispose();
				this.client = null;
			}
		}
Esempio n. 11
0
        /// <summary>
        /// <see cref="IDisposable.Dispose"/>
        /// </summary>
        public void Dispose()
        {
            this.disposed = true;

            this.idleTimer?.Dispose();
            this.idleTimer = null;

            this.tcpConnection?.Dispose();
            this.tcpConnection = null;

            this.Closed();
        }
Esempio n. 12
0
 public ClientHandler(BinaryTcpClient client,
                      string logsSourcePath, string logsDestPath,
                      ILogger logger)
 {
     this.client         = client;
     this.logsSourcePath = logsSourcePath;
     this.logsDestPath   = logsDestPath;
     this.logger         = logger;
     requestHandler      = new ClientRequestHandler(
         client, logsSourcePath, logsDestPath, this.logger);
     decoder = new MessageDecoder();
     categorizationStrategy = GetCategorizationStrategy();
 }
Esempio n. 13
0
		/// <summary>
		/// Client used for SOCKS5 communication.
		/// </summary>
		/// <param name="Host">Host of SOCKS5 stream host.</param>
		/// <param name="Port">Port of SOCKS5 stream host.</param>
		/// <param name="JID">JID of SOCKS5 stream host.</param>
		/// <param name="Sniffers">Optional set of sniffers.</param>
		public Socks5Client(string Host, int Port, string JID, params ISniffer[] Sniffers)
			: base(Sniffers)
		{
			this.host = Host;
			this.port = Port;
			this.jid = JID;

			Task _ = this.SetState(Socks5State.Connecting);
			this.Information("Connecting to " + this.host + ":" + this.port.ToString());

			this.client = new BinaryTcpClient();
			this.Connect();
		}
Esempio n. 14
0
        internal PeerConnection(BinaryTcpClient TcpConnection, PeerToPeerNetwork Network, IPEndPoint RemoteEndpoint,
                                bool EncapsulatePackets)
        {
            this.network            = Network;
            this.remoteEndpoint     = RemoteEndpoint;
            this.tcpConnection      = TcpConnection;
            this.encapsulatePackets = EncapsulatePackets;

            this.tcpConnection.OnDisconnected += TcpConnection_OnDisconnected;
            this.tcpConnection.OnError        += TcpConnection_OnError;
            this.tcpConnection.OnReceived     += TcpConnection_OnReceived;
            this.tcpConnection.OnSent         += TcpConnection_OnSent;
        }
Esempio n. 15
0
		private async Task<bool> Client_OnReceived(object Sender, byte[] Buffer, int Offset, int Count)
		{
			if (this.HasSniffers)
				this.ReceiveBinary(BinaryTcpClient.ToArray(Buffer, Offset, Count));

			try
			{
				await this.ParseIncoming(Buffer, Offset, Count);
				return true;
			}
			catch (Exception ex)
			{
				Log.Critical(ex);
				return false;
			}
		}
Esempio n. 16
0
        private Task <bool> Client_OnReceived(object Sender, byte[] Buffer, int Offset, int Count)
        {
            if (this.HasSniffers)
            {
                this.ReceiveBinary(BinaryTcpClient.ToArray(Buffer, Offset, Count));
            }

            try
            {
                this.ParseIncoming(Buffer, Offset, Count);
            }
            catch (Exception ex)
            {
                Log.Critical(ex);
            }

            return(Task.FromResult <bool>(true));
        }
        public void Dispose()
        {
            if (!this.disposed)
            {
                this.disposed = true;

                this.webSocket?.Dispose();
                this.webSocket = null;

                this.headerStream?.Dispose();
                this.headerStream = null;

                this.dataStream?.Dispose();
                this.dataStream = null;

                this.client?.DisposeWhenDone();
                this.client = null;
            }
        }
Esempio n. 18
0
        private async Task BeginConnect()
        {
            try
            {
                this.Information("Connecting to " + Host + ":" + Port.ToString());

                this.DisposeClient();

                this.State = MqttState.Connecting;

                this.client = new BinaryTcpClient();
                await this.client.ConnectAsync(Host, Port, this.tls);

                if (this.tls)
                {
                    this.State = MqttState.StartingEncryption;
#if WINDOWS_UWP
                    await this.client.UpgradeToTlsAsClient(SocketProtectionLevel.Tls12, this.trustServer);
#else
                    await this.client.UpgradeToTlsAsClient(this.clientCertificate, SslProtocols.Tls12, this.trustServer);
#endif
                    this.client.Continue();
                }

                this.client.OnSent         += this.Client_OnSent;
                this.client.OnReceived     += this.Client_OnReceived;
                this.client.OnDisconnected += this.Client_OnDisconnected;
                this.client.OnError        += this.ConnectionError;

                await this.CONNECT(KeepAliveTimeSeconds);
            }
            catch (Exception ex)
            {
                await this.ConnectionError(this, ex);
            }
        }
Esempio n. 19
0
        private async Task <bool> Client_OnReceived(object Sender, byte[] Buffer, int Offset, int Count)
        {
            if (this.HasSniffers)
            {
                this.ReceiveBinary(BinaryTcpClient.ToArray(Buffer, Offset, Count));
            }

            byte b;
            bool Result = true;

            while (Count-- > 0)
            {
                b = Buffer[Offset++];

                switch (this.inputState)
                {
                case 0:
                    this.inputPacket = new MemoryStream();
                    this.inputPacket.WriteByte(b);
                    this.inputPacketType      = (MqttControlPacketType)(b >> 4);
                    this.inputRemainingLength = 0;
                    this.inputOffset          = 0;
                    this.inputState++;
                    break;

                case 1:
                    this.inputRemainingLength |= ((b & 127) << this.inputOffset);
                    this.inputOffset          += 7;

                    this.inputPacket.WriteByte(b);
                    if ((b & 128) == 0)
                    {
                        switch (this.inputPacketType)
                        {
                        case MqttControlPacketType.CONNECT:
                        case MqttControlPacketType.CONNACK:
                        case MqttControlPacketType.PINGREQ:
                        case MqttControlPacketType.PINGRESP:
                        case MqttControlPacketType.DISCONNECT:
                        case MqttControlPacketType.PUBLISH:
                        default:
                            if (this.inputRemainingLength == 0)
                            {
                                this.inputState = 0;
                                if (!await this.ProcessInputPacket())
                                {
                                    Result = false;
                                }
                            }
                            else
                            {
                                this.inputState += 3;
                            }
                            break;

                        case MqttControlPacketType.PUBACK:
                        case MqttControlPacketType.PUBREC:
                        case MqttControlPacketType.PUBREL:
                        case MqttControlPacketType.PUBCOMP:
                        case MqttControlPacketType.SUBSCRIBE:
                        case MqttControlPacketType.SUBACK:
                        case MqttControlPacketType.UNSUBSCRIBE:
                        case MqttControlPacketType.UNSUBACK:
                            this.inputState++;
                            break;
                        }
                    }
                    break;

                case 2:
                    this.inputPacket.WriteByte(b);
                    this.inputState++;
                    this.inputRemainingLength--;
                    break;

                case 3:
                    this.inputPacket.WriteByte(b);
                    this.inputRemainingLength--;

                    if (this.inputRemainingLength == 0)
                    {
                        this.inputState = 0;
                        if (!await this.ProcessInputPacket())
                        {
                            Result = false;
                        }
                    }
                    else
                    {
                        this.inputState++;
                    }

                    break;

                case 4:
                    this.inputPacket.WriteByte(b);
                    this.inputRemainingLength--;

                    if (this.inputRemainingLength == 0)
                    {
                        this.inputState = 0;
                        if (!await this.ProcessInputPacket())
                        {
                            Result = false;
                        }
                    }
                    break;
                }
            }

            return(Result);
        }
Esempio n. 20
0
 public void HandleClient(BinaryTcpClient client, ILogger logger)
 {
 }
Esempio n. 21
0
 private void DisposeClient()
 {
     this.client?.Dispose();
     this.client = null;
 }
Esempio n. 22
0
 public void HandleClientThreaded(BinaryTcpClient client, ILogger logger)
 {
     ThreadPool.QueueUserWorkItem(s => HandleClient(client, logger));
 }
Esempio n. 23
0
 protected override void OnAcceptClient(BinaryTcpClient client)
 {
     logger.Log("Client connected");
     clientHandler.HandleClientThreaded(client, logger);
 }
        private Task <bool> Connection_OnReceived(object Sender, byte[] Buffer, int Offset, int Count)
        {
            PeerConnection Connection = (PeerConnection)Sender;
            Guid           PlayerId;
            IPAddress      PlayerRemoteAddress;
            IPEndPoint     PlayerRemoteEndpoint;

            try
            {
                BinaryInput Input = new BinaryInput(BinaryTcpClient.ToArray(Buffer, Offset, Count));

                PlayerId             = Input.ReadGuid();
                PlayerRemoteAddress  = IPAddress.Parse(Input.ReadString());
                PlayerRemoteEndpoint = new IPEndPoint(PlayerRemoteAddress, Input.ReadUInt16());
            }
            catch (Exception)
            {
                Connection.Dispose();
                return(Task.FromResult <bool>(true));
            }

            Player Player = (Player)Connection.StateObject;

            lock (this.remotePlayersByEndpoint)
            {
                if (!this.playersById.TryGetValue(PlayerId, out Player Player2) || Player2.PlayerId != Player.PlayerId)
                {
                    Connection.Dispose();
                    return(Task.FromResult <bool>(true));
                }

                Player.Connection = Connection;
            }

            Connection.RemoteEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork);

            Connection.OnReceived -= this.Connection_OnReceived;
            Connection.OnReceived += this.Peer_OnReceived;
            Connection.OnSent     += this.Connection_OnSent;

            BinaryOutput Output = new BinaryOutput();

            Output.WriteGuid(this.localPlayer.PlayerId);
            Output.WriteString(this.ExternalAddress.ToString());
            Output.WriteUInt16((ushort)this.ExternalEndpoint.Port);

            Connection.SendTcp(Output.GetPacket());

            MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerConnected;

            if (h != null)
            {
                try
                {
                    h(this, Player);
                }
                catch (Exception ex)
                {
                    Events.Log.Critical(ex);
                }
            }

            return(Task.FromResult <bool>(true));
        }
        private Task <bool> Peer_OnReceived(object Sender, byte[] Buffer, int Offset, int Count)
        {
            PeerConnection Connection = (PeerConnection)Sender;
            Player         Player;

            byte[] Packet;

            if (Connection.StateObject is null)
            {
                BinaryInput Input = new BinaryInput(BinaryTcpClient.ToArray(Buffer, Offset, Count));
                Guid        PlayerId;
                IPAddress   PlayerRemoteAddress;
                IPEndPoint  PlayerRemoteEndpoint;

                try
                {
                    PlayerId             = Input.ReadGuid();
                    PlayerRemoteAddress  = IPAddress.Parse(Input.ReadString());
                    PlayerRemoteEndpoint = new IPEndPoint(PlayerRemoteAddress, Input.ReadUInt16());
                }
                catch (Exception)
                {
                    Connection.Dispose();
                    return(Task.FromResult <bool>(true));
                }

                if (Input.BytesLeft == 0)
                {
                    Packet = null;
                }
                else
                {
                    Packet = Input.GetRemainingData();
                }

                bool AllConnected;

                lock (this.remotePlayersByEndpoint)
                {
                    if (!this.playersById.TryGetValue(PlayerId, out Player))
                    {
                        Connection.Dispose();
                        return(Task.FromResult <bool>(true));
                    }

                    if (Player.Connection is null)
                    {
                        this.connectionCount++;
                    }
                    else
                    {
                        Player.Connection.Dispose();
                    }

                    Player.Connection         = Connection;
                    Connection.StateObject    = Player;
                    Connection.RemoteEndpoint = Player.GetExpectedEndpoint(this.p2pNetwork);

                    AllConnected = this.connectionCount + 1 == this.playerCount;
                }

                MultiPlayerEnvironmentPlayerInformationEventHandler h = this.OnPlayerConnected;
                if (h != null)
                {
                    try
                    {
                        h(this, Player);
                    }
                    catch (Exception ex)
                    {
                        Events.Log.Critical(ex);
                    }
                }

                if (AllConnected)
                {
                    this.State = MultiPlayerState.Ready;
                }

                if (Packet is null)
                {
                    return(Task.FromResult <bool>(true));
                }
            }
            else
            {
                Player = (Player)Connection.StateObject;
                Packet = BinaryTcpClient.ToArray(Buffer, Offset, Count);
            }

            this.GameDataReceived(Player, Connection, Packet);

            return(Task.FromResult <bool>(true));
        }
Esempio n. 26
0
        private async void AcceptTcpClients()
        {
            try
            {
                while (!this.disposed && !(this.tcpListener is null))
                {
                    try
                    {
                        TcpClient TcpClient;

                        try
                        {
                            TcpClient = await this.tcpListener.AcceptTcpClientAsync();

                            if (this.disposed)
                            {
                                return;
                            }
                        }
                        catch (InvalidOperationException)
                        {
                            this.State = PeerToPeerNetworkState.Error;

                            this.tcpListener?.Stop();
                            this.tcpListener = null;

                            this.udpClient?.Dispose();
                            this.udpClient = null;

                            return;
                        }

                        if (!(TcpClient is null))
                        {
                            PeerConnection Connection = null;

                            try
                            {
                                BinaryTcpClient Client = new BinaryTcpClient(TcpClient);
                                Client.Bind(true);

                                Connection = new PeerConnection(Client, this,
                                                                (IPEndPoint)TcpClient.Client.RemoteEndPoint, this.encapsulatePackets);

                                this.State = PeerToPeerNetworkState.Ready;

                                this.PeerConnected(Connection);

                                Connection.Start();
                            }
                            catch (Exception)
                            {
                                Connection?.Dispose();
                            }
                        }
                    }
                    catch (SocketException)
                    {
                        // Ignore
                    }
                    catch (ObjectDisposedException)
                    {
                        // Ignore
                    }
                    catch (NullReferenceException)
                    {
                        // Ignore
                    }
                    catch (Exception ex)
                    {
                        Log.Critical(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                if (this.disposed)
                {
                    return;
                }

                Log.Critical(ex);
            }
        }