Esempio n. 1
0
        private async Task HandleTcpClientAsync(TcpClient tcpClient, int id, CancellationToken cancellationToken)
        {
            try
            {
                var tcpConnection = new TcpConnection(tcpClient);
                ConnectionAccepted?.Invoke(this, new ConnectionAcceptedEventArgs <TcpConnection> {
                    Connection = tcpConnection, AuthenticatedUserName = null
                });

                try
                {
                    await tcpConnection.WhenClosed();
                }
                finally
                {
                    ConnectionClosed?.Invoke(this, new ConnectionEventArgs <TcpConnection> {
                        Connection = tcpConnection
                    });
                }
            }
            finally
            {
                Task dummy;
                activeConnections.TryRemove(id, out dummy);
            }
        }
Esempio n. 2
0
        internal void HandleAccept(SocketAsyncEventArgs AcceptArgs)
        {
            if (AcceptArgs.SocketError != SocketError.Success)
            {
                HandleBadAccept(AcceptArgs);
                return;
            }

            StartAccept();

            SocketAsyncEventArgs ReceiveArgs;

            if (ReceivePool.TryPop(out ReceiveArgs))
            {
                ReceiveArgs.UserToken                       = (T)Activator.CreateInstance(typeof(T));
                ((T)ReceiveArgs.UserToken).Socket           = AcceptArgs.AcceptSocket;
                ((T)ReceiveArgs.UserToken).ReceiveEventArgs = ReceiveArgs;

                AcceptArgs.AcceptSocket = null;
                AcceptPool.Push(AcceptArgs);

                if (ConnectionAccepted != null)
                {
                    ConnectionAccepted.Invoke((T)ReceiveArgs.UserToken);
                }

                StartReceive(ReceiveArgs);
            }
            else
            {
                HandleAccept(AcceptArgs);
            }
        }
Esempio n. 3
0
        public ServiceClient(IClientLogic logic, IPAddress hostIP, int port, int interfaceId, long ticket)
        {
            this.logic = logic;

            client = new DynamicClient(hostIP, port);
            tree   = new ProtocolTree();
            root   = new DummyHandler <DummyProtocol>();
            auth   = new LeafProtocolHandler <AuthenticationProtocol>();

            tree.Register(root);
            tree.Register(auth);
            tree.Entry(root);
            tree.ConnectToLeaf(root, auth);
            tree.Connect(root, logic.ProtocolTree);

            app = new ApplicationConnectionManager(client, tree, 3000, 6000);

            auth.NewData += data =>
            {
                switch (data.statusCode)
                {
                case AuthenticationProtocol.StatusCode.Request:
                    Logger.Log("receiving auth request", "ServiceClient");
                    auth.Send(new AuthenticationProtocol
                    {
                        interfaceId = interfaceId,
                        ticket      = ticket,
                        resumeToken = ResumeToken,
                        statusCode  = AuthenticationProtocol.StatusCode.Ack
                    });
                    break;

                case AuthenticationProtocol.StatusCode.Accept:
                    Logger.Log("auth accepted by the host", "ServiceClient");
                    ResumeToken = data.resumeToken;
                    ConnectionAccepted?.Invoke();
                    break;

                case AuthenticationProtocol.StatusCode.Reject:
                    Logger.Log($"auth rejected by the host, {data.reason}", "ServiceClient", Logger.LogType.WARNING);
                    rejected = true;
                    client.CloseConnection();
                    app.Dispose();
                    ConnectionRejected?.Invoke();
                    break;

                default:
                    Logger.Log("invalid auth msg from host", "ServiceClient", Logger.LogType.WARNING);
                    break;
                }
            };

            app.ConnectionLost += () =>
            {
                if (!rejected)
                {
                    ConnectionLost?.Invoke();
                }
            };
        }
Esempio n. 4
0
        public void NotifyConnectionAccepted(string connectionId, string playerName = null)
        {
            var connection = new SignalRConnection(this, connectionId);

            connections[connectionId] = connection;
            ConnectionAccepted?.Invoke(this, new ConnectionAcceptedEventArgs <SignalRConnection>()
            {
                Connection            = connection,
                AuthenticatedUserName = playerName ?? "Guest"
            });
        }
Esempio n. 5
0
        public void HandleConnectResponce(object sender, ShipMessage message)
        {
            LastConnectResponce = message as ConnectResponce;

            ConnectedShip = null;

            if (LastConnectResponce.Responce == ConnectResponce.ResponceTypes.Rejected)
            {
                ConnectionRejected?.Invoke(this, LastConnectResponce);
            }
            else
            {
                ConnectionAccepted?.Invoke(this, LastConnectResponce);
            }
        }
Esempio n. 6
0
        private async Task ListenAsync(CancellationToken token)
        {
            token.Register(() => _listener?.Close());

            await Task.Run(async() =>
            {
                _listener.Listen(_limit);

                while (!token.IsCancellationRequested)
                {
                    ISocket socket = null;
                    try
                    {
                        socket = _listener.Accept();
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(ex);
                        break;
                    }

                    TcpConnection client = null;
                    try
                    {
                        if (!_connections.TryAdd(socket.RemoteEndPoint, client = new TcpConnection(socket)))
                        {
                            continue;
                        }

                        client.Closing += Client_Closing;

                        _ = client.ListenAsync(PreparePacket, token);

                        ConnectionAccepted?.Invoke(client.RemoteEndPoint);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(ex);
                    }

                    token.ThrowIfCancellationRequested();
                    await Task.Delay(INACTIVE_INTERVAL);
                }
            });

            FreeToken();
            FreeSocket();
        }
        private void onAccept(IAsyncResult result)
        {
            try
            {
                Socket socket = this.listener.EndAcceptSocket(result);

                this.control.Invoke((MethodInvoker)(() =>
                {
                    ConnectionAccepted?.Invoke(new ClientConnection(this.control, this.LocalUserName, socket));
                }));
                listener.BeginAcceptSocket(onAccept, null);
            }
            catch (ObjectDisposedException)
            {
            }
        }
Esempio n. 8
0
        private void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler  = listener.EndAccept(ar);

            Console.WriteLine("Accepted connection!");
            ConnectionAccepted?.Invoke(this, new SocketData {
                Data = "Conexão OK"
            });
            // Create the state object.
            StateObject state = new StateObject();

            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                 new AsyncCallback(ReadCallback), state);
        }
Esempio n. 9
0
 public void AcceptSocket()
 {
     if (this._socketListener != null)
     {
         this._socketListener.AcceptTcpClientAsync().ContinueWith((task) =>
         {
             if (task.IsFaulted)
             {
                 ServerSocketFail.Invoke(task, task.Exception);
             }
             else
             {
                 AcceptSocket();
                 ThreadPool.QueueUserWorkItem((o) =>
                 {
                     ConnectionAccepted?.Invoke(this, task.Result);
                 });
             }
         });
     }
 }
Esempio n. 10
0
        private async Task Listen()
        {
            Log.InfoFormat("Listening for incoming TCP/IP connections on port '{0}'", LocalEndpoint.Port);

            SocketAsyncEventArgs e         = new SocketAsyncEventArgs();
            SocketAwaitable      awaitable = new SocketAwaitable(e);

            while (true)
            {
                Log.Debug("Ready to accept new connection");

                await Socket.AcceptAsync(awaitable);

                if (e.AcceptSocket != null)
                {
                    Log.InfoFormat("Connection accepted from '{0}'", e.AcceptSocket.RemoteEndPoint);
                    ConnectionAccepted?.Invoke(this, new TcpConnectionEventArgs(new TcpConnection(e.AcceptSocket)));

                    Task.Factory.StartNew(Receive, e.AcceptSocket);
                }
            }
        }
Esempio n. 11
0
        private void AcceptSocket(IAsyncResult ar)
        {
            try
            {
                var socket = _listener.EndAcceptSocket(ar);


                Task.Run(() =>
                {
                    var session           = new Session(socket, hostKeys, ServerSettings.ServerBanner, ServerSettings.IdleTimeout);
                    session.Disconnected += (ss, ee) => { lock (_lock) sessions.Remove(session); };
                    lock (_lock)
                        sessions.Add(session);
                    try
                    {
                        ConnectionAccepted?.Invoke(this, session);
                        session.EstablishConnection();
                    }
                    catch (SshConnectionException ex)
                    {
                        session.Disconnect(ex.DisconnectReason, ex.Message);
                        ExceptionRasied?.Invoke(this, ex);
                    }
                    catch (Exception ex)
                    {
                        session.Disconnect();
                        ExceptionRasied?.Invoke(this, ex);
                    }
                });
            }
            catch
            {
            }
            finally
            {
                BeginAcceptSocket();
            }
        }
Esempio n. 12
0
        public async Task Listen()
        {
            var ps = new PipeSecurity();

            ps.AddAccessRule(new PipeAccessRule(
                                 new SecurityIdentifier(_allowedSid),
                                 PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance,
                                 AccessControlType.Allow));

            var pipeName = GetPipeName(_allowedSid, _allowedPid);

            Logger.Instance.Log($"Using named pipe {pipeName}.", LogLevel.Debug);

            Logger.Instance.Log($"Access allowed only for ProcessID {_allowedPid} and childs", LogLevel.Debug);

            while (!cancellationTokenSource.IsCancellationRequested)
            {
                using (NamedPipeServerStream dataPipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, MAX_SERVER_INSTANCES,
                                                                                  PipeTransmissionMode.Message, PipeOptions.Asynchronous, GlobalSettings.BufferSize, GlobalSettings.BufferSize, ps))
                {
                    using (NamedPipeServerStream controlPipe = new NamedPipeServerStream(pipeName + "_control", PipeDirection.InOut, MAX_SERVER_INSTANCES,
                                                                                         PipeTransmissionMode.Message, PipeOptions.Asynchronous, GlobalSettings.BufferSize, GlobalSettings.BufferSize, ps))
                    {
                        Logger.Instance.Log("NamedPipeServer listening.", LogLevel.Debug);
                        Task.WaitAll(
                            new Task[]
                        {
                            dataPipe.WaitForConnectionAsync(cancellationTokenSource.Token),
                            controlPipe.WaitForConnectionAsync(cancellationTokenSource.Token),
                        },
                            cancellationTokenSource.Token
                            );

                        if (dataPipe.IsConnected && controlPipe.IsConnected && !cancellationTokenSource.IsCancellationRequested)
                        {
                            var connection = new Connection()
                            {
                                ControlStream = controlPipe, DataStream = dataPipe
                            };

                            ConnectionKeepAliveThread.Start(connection);

                            Logger.Instance.Log("Incoming Connection.", LogLevel.Info);

                            var clientPid = dataPipe.GetClientProcessId();

                            if (!IsAuthorized(clientPid, _allowedPid))
                            {
                                Logger.Instance.Log($"Unauthorized access from PID {clientPid}", LogLevel.Warning);

                                await controlPipe.WriteAsync($"{Constants.TOKEN_ERROR}Unauthorized.{Constants.TOKEN_ERROR}").ConfigureAwait(false);

                                await controlPipe.FlushAsync().ConfigureAwait(false);

                                controlPipe.WaitForPipeDrain();

                                dataPipe.Disconnect();
                                controlPipe.Disconnect();

                                // kill the server.
                                return;
                            }

                            ConnectionAccepted?.Invoke(this, connection);

                            while (connection.IsAlive)
                            {
                                await Task.Delay(10).ConfigureAwait(false);
                            }

                            ConnectionClosed?.Invoke(this, connection);
                        }

                        Logger.Instance.Log("Listener Closed.", LogLevel.Debug);
                    }
                }
            }
        }
Esempio n. 13
0
        private void WebsocketPacketHandler_SocketMessageReceived(List <Packet> packets)
        {
            // Server may send more than one packet.
            // -------------------------------------
            foreach (var packet in packets)
            {
                if (packet.Header == ConnectionAcceptedPacket.ToString())
                {
                    if (packet.Data == null)
                    {
                        throw new Exception("Invalid packet received, packet data is null.");
                    }

                    SendPacket(new ClientInfoPacket(false, UserAgent, packet.Data["hash"].ToString(), 0, false));
                    SendPacket(new OpenAcknowledgedPacket());

                    var eventArgs = new ConnectionAcceptedEventArgs(packet.Data["conn_id"].ToString(), packet.Data["hash"].ToString());
                    ConnectionAccepted?.Invoke(this, eventArgs);
                    continue;
                }

                if (packet.Header == ConversationEndedPacket.ToString())
                {
                    // Unusual behavior, server sends "convended" without any data
                    // if "flag stranger" packet is sent and no conversation have
                    // been started before.
                    //
                    // Hence, we have to handle it like this.
                    // -----------------------------------------------------------
                    IsStrangerConnected = false;
                    if (packet.Data != null)
                    {
                        var di        = new DisconnectInfo(true, int.Parse(packet.Data.ToString()));
                        var eventArgs = new ConversationEndedEventArgs(di);

                        ConversationEnded?.Invoke(this, eventArgs);
                    }
                    else
                    {
                        var di        = new DisconnectInfo(true, -1);
                        var eventArgs = new ConversationEndedEventArgs(di);

                        ConversationEnded?.Invoke(this, eventArgs);
                    }
                    continue;
                }

                if (packet.Header == StrangerDisconnectedPacket.ToString())
                {
                    if (CurrentCID != packet.Data.ToString() && EncounteredClientIDs.Contains(packet.Data.ToString()))
                    {
                        EncounteredClientIDs.Remove(packet.Data.ToString());
                        continue;
                    }

                    IsStrangerConnected = false;

                    if (packet.Data == null)
                    {
                        throw new Exception("Invalid packet received, packet data is null.");
                    }

                    var di        = new DisconnectInfo(false, int.Parse(packet.Data.ToString()));
                    var eventArgs = new ConversationEndedEventArgs(di);

                    ConversationEnded?.Invoke(this, eventArgs);
                    continue;
                }

                if (packet.Header == MessageReceivedPacket.ToString())
                {
                    if (packet.Data == null)
                    {
                        throw new Exception("Invalid packet received, packet data is null.");
                    }

                    int postId = -1;
                    if (packet.AdditionalFields.ContainsKey("post_id"))
                    {
                        postId = int.Parse(packet.AdditionalFields["post_id"].ToString());
                    }

                    var message = new Message(
                        packet.Data["msg"].ToString(),
                        int.Parse(packet.Data["cid"].ToString()),
                        postId,
                        MessageType.Chat
                        );
                    var eventArgs = new MessageEventArgs(message);
                    MessageReceived?.Invoke(this, eventArgs);
                    continue;
                }

                if (packet.Header == OnlinePeopleCountPacket.ToString())
                {
                    if (packet.Data == null)
                    {
                        throw new Exception("Invalid packet received, packet data is null.");
                    }

                    int number;
                    if (!int.TryParse(packet.Data.ToString(), out number))
                    {
                        number = -1;
                    }

                    var eventArgs = new OnlineCountEventArgs(number);
                    OnlinePeopleCountChanged?.Invoke(this, eventArgs);
                    continue;
                }

                if (packet.Header == PingPacket.ToString())
                {
                    if (KeepAlive)
                    {
                        PongResponse();
                    }

                    var eventArgs = new PingEventArgs(DateTime.Now);
                    PingReceived?.Invoke(this, eventArgs);
                    continue;
                }

                if (packet.Header == RandomTopicReceivedPacket.ToString())
                {
                    if (packet.Data == null)
                    {
                        throw new Exception("Invalid packet received, packet data is null.");
                    }

                    var message = new Message(
                        packet.Data["topic"].ToString(),
                        int.Parse(packet.Data["cid"].ToString()),
                        int.Parse(packet.AdditionalFields["post_id"].ToString()),
                        MessageType.Topic
                        );
                    var eventArgs = new MessageEventArgs(message);
                    MessageReceived?.Invoke(this, eventArgs);
                    continue;
                }

                if (packet.Header == ServiceMessageReceivedPacket.ToString())
                {
                    if (packet.Data == null)
                    {
                        throw new Exception("Invalid packet received, packet data is null.");
                    }

                    var message   = new Message(packet.Data.ToString(), -1, -1, MessageType.Service);
                    var eventArgs = new MessageEventArgs(message);
                    MessageReceived?.Invoke(this, eventArgs);
                    continue;
                }

                if (packet.Header == StrangerChatstatePacket.ToString())
                {
                    if (packet.Data == null)
                    {
                        throw new Exception("Invalid packet received, packet data is null.");
                    }

                    bool writing;
                    if (!bool.TryParse(packet.Data.ToString(), out writing))
                    {
                        writing = false;
                    }

                    var chatState = writing ? ChatState.Writing : ChatState.Idle;
                    var eventArgs = new ChatstateEventArgs(chatState);

                    StrangerChatstateChanged?.Invoke(this, eventArgs);
                    continue;
                }

                if (packet.Header == StrangerFoundPacket.ToString())
                {
                    if (packet.Data == null)
                    {
                        throw new Exception("Invalid packet received, packet data is null.");
                    }

                    CurrentContactUID = packet.Data["ckey"].ToString();

                    SendPacket(new ConversationStartAcknowledged(CurrentContactUID));
                    ActionID++;

                    EncounteredClientIDs.Add(packet.Data["cid"].ToString());

                    IsSearchingForStranger = false;
                    IsStrangerConnected    = true;

                    var si = new StrangerInfo(
                        int.Parse(packet.Data["cid"].ToString()),
                        packet.Data["ckey"].ToString(),
                        bool.Parse(packet.Data["flaged"].ToString()),
                        packet.Data["info"]
                        );

                    var eventArgs = new StrangerFoundEventArgs(si);
                    StrangerFound?.Invoke(this, eventArgs);
                }
            }
        }
Esempio n. 14
0
        public async Task Listen()
        {
            var ps = new PipeSecurity();

            ps.AddAccessRule(new PipeAccessRule(
                                 new SecurityIdentifier(_allowedSid),
                                 PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance,
                                 AccessControlType.Allow));

            var networkSid = new SecurityIdentifier("S-1-5-2");

            // deny remote connections.
            ps.AddAccessRule(new PipeAccessRule(
                                 networkSid,
                                 PipeAccessRights.FullControl,
                                 System.Security.AccessControl.AccessControlType.Deny));

            var pipeName = NamedPipeNameFactory.GetPipeName(_allowedSid, _allowedPid);

            Logger.Instance.Log($"Listening on named pipe {pipeName}.", LogLevel.Debug);

            Logger.Instance.Log($"Access allowed only for ProcessID {_allowedPid} and children", LogLevel.Debug);

            _ = Task.Factory.StartNew(CancelIfAllowedProcessEnds, _cancellationTokenSource.Token,
                                      TaskCreationOptions.LongRunning, TaskScheduler.Current);

            do
            {
                using (NamedPipeServerStream dataPipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, MAX_SERVER_INSTANCES,
                                                                                  PipeTransmissionMode.Message, PipeOptions.Asynchronous, Settings.BufferSize, Settings.BufferSize, ps))
                {
                    using (NamedPipeServerStream controlPipe = new NamedPipeServerStream(pipeName + "_control", PipeDirection.InOut, MAX_SERVER_INSTANCES,
                                                                                         PipeTransmissionMode.Message, PipeOptions.Asynchronous, Settings.BufferSize, Settings.BufferSize, ps))
                    {
                        Logger.Instance.Log("NamedPipeServer listening.", LogLevel.Debug);
                        Task.WaitAll(
                            new Task[]
                        {
                            dataPipe.WaitForConnectionAsync(_cancellationTokenSource.Token),
                            controlPipe.WaitForConnectionAsync(_cancellationTokenSource.Token),
                        },
                            _cancellationTokenSource.Token
                            );

                        if (dataPipe.IsConnected && controlPipe.IsConnected && !_cancellationTokenSource.IsCancellationRequested)
                        {
                            var connection = new Connection()
                            {
                                ControlStream = controlPipe, DataStream = dataPipe
                            };

                            ConnectionKeepAliveThread.Start(connection);

                            Logger.Instance.Log("Incoming Connection.", LogLevel.Info);

                            var clientPid = dataPipe.GetClientProcessId();

                            if (!IsAuthorized(clientPid, _allowedPid))
                            {
                                Logger.Instance.Log($"Unauthorized access from PID {clientPid}", LogLevel.Warning);

                                await controlPipe.WriteAsync($"{Constants.TOKEN_ERROR}Unauthorized.{Constants.TOKEN_ERROR}").ConfigureAwait(false);

                                await controlPipe.FlushAsync().ConfigureAwait(false);

                                controlPipe.WaitForPipeDrain();

                                dataPipe.Disconnect();
                                controlPipe.Disconnect();

                                // kill the server.
                                return;
                            }

                            ConnectionAccepted?.Invoke(this, connection);

                            while (connection.IsAlive)
                            {
                                await Task.Delay(10).ConfigureAwait(false);
                            }

                            ConnectionClosed?.Invoke(this, connection);
                            Logger.Instance.Log("Connection Closed.", LogLevel.Info);
                        }
                    }
                }
            } while (!_singleUse && !_cancellationTokenSource.IsCancellationRequested);
            Logger.Instance.Log("Listener Closed.", LogLevel.Debug);
            _exeLock?.Close();
        }
Esempio n. 15
0
 internal void HandleConnectionAccepted(PacketServerConnection connection)
 {
     ConnectionsList.Add(connection);
     ConnectionAccepted?.Invoke(this, new PacketServerConnectionAcceptedEventArgs(connection));
     Listener.BeginAcceptTcpClient(OnConnectionAccepted, null);
 }
Esempio n. 16
0
 private void OnConnectionAccepted(WebSocketClient client)
 {
     ConnectionAccepted?.Invoke(this, new ClientEventArgs(client.Id));
 }
Esempio n. 17
0
 internal void OnConnectionAccepted(ConnectionInfo connectionInfo)
 => ConnectionAccepted?.Invoke(this, new ConnectionEventArgs(connectionInfo));
Esempio n. 18
0
 private void OnConnectionAccepted(Socket client)
 {
     ConnectionAccepted?.Invoke(client);
 }