/// <summary>
        /// Start å lytte på meldinger.
        /// </summary>
        /// <param name="receiveMode">Receive mode (<see cref="ReceiveMode"/>)</param>
        public void StartListening(ReceiveMode receiveMode)
        {
            if (_isListening)
            {
                return;
            }

            _messagingFactory = MessagingFactory.CreateFromConnectionString(_sbCnnString);
            _isListening      = true;
            _listenTask       = Task.Run(() => Listen(receiveMode));
            ListeningStarted?.Invoke();
        }
示例#2
0
        /// <summary>
        /// Initializes a new instance of the Listener
        /// </summary>
        /// <param name="cancellationToken">The Cancellation Token to stop a transaction</param>
        /// <returns>An awaitable <see cref="Task"/> with the listener to Smtp Messages</returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            // Parameters for the SMTP Server
            ISmtpServerOptions options;

            // Setup the MessageStore
            SmtpMessageStore smtpMessageStore = new SmtpMessageStore();

            smtpMessageStore.MessageReceived           += SmtpMessageStore_MessageReceived;
            smtpMessageStore.MessageReceivedWithErrors += SmtpMessageStore_MessageReceivedWithErrors;

            // Configure the SMTP Server Parameters
            if (this.RequiresAuthentication)
            {
                // Setup the UserAuthenticator
                SmtpAuthenticator smtpAuthenticator = new SmtpAuthenticator();

                options = new SmtpServerOptionsBuilder().ServerName(this.ServerName)
                          .Port(this.Ports)
                          .AllowUnsecureAuthentication(!this.UseSSL)
                          .AuthenticationRequired(true)
                          .MessageStore(smtpMessageStore)
                          .UserAuthenticator(smtpAuthenticator)
                          .Build();
            }
            else
            {
                options = new SmtpServerOptionsBuilder().ServerName(this.ServerName)
                          .Port(this.Ports)
                          .AllowUnsecureAuthentication(!this.UseSSL)
                          .AuthenticationRequired(false)
                          .MessageStore(smtpMessageStore)
                          .Build();
            }

            // Initialize the SMTP Server
            Server = new SmtpServer.SmtpServer(options);

            // Hook the events
            Server.SessionCreated   += Server_OnSessionCreated;
            Server.SessionCompleted += Server_OnSessionCompleted;

            // Sets the Listening to on and kick event
            IsListening = true;
            ListeningStarted?.Invoke(this, null);

            // Starts the SMTP Server
            await Server.StartAsync(cancellationToken);
        }
示例#3
0
 private void OnListeningStarted(ITcpListener tcpListener) => ListeningStarted?.Invoke(this, new TcpIpListenerListen12EventArgs(tcpListener));
示例#4
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);
            }
        }
示例#5
0
 // Fired when server is started and waiting for incoming connections
 private void JavaListeningStartedHandler(string empty)
 {
     ListeningStarted?.Invoke();
 }
示例#6
0
        /// <summary>
        /// Starts Processing Commands
        /// </summary>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns>A Task which performs the operation</returns>
        public async override Task StartAsync(CancellationToken cancellationToken)
        {
            // Validate Port before starting
            if (Port == 0)
            {
                throw new Exception("Invalid port number");
            }

            // Initializes Server
            try
            {
                Server = new TcpListener(IPAddress.Any, Port);
                Server.Start(10);

                // Notify the listening started
                ListeningStarted?.Invoke(this, new ListeningStartedEventArgs(Port));

                while (cancellationToken.IsCancellationRequested == false)
                {
                    // Keep listening for incoming connections
                    var client = await Server.AcceptTcpClientAsync().WithCancellation(cancellationToken).ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();

                    // Creates the Communication Session
                    var sessionID = this.BeginSession();

                    // Notify that a session is started
                    var sessionStartedEventArgs = new SessionStartedEventArgs(sessionID);
                    SessionStarted?.Invoke(this, sessionStartedEventArgs);

                    // Make sure session is not denied
                    if (sessionStartedEventArgs.Deny)
                    {
                        // Session is denied, unregister it
                        this.EndSession(sessionID);
                    }
                    else
                    {
                        // Session is allowed, continue with it
                        var networkCommunicationSession = new NetworkCommunicationSession(client, sessionID, ShowTimer, ShowPrompt);
                        networkCommunicationSession.RawCommandReceived += (sender, commandEventArgs) =>
                        {
                            // Executes the command and waits for the answer
                            var taskResponse = Task.Run <CommandExecutionResponse>(async() => await ExecuteCommandAsync(networkCommunicationSession.ID, commandEventArgs.RawCommand));
                            var response     = taskResponse.Result;

                            // Outputs the response
                            commandEventArgs.Response = this.ResponseFormatter.Format(response);

                            // Replace "\n" by the environment NewLine
                            commandEventArgs.Response = commandEventArgs.Response.Replace("\n", System.Environment.NewLine);
                        };

                        // Add session to the collection
                        lock (NetworkCommunicationSessionsLock)
                        {
                            NetworkCommunicationSessions.Add(networkCommunicationSession.ID, networkCommunicationSession);
                        }

#pragma warning disable 4014

                        // Run Communication Session
                        networkCommunicationSession.RunAsync(cancellationToken).ContinueWith(t =>
                        {
                            // Stop Session
                            networkCommunicationSession.Stop();

                            // Remove Session from Internal Controls
                            lock (NetworkCommunicationSessionsLock)
                            {
                                NetworkCommunicationSessions.Remove(networkCommunicationSession.ID);
                            }

                            // Unregister session with the Command Processor
                            this.EndSession(networkCommunicationSession.ID);

                            // Call SessionEnded event
                            SessionEnded?.Invoke(this, new SessionEndedEventArgs(networkCommunicationSession.ID));
                        }, cancellationToken);

#pragma warning restore 4014
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (Server != null)
                {
                    Server.Stop();
                }
            }
        }
示例#7
0
 protected virtual void OnListeningStarted()
 {
     ListeningStarted.InvokeSafely();
 }