Exemplo n.º 1
0
        public async Task StartListening(int port)
        {
            try
            {
                _tcpListener = new TcpListener(IPAddress.Any, port);
                _tcpListener.Start();

                while (true)
                {
                    await AwaitConnection(_tcpListener);
                }
            }
            catch (Exception ex)
            {
                _logger.Trace(ex, "Connection listening stopped, no new connections can be made.");
                ListeningStopped?.Invoke(this, EventArgs.Empty);
            }
        }
Exemplo n.º 2
0
        public static void StartAutomationListener(int port)
        {
            try
            {
                // TcpListener server = new TcpListener(port);
                _tcpListener = new TcpListener(IPAddress.Any, port);
                _port        = port;

                // Start listening for client requests.
                _tcpListener.Start();

                _automationLogger.Information($"Automation Listener Endpoint started at {_tcpListener.LocalEndpoint}");

                // Buffer for reading data
                Byte[] bytes = new Byte[2048];
                String data  = null;

                // Enter the listening loop.
                while (true)
                {
                    IsListening = true;

                    ListeningStarted?.Invoke(null, null);
                    _automationLogger.Information($"Automation Listener Waiting for Request");

                    TcpClient client = _tcpListener.AcceptTcpClient();

                    _automationLogger.Information($"Client '{client.Client.RemoteEndPoint}' Connected to Automation Listener");

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();
                    int           i;

                    try
                    {
                        // Loop to receive all the data sent by the client.
                        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                        {
                            // Translate data bytes to a ASCII string.
                            data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                            _automationLogger.Information($"Client Message Content: {data}");

                            //break out request content
                            var messageContent = data.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

                            if (_listenerSettings.EnableWhitelist)
                            {
                                _automationLogger.Information($"Listener requires IP Verification (Whitelist)");

                                //verify that client is allowed to connect
                                var clientAddress = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();

                                //get list of ip
                                var enabledIPs = _listenerSettings.IPWhiteList.Split(',');

                                if (enabledIPs.Any(s => s.Trim().Contains(clientAddress)))
                                {
                                    _automationLogger.Information($"Client '{clientAddress}' verified from WhiteList '{_listenerSettings.IPWhiteList}'");
                                }
                                else
                                {
                                    _automationLogger.Information($"Closing Client Connection due to IP verification failure");
                                    SendResponse(HttpStatusCode.Unauthorized, $"Unauthorized", stream);
                                    return;
                                }
                            }
                            else
                            {
                                _automationLogger.Information($"Listener does not require IP Verification");
                            }

                            if (_listenerSettings.RequireListenerAuthenticationKey)
                            {
                                string authKey = "";
                                foreach (var item in messageContent)
                                {
                                    if (item.StartsWith("AuthKey: "))
                                    {
                                        authKey = item.Replace("AuthKey: ", "");
                                        break;
                                    }
                                }

                                //auth key check
                                if (string.IsNullOrEmpty(authKey))
                                {
                                    //auth key not provided
                                    _automationLogger.Information($"Closing Client Connection due to Null/Empty Auth Key");
                                    SendResponse(HttpStatusCode.Unauthorized, $"Invalid Auth Key", stream);
                                    break;
                                }
                                else if (authKey != _listenerSettings.AuthKey)
                                {
                                    //auth key invalid
                                    _automationLogger.Information($"Closing Client Connection due to Invalid Auth Key");
                                    SendResponse(HttpStatusCode.Unauthorized, $"Invalid Auth Key", stream);
                                    break;
                                }
                                else if (authKey == _listenerSettings.AuthKey)
                                {
                                    //auth key valid
                                    _automationLogger.Information($"Auth Key Verified");
                                    ProcessRequest(data, messageContent, stream);
                                }
                            }
                            else
                            {
                                //verification not required
                                _automationLogger.Information($"Auth Key Verification Not Required");
                                ProcessRequest(data, messageContent, stream);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _automationLogger.Information($"Error Occured Reading Stream: {ex}");
                    }

                    // Shutdown and end connection
                    client.Close();
                    _automationLogger.Information($"Client Connection Closed");
                }
            }
            catch (SocketException e)
            {
                _automationLogger.Information("SocketException: {0}", e);
            }
            finally
            {
                // Stop listening for new clients.
                _tcpListener.Stop();
                IsListening = false;
                ListeningStopped?.Invoke(null, null);
            }
        }
Exemplo n.º 3
0
 // Fired when listening for incoming connections
 // was stopped by StopListening()
 private void JavaListeningStoppedHandler(string empty)
 {
     ListeningStopped?.Invoke();
 }