Example #1
0
        /// <summary>
        /// Initialize the TCP server using IPAddress.Any and the given parameters.
        /// </summary>
        /// <param name="Port">The listening port</param>
        /// <param name="ServiceBanner">Service banner.</param>
        /// <param name="SplitCharacters">An array of delimiters to split the incoming CSV line into individual elements.</param>
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        /// <param name="Autostart">Start the TCP server thread immediately (default: no).</param>
        public TCPCSVServer(IPPort Port,
                            String ServiceBanner = __DefaultServiceBanner,
                            IEnumerable <Char> SplitCharacters      = null,
                            String ServerThreadName                 = null,
                            ThreadPriority ServerThreadPriority     = ThreadPriority.AboveNormal,
                            Boolean ServerThreadIsBackground        = true,
                            ConnectionIdBuilder ConnectionIdBuilder = null,
                            ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder         = null,
                            ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null,
                            Boolean ConnectionThreadsAreBackground = true,
                            TimeSpan?ConnectionTimeout             = null,
                            UInt32 MaxClientConnections            = __DefaultMaxClientConnections,
                            Boolean Autostart = false)

            : this(IPv4Address.Any,
                   Port,
                   ServiceBanner,
                   SplitCharacters,
                   ServerThreadName,
                   ServerThreadPriority,
                   ServerThreadIsBackground,
                   ConnectionIdBuilder,
                   ConnectionThreadsNameBuilder,
                   ConnectionThreadsPriorityBuilder,
                   ConnectionThreadsAreBackground,
                   ConnectionTimeout,
                   MaxClientConnections,
                   Autostart)

        {
        }
Example #2
0
        /// <summary>
        /// Initialize the TCP server using IPAddress.Any and the given parameters.
        /// </summary>
        /// <param name="IPSocket">The IP socket to listen.</param>
        /// <param name="ServiceBanner">Service banner.</param>
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        /// <param name="Autostart">Start the TCP server thread immediately (default: no).</param>
        public TCPServer(IPSocket IPSocket,
                         String ServiceBanner                    = __DefaultServiceBanner,
                         String ServerThreadName                 = null,
                         ThreadPriority ServerThreadPriority     = ThreadPriority.AboveNormal,
                         Boolean ServerThreadIsBackground        = true,
                         ConnectionIdBuilder ConnectionIdBuilder = null,
                         ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder         = null,
                         ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null,
                         Boolean ConnectionThreadsAreBackground = true,
                         TimeSpan?ConnectionTimeout             = null,
                         UInt32 MaxClientConnections            = __DefaultMaxClientConnections,
                         Boolean Autostart = false)

            : this(IPSocket.IPAddress,
                   IPSocket.Port,
                   ServiceBanner,
                   ServerThreadName,
                   ServerThreadPriority,
                   ServerThreadIsBackground,
                   ConnectionIdBuilder,
                   ConnectionThreadsNameBuilder,
                   ConnectionThreadsPriorityBuilder,
                   ConnectionThreadsAreBackground,
                   ConnectionTimeout,
                   MaxClientConnections,
                   Autostart)

        {
        }
Example #3
0
        /// <summary>
        /// Create a new TCP service allowing to attach multiple TCP servers on different IP sockets.
        /// </summary>
        /// <param name="ServiceBanner">The service banner transmitted to a TCP client after connection initialization.</param>
        /// <param name="X509Certificate">Use this X509 certificate for TLS.</param>
        /// <param name="ServerThreadName">An optional name of the TCP server threads.</param>
        /// <param name="ServerThreadPriority">An optional priority of the TCP server threads (default: AboveNormal).</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server threads are a background thread or not (default: yes).</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        /// <param name="DNSClient">The DNS client to use.</param>
        /// <param name="Autostart">Start the TCP server threads immediately (default: no).</param>
        public ATCPServers(String ServiceBanner                    = TCPServer.__DefaultServiceBanner,
                           X509Certificate2 X509Certificate        = null,
                           String ServerThreadName                 = TCPServer.__DefaultServerThreadName,
                           ThreadPriority ServerThreadPriority     = ThreadPriority.AboveNormal,
                           Boolean ServerThreadIsBackground        = true,
                           ConnectionIdBuilder ConnectionIdBuilder = null,
                           ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder         = null,
                           ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null,
                           Boolean ConnectionThreadsAreBackground = true,
                           TimeSpan?ConnectionTimeout             = null,
                           UInt32 MaxClientConnections            = TCPServer.__DefaultMaxClientConnections,
                           DNSClient DNSClient = null,
                           Boolean Autostart   = false)

        {
            this._TCPServers = new List <TCPServer>();
            this._DNSClient  = DNSClient;

            #region TCP Server

            this._ServiceBanner   = ServiceBanner;
            this._X509Certificate = X509Certificate;

            #endregion

            #region Server thread related

            this._ServerThreadName         = ServerThreadName;
            this._ServerThreadPriority     = ServerThreadPriority;
            this._ServerThreadIsBackground = ServerThreadIsBackground;

            #endregion

            #region TCP Connection

            this._ConnectionIdBuilder = (ConnectionIdBuilder != null)
                                                          ? ConnectionIdBuilder
                                                          : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => "TCP:" + RemoteIPSocket.IPAddress + ":" + RemoteIPSocket.Port;

            this._ConnectionThreadsNameBuilder = (ConnectionThreadsNameBuilder != null)
                                                          ? ConnectionThreadsNameBuilder
                                                          : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => "TCP thread " + RemoteIPSocket.IPAddress + ":" + RemoteIPSocket.Port;

            this._ConnectionThreadsPriorityBuilder = (ConnectionThreadsPriorityBuilder != null)
                                                          ? ConnectionThreadsPriorityBuilder
                                                          : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => ThreadPriority.AboveNormal;

            this._ConnectionThreadsAreBackground = ConnectionThreadsAreBackground;
            this._ConnectionTimeout = ConnectionTimeout.HasValue ? ConnectionTimeout.Value : TimeSpan.FromSeconds(30);

            #endregion

            if (Autostart)
            {
                Start();
            }
        }
Example #4
0
        /// <summary>
        /// Initialize the SMTP server using the given parameters.
        /// </summary>
        /// <param name="IPPort"></param>
        /// <param name="DefaultServerName">The default SMTP servername.</param>
        /// <param name="X509Certificate">Use this X509 certificate for TLS.</param>
        /// <param name="UseTLS">Use TLS (implicit true, if a X509 certificate was given!).</param>
        /// <param name="CallingAssemblies">Calling assemblies.</param>
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        /// <param name="DNSClient">The DNS client to use.</param>
        /// <param name="Autostart">Start the SMTP server thread immediately (default: no).</param>
        public SMTPServer(IPPort IPPort                            = null,
                          String DefaultServerName                 = __DefaultServerName,
                          X509Certificate2 X509Certificate         = null,
                          Boolean?UseTLS                           = true,
                          IEnumerable <Assembly> CallingAssemblies = null,
                          String ServerThreadName                  = null,
                          ThreadPriority ServerThreadPriority      = ThreadPriority.AboveNormal,
                          Boolean ServerThreadIsBackground         = true,
                          ConnectionIdBuilder ConnectionIdBuilder  = null,
                          ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder         = null,
                          ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null,
                          Boolean ConnectionThreadsAreBackground = true,
                          TimeSpan?ConnectionTimeout             = null,
                          UInt32 MaxClientConnections            = TCPServer.__DefaultMaxClientConnections,
                          DNSClient DNSClient = null,
                          Boolean Autostart   = false)

            : base(DefaultServerName,
                   X509Certificate,
                   ServerThreadName,
                   ServerThreadPriority,
                   ServerThreadIsBackground,
                   ConnectionIdBuilder,
                   ConnectionThreadsNameBuilder,
                   ConnectionThreadsPriorityBuilder,
                   ConnectionThreadsAreBackground,
                   ConnectionTimeout,
                   MaxClientConnections,
                   DNSClient,
                   false)

        {
            this._DefaultServerName = DefaultServerName;
            this._UseTLS            = UseTLS.HasValue
                                                 ? UseTLS.Value
                                                 : (X509Certificate != null
                                                       ? true
                                                       : false);

            _SMTPConnection = new SMTPConnection(DefaultServerName, this._UseTLS);
            _SMTPConnection.MAIL_FROMFilter += Process_MAIL_FROMFilter;
            _SMTPConnection.RCPT_TOFilter   += Process_RCPT_TOFilter;
            _SMTPConnection.OnNotification  += ProcessNotification;
            _SMTPConnection.ErrorLog        += (HTTPProcessor, ServerTimestamp, SMTPCommand, Request, Response, Error, LastException) =>
                                               LogError(ServerTimestamp, SMTPCommand, Request, Response, Error, LastException);

            if (IPPort != null)
            {
                this.AttachTCPPort(IPPort);
            }

            if (Autostart)
            {
                Start();
            }
        }
Example #5
0
        /// <summary>
        /// Initialize the TCP server using the given parameters.
        /// </summary>
        /// <param name="IIPAddress">The listening IP address(es)</param>
        /// <param name="Port">The listening port</param>
        /// <param name="ServiceBanner">Service banner.</param>
        /// <param name="SplitCharacters">An enumeration of delimiters to split the incoming CSV line into individual elements.</param>
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        /// <param name="Autostart">Start the TCP/CSV server thread immediately (default: no).</param>
        public TCPCSVServer(IIPAddress IIPAddress,
                            IPPort Port,
                            String ServiceBanner = __DefaultServiceBanner,
                            IEnumerable <Char> SplitCharacters      = null,
                            String ServerThreadName                 = null,
                            ThreadPriority ServerThreadPriority     = ThreadPriority.AboveNormal,
                            Boolean ServerThreadIsBackground        = true,
                            ConnectionIdBuilder ConnectionIdBuilder = null,
                            ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder         = null,
                            ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null,
                            Boolean ConnectionThreadsAreBackground = true,
                            TimeSpan?ConnectionTimeout             = null,
                            UInt32 MaxClientConnections            = __DefaultMaxClientConnections,
                            Boolean Autostart = false)

            : base(IIPAddress,
                   Port,
                   ServiceBanner,
                   ServerThreadName,
                   ServerThreadPriority,
                   ServerThreadIsBackground,
                   ConnectionIdBuilder,
                   ConnectionThreadsNameBuilder,
                   ConnectionThreadsPriorityBuilder,
                   ConnectionThreadsAreBackground,
                   ConnectionTimeout,
                   MaxClientConnections,
                   false)

        {
            this.ServiceBanner   = ServiceBanner;
            this.SplitCharacters = SplitCharacters != null?SplitCharacters.ToArray() : DefaultSpitCharacters;

            this._TCPCSVProcessor = new TCPCSVProcessor(this.SplitCharacters);
            this.SendTo(_TCPCSVProcessor);
            //  this.OnNewConnection         += (TCPServer, Timestamp, RemoteSocket, ConnectionId, TCPConnection) => SendNewConnection   (Timestamp, RemoteSocket, ConnectionId, TCPConnection);
            //  this.OnConnectionClosed      += (TCPServer, Timestamp, RemoteSocket, ConnectionId, ClosedBy)      => SendConnectionClosed(Timestamp, RemoteSocket, ConnectionId, ClosedBy);

            this._TCPCSVCommandProcessor = new TCPCSVCommandProcessor();
            this._TCPCSVProcessor.ConnectTo(_TCPCSVCommandProcessor);
            this._TCPCSVCommandProcessor.OnNotification += ProcessBoomerang;

            if (Autostart)
            {
                Start();
            }
        }
Example #6
0
        /// <summary>
        /// Initialize the SOAP server using the given parameters.
        /// </summary>
        /// <param name="TCPPort">An IP port to listen on.</param>
        /// <param name="DefaultServerName">The default HTTP servername, used whenever no HTTP Host-header had been given.</param>
        /// <param name="SOAPContentType">The default HTTP content type used for all SOAP requests/responses.</param>
        /// <param name="X509Certificate">Use this X509 certificate for TLS.</param>
        /// <param name="CallingAssemblies">A list of calling assemblies to include e.g. into embedded ressources lookups.</param>
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        /// <param name="DNSClient">The DNS client to use.</param>
        /// <param name="Autostart">Start the HTTP server thread immediately (default: no).</param>
        public SOAPServer(IPPort TCPPort                           = null,
                          String DefaultServerName                 = DefaultHTTPServerName,
                          HTTPContentType SOAPContentType          = null,
                          X509Certificate2 X509Certificate         = null,
                          IEnumerable <Assembly> CallingAssemblies = null,
                          String ServerThreadName                  = null,
                          ThreadPriority ServerThreadPriority      = ThreadPriority.AboveNormal,
                          Boolean ServerThreadIsBackground         = true,
                          ConnectionIdBuilder ConnectionIdBuilder  = null,
                          ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder         = null,
                          ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null,
                          Boolean ConnectionThreadsAreBackground = true,
                          TimeSpan?ConnectionTimeout             = null,
                          UInt32 MaxClientConnections            = TCPServer.__DefaultMaxClientConnections,
                          DNSClient DNSClient = null,
                          Boolean Autostart   = false)

            : base(TCPPort,
                   DefaultServerName,
                   X509Certificate,
                   CallingAssemblies,
                   ServerThreadName,
                   ServerThreadPriority,
                   ServerThreadIsBackground,
                   ConnectionIdBuilder,
                   ConnectionThreadsNameBuilder,
                   ConnectionThreadsPriorityBuilder,
                   ConnectionThreadsAreBackground,
                   ConnectionTimeout,
                   MaxClientConnections,
                   DNSClient,
                   false)

        {
            this.SOAPContentType  = SOAPContentType != null ? SOAPContentType : DefaultSOAPContentType;
            this._SOAPDispatchers = new Dictionary <String, SOAPDispatcher>();

            if (Autostart)
            {
                Start();
            }
        }
Example #7
0
        /// <summary>
        /// Create an instance of the Open Charging Cloud API.
        /// </summary>
        /// <param name="ServiceName">The name of the service.</param>
        /// <param name="HTTPServerName">The default HTTP servername, used whenever no HTTP Host-header had been given.</param>
        /// <param name="LocalHostname">The HTTP hostname for all URIs within this API.</param>
        /// <param name="LocalPort">A TCP port to listen on.</param>
        /// <param name="ExternalDNSName">The offical URL/DNS name of this service, e.g. for sending e-mails.</param>
        /// <param name="URLPathPrefix">A common prefix for all URLs.</param>
        ///
        /// <param name="ServerCertificateSelector">An optional delegate to select a SSL/TLS server certificate.</param>
        /// <param name="ClientCertificateValidator">An optional delegate to verify the SSL/TLS client certificate used for authentication.</param>
        /// <param name="ClientCertificateSelector">An optional delegate to select the SSL/TLS client certificate used for authentication.</param>
        /// <param name="AllowedTLSProtocols">The SSL/TLS protocol(s) allowed for this connection.</param>
        ///
        /// <param name="APIEMailAddress">An e-mail address for this API.</param>
        /// <param name="APIPassphrase">A GPG passphrase for this API.</param>
        /// <param name="APIAdminEMails">A list of admin e-mail addresses.</param>
        /// <param name="APISMTPClient">A SMTP client for sending e-mails.</param>
        ///
        /// <param name="SMSAPICredentials">The credentials for the SMS API.</param>
        /// <param name="SMSSenderName">The (default) SMS sender name.</param>
        /// <param name="APIAdminSMS">A list of admin SMS phonenumbers.</param>
        ///
        /// <param name="TelegramBotToken">The Telegram API access token of the bot.</param>
        ///
        /// <param name="CookieName">The name of the HTTP Cookie for authentication.</param>
        /// <param name="UseSecureCookies">Force the web browser to send cookies only via HTTPS.</param>
        /// <param name="Language">The main language of the API.</param>
        /// <param name="NewUserSignUpEMailCreator">A delegate for sending a sign-up e-mail to a new user.</param>
        /// <param name="NewUserWelcomeEMailCreator">A delegate for sending a welcome e-mail to a new user.</param>
        /// <param name="ResetPasswordEMailCreator">A delegate for sending a reset password e-mail to a user.</param>
        /// <param name="PasswordChangedEMailCreator">A delegate for sending a password changed e-mail to a user.</param>
        /// <param name="MinUserNameLength">The minimal user name length.</param>
        /// <param name="MinRealmLength">The minimal realm length.</param>
        /// <param name="PasswordQualityCheck">A delegate to ensure a minimal password quality.</param>
        /// <param name="SignInSessionLifetime">The sign-in session lifetime.</param>
        ///
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        ///
        /// <param name="SkipURLTemplates">Skip URI templates.</param>
        /// <param name="DisableNotifications">Disable external notifications.</param>
        /// <param name="DisableLogfile">Disable the log file.</param>
        /// <param name="LoggingPath">The path for all logfiles.</param>
        /// <param name="LogfileName">The name of the logfile for this API.</param>
        /// <param name="DNSClient">The DNS client of the API.</param>
        /// <param name="Autostart">Whether to start the API automatically.</param>
        public OpenChargingCloudCSOAPI(String ServiceName         = "GraphDefined Open Charging Cloud CSO API",
                                       String HTTPServerName      = "GraphDefined Open Charging Cloud CSO API",
                                       HTTPHostname?LocalHostname = null,
                                       IPPort?LocalPort           = null,
                                       String ExternalDNSName     = null,
                                       HTTPPath?URLPathPrefix     = null,
                                       String HTMLTemplate        = null,
                                       JObject APIVersionHashes   = null,

                                       ServerCertificateSelectorDelegate ServerCertificateSelector    = null,
                                       RemoteCertificateValidationCallback ClientCertificateValidator = null,
                                       LocalCertificateSelectionCallback ClientCertificateSelector    = null,
                                       SslProtocols AllowedTLSProtocols = SslProtocols.Tls12,

                                       EMailAddress APIEMailAddress    = null,
                                       String APIPassphrase            = null,
                                       EMailAddressList APIAdminEMails = null,
                                       SMTPClient APISMTPClient        = null,

                                       Credentials SMSAPICredentials         = null,
                                       String SMSSenderName                  = null,
                                       IEnumerable <PhoneNumber> APIAdminSMS = null,

                                       String TelegramBotToken = null,

                                       HTTPCookieName?CookieName = null,
                                       Boolean UseSecureCookies  = true,
                                       Languages?Language        = null,
                                       NewUserSignUpEMailCreatorDelegate NewUserSignUpEMailCreator     = null,
                                       NewUserWelcomeEMailCreatorDelegate NewUserWelcomeEMailCreator   = null,
                                       ResetPasswordEMailCreatorDelegate ResetPasswordEMailCreator     = null,
                                       PasswordChangedEMailCreatorDelegate PasswordChangedEMailCreator = null,
                                       Byte?MinLoginLength    = null,
                                       Byte?MinRealmLength    = null,
                                       Byte?MinUserNameLength = null,
                                       PasswordQualityCheckDelegate PasswordQualityCheck = null,
                                       TimeSpan?SignInSessionLifetime = null,

                                       String ServerThreadName                 = null,
                                       ThreadPriority ServerThreadPriority     = ThreadPriority.AboveNormal,
                                       Boolean ServerThreadIsBackground        = true,
                                       ConnectionIdBuilder ConnectionIdBuilder = null,
                                       ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder         = null,
                                       ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null,
                                       Boolean ConnectionThreadsAreBackground = true,
                                       TimeSpan?ConnectionTimeout             = null,
                                       UInt32 MaxClientConnections            = TCPServer.__DefaultMaxClientConnections,

                                       TimeSpan?MaintenanceEvery       = null,
                                       Boolean DisableMaintenanceTasks = false,

                                       Boolean SkipURLTemplates     = false,
                                       Boolean DisableNotifications = false,
                                       Boolean DisableLogfile       = false,
                                       String DatabaseFile          = DefaultOpenChargingCloudAPIDatabaseFile,
                                       String LoggingPath           = null,
                                       String LogfileName           = DefaultOpenChargingCloudAPILogFile,
                                       DNSClient DNSClient          = null,
                                       Boolean Autostart            = false)

            : base(ServiceName ?? "GraphDefined Open Charging Cloud CSO API",
                   HTTPServerName ?? "GraphDefined Open Charging Cloud CSO API",
                   LocalHostname,
                   LocalPort,
                   ExternalDNSName,
                   URLPathPrefix,
                   HTMLTemplate,
                   APIVersionHashes,

                   ServerCertificateSelector,
                   ClientCertificateValidator,
                   ClientCertificateSelector,
                   AllowedTLSProtocols,

                   APIEMailAddress,
                   APIPassphrase,
                   APIAdminEMails,
                   APISMTPClient,

                   SMSAPICredentials,
                   SMSSenderName ?? "Open Charging Cloud",
                   APIAdminSMS,

                   TelegramBotToken,

                   CookieName ?? HTTPCookieName.Parse("OpenChargingCloudCSOAPI"),
                   UseSecureCookies,
                   Language,
                   NewUserSignUpEMailCreator,
                   NewUserWelcomeEMailCreator,
                   ResetPasswordEMailCreator,
                   PasswordChangedEMailCreator,
                   MinLoginLength,
                   MinRealmLength,
                   MinUserNameLength,
                   PasswordQualityCheck,
                   SignInSessionLifetime,

                   ServerThreadName,
                   ServerThreadPriority,
                   ServerThreadIsBackground,
                   ConnectionIdBuilder,
                   ConnectionThreadsNameBuilder,
                   ConnectionThreadsPriorityBuilder,
                   ConnectionThreadsAreBackground,
                   ConnectionTimeout,
                   MaxClientConnections,

                   MaintenanceEvery,
                   DisableMaintenanceTasks,

                   SkipURLTemplates,
                   DisableNotifications,
                   DisableLogfile,
                   DatabaseFile ?? DefaultOpenChargingCloudCSOAPIDatabaseFile,
                   LoggingPath ?? "default",
                   LogfileName ?? DefaultOpenChargingCloudCSOAPILogFile,
                   DNSClient,
                   false)

        {
            //RegisterURLTemplates();

            if (Autostart)
            {
                Start();
            }
        }
        /// <summary>
        /// Initialize the GraphDevroom HTTP API using IPAddress.Any, http port 8080 and start the server.
        /// </summary>
        /// <param name="IPPort">The IP listing port.</param>
        public GraphDevroomHTTPAPI(IPPort                                                                   IPPort                            = null,
                                   String                                                                   DefaultServerName                 = __DefaultServerName,
                                   String                                                                   HTTPRoot                          = __DefaultHTTPRoot,
                                   String                                                                   URIPrefix                         = "",

                                   IGenericPropertyGraph<UInt64, Int64, GDVertexLabel,    String, Object,
                                                         UInt64, Int64, GDEdgeLabel,      String, Object,
                                                         UInt64, Int64, GDMultiEdgeLabel, String, Object,
                                                         UInt64, Int64, GDHyperEdgeLabel, String, Object>   Graph                             = null,

                                   String                                                                   ServerThreadName                  = null,
                                   ThreadPriority                                                           ServerThreadPriority              = ThreadPriority.AboveNormal,
                                   Boolean                                                                  ServerThreadIsBackground          = true,

                                   ConnectionIdBuilder                                                      ConnectionIdBuilder               = null,
                                   ConnectionThreadsNameBuilder                                             ConnectionThreadsNameBuilder      = null,
                                   ConnectionThreadsPriorityBuilder                                         ConnectionThreadsPriorityBuilder  = null,
                                   Boolean                                                                  ConnectionThreadsAreBackground    = true,
                                   TimeSpan?                                                                ConnectionTimeout                 = null,
                                   UInt32                                                                   MaxClientConnections              = TCPServer.__DefaultMaxClientConnections,

                                   IEnumerable<Assembly>                                                    CallingAssemblies                 = null,

                                   Boolean                                                                  Autostart                         = false)
            : base((IPPort != null) ? IPPort : IPPort.Parse(8080),
                   "",
                   DefaultServerName,

                   //ServerThreadName,
                   //ServerThreadPriority,
                   //ServerThreadIsBackground,
                   //
                   //ConnectionIdBuilder,
                   //ConnectionThreadsNameBuilder,
                   //ConnectionThreadsPriorityBuilder,
                   //ConnectionThreadsAreBackground,
                   //
                   //ConnectionTimeout,
                   //MaxClientConnections,
                   Autostart: false)
        {
            this._Graph            = (Graph != null) ? Graph : GraphDevroomGraphFactory.Create(1, "FOSDEM GraphDevroom Graph");
            this._HTTPRoot         = HTTPRoot;
            //this._Logger           = Logger;

            #region / (HTTPRoot)

            //this.RegisterResourcesFolder(URIPrefix + "/",
            //                             _HTTPRoot,
            //                             DefaultFilename: "index.html");

            // Redirect to GitHub pages
            this.RegisterMovedTemporarilyHandler("/", "http://graphdevroom.github.io");

            #endregion

            #region /raw

            this.AddMethodCallback(HTTPMethod.GET,
                                   "/raw",
                                   HTTPContentType.HTML_UTF8,
                                   HTTPRequest => {

                                       return new HTTPResponseBuilder()
                                       {
                                           HTTPStatusCode  = HTTPStatusCode.OK,
                                           ContentType     = HTTPContentType.TEXT_UTF8,
                                           Content         = HTTPRequest.RawHTTPHeader.ToString().ToUTF8Bytes(),
                                           CacheControl    = "private",
                                           //Expires         = "Mon, 25 Jun 2015 21:31:12 GMT",
                                           Connection      = "close"
                                       };

                                   });

            #endregion

            #region ~/{Year}/{Event}/schedule

            #region GET         ~/{Year}/{Event}/schedule

            #region HTML_UTF8

            // -----------------------------------------------------------------------------
            // curl -v -H "Accept: text/html" http://127.0.0.1:8080/{Year}/{Event}/schedule
            // -----------------------------------------------------------------------------
            this.AddMethodCallback(HTTPMethod.GET,
                                   "/{Year}/{Event}/schedule",
                                   HTTPContentType.HTML_UTF8,
                                   HTTPDelegate: HTTPRequest => {

                                       #region Parse Year

                                       UInt16 Year;

                                       if (HTTPRequest.ParsedURIParameters.Length < 1)
                                       {

                                           Log.Timestamp("Bad request: Missing year query parameter!");

                                           return new HTTPResponseBuilder() {
                                               HTTPStatusCode  = HTTPStatusCode.BadRequest,
                                               ContentType     = HTTPContentType.JSON_UTF8,
                                               Content         = new JObject(new JProperty("@context",    "http://emi3group.org/contexts/BadRequest.jsonld"),
                                                                             new JProperty("Description", "Missing year query parameter!")).
                                                                             ToString().ToUTF8Bytes()
                                           };

                                       }

                                       if (!UInt16.TryParse(HTTPRequest.ParsedURIParameters[0], out Year))
                                       {

                                           Log.Timestamp("Bad request: Invalid year query parameter!");

                                           return new HTTPResponseBuilder() {
                                               HTTPStatusCode  = HTTPStatusCode.BadRequest,
                                               ContentType     = HTTPContentType.JSON_UTF8,
                                               Content         = new JObject(new JProperty("@context",    "http://emi3group.org/contexts/BadRequest.jsonld"),
                                                                             new JProperty("Value",       HTTPRequest.ParsedURIParameters[0]),
                                                                             new JProperty("Description", "Invalid year query parameter!")).
                                                                             ToString().ToUTF8Bytes()
                                           };

                                       }

                                       #endregion

                                       var Content = "lala";

                                       return new HTTPResponseBuilder() {
                                           HTTPStatusCode  = HTTPStatusCode.OK,
                                           Server          = this.DefaultServerName,
                                           ETag            = "1",
                                           ContentType     = HTTPContentType.HTML_UTF8,
                                           Content         = Content.ToUTF8Bytes(),
                                           CacheControl    = "no-cache"
                                       };

                                   });

            #endregion

            #endregion

            #endregion

            this.AddEventSource(EventIdentification:     "Semantics.DebugLog",
                                MaxNumberOfCachedEvents: 100,
                                RetryIntervall:          TimeSpan.FromSeconds(5),
                                URITemplate:             URIPrefix + "/DebugLog");

            // HTTP ACCEPT TYPE  !=  HTTP CONTENT TYPE !!!

            if (Autostart)
                this.Start();
        }
Example #9
0
        /// <summary>
        /// Initialize the TCP server using the given parameters.
        /// </summary>
        /// <param name="IIPAddress">The listening IP address(es)</param>
        /// <param name="Port">The listening port</param>
        /// <param name="ServiceBanner">Service banner.</param>
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        /// <param name="Autostart">Start the TCP server thread immediately (default: no).</param>
        public TCPServer(IIPAddress IIPAddress,
                         IPPort Port,
                         String ServiceBanner                    = __DefaultServiceBanner,
                         String ServerThreadName                 = null,
                         ThreadPriority ServerThreadPriority     = ThreadPriority.AboveNormal,
                         Boolean ServerThreadIsBackground        = true,
                         ConnectionIdBuilder ConnectionIdBuilder = null,
                         ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder         = null,
                         ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null,
                         Boolean ConnectionThreadsAreBackground = true,
                         TimeSpan?ConnectionTimeout             = null,
                         UInt32 MaxClientConnections            = __DefaultMaxClientConnections,
                         Boolean Autostart = false)

        {
            #region TCP Socket

            this._IPAddress   = IIPAddress;
            this._Port        = Port;
            this._IPSocket    = new IPSocket(_IPAddress, _Port);
            this._TCPListener = new TcpListener(new System.Net.IPAddress(_IPAddress.GetBytes()), _Port.ToInt32());

            #endregion

            #region TCP Server

            this._ServiceBanner = (ServiceBanner.IsNotNullOrEmpty())
                                                          ? ServiceBanner
                                                          : __DefaultServiceBanner;

            this.ServerThreadName = (ServerThreadName != null)
                                                          ? ServerThreadName
                                                          : __DefaultServerThreadName + this.IPSocket.ToString();

            this.ServerThreadPriority     = ServerThreadPriority;
            this.ServerThreadIsBackground = ServerThreadIsBackground;

            #endregion

            #region TCP Connections

            this._TCPConnections = new ConcurrentDictionary <IPSocket, TCPConnection>();


            this.ConnectionIdBuilder = (ConnectionIdBuilder != null)
                                                          ? ConnectionIdBuilder
                                                          : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => "TCP:" + RemoteIPSocket.IPAddress + ":" + RemoteIPSocket.Port;

            this.ConnectionThreadsNameBuilder = (ConnectionThreadsNameBuilder != null)
                                                          ? ConnectionThreadsNameBuilder
                                                          : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => "TCP thread " + RemoteIPSocket.IPAddress + ":" + RemoteIPSocket.Port;

            this.ConnectionThreadsPriorityBuilder = (ConnectionThreadsPriorityBuilder != null)
                                                          ? ConnectionThreadsPriorityBuilder
                                                          : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => ThreadPriority.AboveNormal;

            this.ConnectionThreadsAreBackground = ConnectionThreadsAreBackground;

            this._ConnectionTimeout = ConnectionTimeout.HasValue
                                                          ? ConnectionTimeout.Value
                                                          : TimeSpan.FromSeconds(30);

            this._MaxClientConnections = MaxClientConnections;

            #endregion

            #region TCP Listener Thread

            this.CancellationTokenSource = new CancellationTokenSource();
            this.CancellationToken       = CancellationTokenSource.Token;

            _ListenerThread = new Thread(() => {
#if __MonoCS__
                // Code for Mono C# compiler
#else
                Thread.CurrentThread.Name         = this.ServerThreadName;
                Thread.CurrentThread.Priority     = this.ServerThreadPriority;
                Thread.CurrentThread.IsBackground = this.ServerThreadIsBackground;
#endif

                #region SetSocketOptions

                // IOControlCode.*

                // fd.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, tcpKeepalive);

                // bytes.PutInteger(endian, tcpKeepalive,      0);
                // bytes.PutInteger(endian, tcpKeepaliveIdle,  4);
                // bytes.PutInteger(endian, tcpKeepaliveIntvl, 8);

                // fd.IOControl(IOControlCode.KeepAliveValues, (byte[])bytes, null);

                #endregion

                try
                {
                    _IsRunning = true;

                    while (!_StopRequested)
                    {
                        // Wait for a new/pending client connection
                        while (!_StopRequested && !_TCPListener.Pending())
                        {
                            Thread.Sleep(5);
                        }

                        // Break when a server stop was requested
                        if (_StopRequested)
                        {
                            break;
                        }

                        // Processing the pending client connection within its own task
                        var NewTCPClient = _TCPListener.AcceptTcpClient();
                        //  var NewTCPConnection = _TCPListener.AcceptTcpClientAsync().
                        //                                      ContinueWith(a => new TCPConnection(this, a.Result));
                        //                                  //    ConfigureAwait(false);

                        // Store the new connection
                        //_SocketConnections.AddOrUpdate(_TCPConnection.Value.RemoteSocket,
                        //                               _TCPConnection.Value,
                        //                               (RemoteEndPoint, TCPConnection) => TCPConnection);

                        Task.Factory.StartNew(Tuple => {
                            try
                            {
                                var _Tuple = Tuple as Tuple <TCPServer, TcpClient>;

                                var NewTCPConnection = new ThreadLocal <TCPConnection>(
                                    () => new TCPConnection(_Tuple.Item1, _Tuple.Item2)
                                    );

                                #region Copy ExceptionOccured event handlers

                                //foreach (var ExceptionOccuredHandler in MyEventStorage)
                                //    _TCPConnection.Value.OnExceptionOccured += ExceptionOccuredHandler;

                                #endregion

                                #region OnNewConnection

                                // If this event closes the TCP connection the OnNotification event will never be fired!
                                // Therefore you can use this event for filtering connection initiation requests.
                                OnNewConnection?.Invoke(NewTCPConnection.Value.TCPServer,
                                                        NewTCPConnection.Value.ServerTimestamp,
                                                        NewTCPConnection.Value.RemoteSocket,
                                                        NewTCPConnection.Value.ConnectionId,
                                                        NewTCPConnection.Value);

                                if (!NewTCPConnection.Value.IsClosed)
                                {
                                    OnNotification?.Invoke(NewTCPConnection.Value);
                                }

                                #endregion
                            }
                            catch (Exception e)
                            {
                                while (e.InnerException != null)
                                {
                                    e = e.InnerException;
                                }

                                OnExceptionOccured?.Invoke(this, DateTime.Now, e);
                                Console.WriteLine(DateTime.Now + " " + e.Message + Environment.NewLine + e.StackTrace);
                            }
                        }, new Tuple <TCPServer, TcpClient>(this, NewTCPClient));
                    }

                    #region Shutdown

                    // Request all client connections to finish!
                    foreach (var _SocketConnection in _TCPConnections)
                    {
                        _SocketConnection.Value.StopRequested = true;
                    }

                    // After stopping the TCPListener wait for
                    // all client connections to finish!
                    while (_TCPConnections.Count > 0)
                    {
                        Thread.Sleep(5);
                    }

                    #endregion
                }

                #region Exception handling

                catch (Exception Exception)
                {
                    var OnExceptionLocal = OnExceptionOccured;
                    if (OnExceptionLocal != null)
                    {
                        OnExceptionLocal(this, DateTime.Now, Exception);
                    }
                }

                #endregion

                _IsRunning = false;
            });

            #endregion

            if (Autostart)
            {
                Start();
            }
        }
Example #10
0
        /// <summary>
        /// Initialize the SOAP server using the given parameters.
        /// </summary>
        /// <param name="TCPPort">An IP port to listen on.</param>
        /// <param name="DefaultServerName">The default HTTP servername, used whenever no HTTP Host-header had been given.</param>
        /// <param name="SOAPContentType">The default HTTP content type used for all SOAP requests/responses.</param>
        /// <param name="X509Certificate">Use this X509 certificate for TLS.</param>
        /// <param name="CallingAssemblies">A list of calling assemblies to include e.g. into embedded ressources lookups.</param>
        /// <param name="ServerThreadName">The optional name of the TCP server thread.</param>
        /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param>
        /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param>
        /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param>
        /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param>
        /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param>
        /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param>
        /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param>
        /// <param name="DNSClient">The DNS client to use.</param>
        /// <param name="Autostart">Start the HTTP server thread immediately (default: no).</param>
        public SOAPServer(IPPort                            TCPPort                           = null,
                          String                            DefaultServerName                 = DefaultHTTPServerName,
                          HTTPContentType                   SOAPContentType                   = null,
                          X509Certificate2                  X509Certificate                   = null,
                          IEnumerable<Assembly>             CallingAssemblies                 = null,
                          String                            ServerThreadName                  = null,
                          ThreadPriority                    ServerThreadPriority              = ThreadPriority.AboveNormal,
                          Boolean                           ServerThreadIsBackground          = true,
                          ConnectionIdBuilder               ConnectionIdBuilder               = null,
                          ConnectionThreadsNameBuilder      ConnectionThreadsNameBuilder      = null,
                          ConnectionThreadsPriorityBuilder  ConnectionThreadsPriorityBuilder  = null,
                          Boolean                           ConnectionThreadsAreBackground    = true,
                          TimeSpan?                         ConnectionTimeout                 = null,
                          UInt32                            MaxClientConnections              = TCPServer.__DefaultMaxClientConnections,
                          DNSClient                         DNSClient                         = null,
                          Boolean                           Autostart                         = false)
            : base(TCPPort,
                   DefaultServerName,
                   X509Certificate,
                   CallingAssemblies,
                   ServerThreadName,
                   ServerThreadPriority,
                   ServerThreadIsBackground,
                   ConnectionIdBuilder,
                   ConnectionThreadsNameBuilder,
                   ConnectionThreadsPriorityBuilder,
                   ConnectionThreadsAreBackground,
                   ConnectionTimeout,
                   MaxClientConnections,
                   DNSClient,
                   false)
        {
            this.SOAPContentType  = SOAPContentType != null ? SOAPContentType : DefaultSOAPContentType;
            this._SOAPDispatchers  = new Dictionary<String, SOAPDispatcher>();

            if (Autostart)
                Start();
        }