Example #1
0
        public RoamingNetworkInfo(Tracker_Id TrackerId,
                                  String IncomingURI,
                                  DateTime ExpiredAfter,

                                  RoamingNetwork_Id RoamingNetworkId,
                                  Byte priority,
                                  Byte weight,
                                  String hostname,
                                  IPPort port,
                                  TransportTypes transport,
                                  String uriPrefix,
                                  HTTPContentType contentType,
                                  ProtocolTypes protocolType,
                                  IEnumerable <String> PublicKeys)
        {
            this.TrackerId    = TrackerId;
            this.IncomingURI  = IncomingURI;
            this.ExpiredAfter = ExpiredAfter;

            this.RoamingNetworkId = RoamingNetworkId;

            this.priority     = priority;
            this.weight       = weight;
            this.hostname     = hostname;
            this.port         = port;
            this.transport    = transport;
            this.uriPrefix    = uriPrefix;
            this.contentType  = contentType;
            this.protocolType = protocolType;
            this.publicKeys   = PublicKeys;

            this.AnnouncedURI = String.Concat(transport, "://", hostname, ":", port, uriPrefix, "_", contentType);
        }
 private void SendChatMess(String text, IPPort ipPort)
 {
     byte[] textbyte = System.Text.Encoding.UTF8.GetBytes(text);
     byte[] sendbyte = null;
     sendbyte = new byte[] { 8, 1, (byte)ipPort.UserId }.Concat(textbyte).ToArray();
     udpProtocol.UdpSocketSend(ipPort.IP, ipPort.Port, sendbyte);
 }
Example #3
0
        /// <summary>
        /// Create a new UDP/CSV receiver using IPAddress.Any and the given parameters.
        /// </summary>
        /// <param name="Port">The port to listen.</param>
        /// <param name="ServiceBanner">Service banner.</param>
        /// <param name="Splitter">An array of delimiters to split the incoming CSV line into individual elements.</param>
        /// <param name="ReceiverThreadName">The optional name of the UDP receiver thread.</param>
        /// <param name="ReceiverThreadPriority">The optional priority of the UDP receiver thread.</param>
        /// <param name="ReceiverThreadIsBackground">Whether the UDP receiver thread is a background thread or not.</param>
        /// <param name="PacketThreadsNameCreator">An optional delegate to set the name of the UDP packet threads.</param>
        /// <param name="PacketThreadsPriority">The optional priority of the UDP packet threads.</param>
        /// <param name="PacketThreadsAreBackground">Whether the UDP packet threads are background threads or not.</param>
        /// <param name="Autostart">Start the UDP receiver thread immediately.</param>
        public UDPCSVReceiver(IPPort Port,
                              String ServiceBanner                  = DefaultServiceBanner,
                              IEnumerable <String> Splitter         = null,
                              String ReceiverThreadName             = "UDP receiver thread",
                              ThreadPriority ReceiverThreadPriority = ThreadPriority.AboveNormal,
                              Boolean ReceiverThreadIsBackground    = true,
                              Func <UDPPacket <IEnumerable <String> >, String> PacketThreadsNameCreator = null,
                              ThreadPriority PacketThreadsPriority = ThreadPriority.AboveNormal,
                              Boolean PacketThreadsAreBackground   = true,
                              Boolean Autostart = false)

            : this(IPv4Address.Any,
                   Port,
                   ServiceBanner,
                   Splitter,
                   ReceiverThreadName,
                   ReceiverThreadPriority,
                   ReceiverThreadIsBackground,
                   PacketThreadsNameCreator,
                   PacketThreadsPriority,
                   PacketThreadsAreBackground,
                   Autostart)

        {
        }
Example #4
0
        public RoamingNetworkInfo(Tracker_Id TrackerId,
                                  String IncomingURI,
                                  DateTime ExpiredAfter,

                                  RoamingNetwork RoamingNetwork,
                                  Byte priority,
                                  Byte weight,
                                  String hostname,
                                  IPPort port,
                                  TransportTypes transport,
                                  String uriPrefix,
                                  HTTPContentType contentType,
                                  ProtocolTypes protocolType,
                                  IEnumerable <String> PublicKeys)

            : this(TrackerId,
                   IncomingURI,
                   ExpiredAfter,

                   RoamingNetwork.Id,
                   priority,
                   weight,
                   hostname,
                   port,
                   transport,
                   uriPrefix,
                   contentType,
                   protocolType,
                   PublicKeys)

        {
            this.RoamingNetwork = RoamingNetwork;
        }
Example #5
0
        /// <summary>
        /// Load all defined VPNs.
        /// </summary>
        /// <param name="path">rasphone.pbk file path</param>
        public void Open(string path)
        {
            List <Rasphone> lt      = new List <Rasphone>();
            const string    pattern = @"\[(.*?)\]";

            //var matches = Regex.Matches(System.IO.File.ReadAllText(path), pattern);//only name

            using (StreamReader sr = File.OpenText(path))
            {
                string tmp_name = null, tmp_ip = null;
                string s = String.Empty;
                while ((s = sr.ReadLine()) != null)
                {
                    if (Regex.IsMatch(s, pattern))
                    {
                        tmp_name = s.Replace("[", "").Replace("]", "");
                    }
                    if (s.IndexOf("PhoneNumber=") == 0)
                    {
                        tmp_ip = s.Remove(0, 12);//s.IndexOf('=') + 1
                    }
                    if (!string.IsNullOrEmpty(tmp_name) && !string.IsNullOrEmpty(tmp_ip))
                    {
                        lt.Add(new Rasphone(tmp_name, IPPort.Parse(tmp_ip)));
                        tmp_name = tmp_ip = null;
                    }
                }
            }
            Entries = lt.ToArray();
        }
Example #6
0
 public SyncWorker(string username, IPPort ipport, string videoMd5, bool ishost = false)
 {
     this.username = username;
     this.ishost   = ishost;
     this.ipport   = ipport;
     this.videoMd5 = videoMd5;
 }
Example #7
0
        public static RoamingNetworkInfo Create(this RoamingNetwork RoamingNetwork,
                                                Tracker_Id TrackerId,
                                                DateTime ExpiredAfter,

                                                Byte priority,
                                                Byte weight,
                                                String hostname,
                                                IPPort port,
                                                TransportTypes transport,
                                                String uriPrefix,
                                                HTTPContentType contentType,
                                                ProtocolTypes protocolType,
                                                IEnumerable <String> PublicKeys)
        {
            return(new RoamingNetworkInfo(TrackerId,
                                          "",
                                          ExpiredAfter,
                                          RoamingNetwork.Id,
                                          priority,
                                          weight,
                                          hostname,
                                          port,
                                          transport,
                                          uriPrefix,
                                          contentType,
                                          protocolType,
                                          PublicKeys));
        }
Example #8
0
        /// <summary>
        /// Create an instance of the OCPI HTTP API for Charge Point Operators
        /// using a newly created HTTP server.
        /// </summary>
        public CPOAPI(RoamingNetwork RoamingNetwork,
                      String HTTPServerName = DefaultHTTPServerName,
                      IPPort HTTPServerPort = null,
                      String URIPrefix      = "",

                      String ServiceName                = DefaultHTTPServerName,
                      EMailAddress APIEMailAddress      = null,
                      PgpSecretKeyRing APISecretKeyRing = null,
                      String APIPassphrase              = null,
                      EMailAddressList APIAdminEMail    = null,
                      SMTPClient APISMTPClient          = null,

                      DNSClient DNSClient = null,
                      String LogfileName  = DefaultLogfileName)

            : base(RoamingNetwork,
                   HTTPServerName,
                   HTTPServerPort != null ? HTTPServerPort : DefaultHTTPServerPort,
                   URIPrefix,
                   ResourceName => typeof(CPOAPI).Assembly.GetManifestResourceStream("org.GraphDefined.WWCP.OCPIv2_1.HTTPAPI.CPOAPI.HTTPRoot." + ResourceName),

                   ServiceName,
                   APIEMailAddress,
                   null,//OpenPGP.ReadPublicKeyRing(typeof(CPOAPI).Assembly.GetManifestResourceStream("org.GraphDefined.WWCP.OCPIv2_1.HTTPAPI.GenericAPI.HTTPRoot.robot@offenes-jena_pubring.gpg")),
                   APISecretKeyRing,
                   APIPassphrase,
                   APIAdminEMail,
                   APISMTPClient,

                   DNSClient,
                   LogfileName)

        {
            RegisterCPOURITemplates();
        }
Example #9
0
        /// <summary>
        /// Load list of buttons.
        /// </summary>
        private void Load()
        {
            if (File.Exists("rdp_buttons.xml"))
            {
                XElement rdp = XElement.Load("rdp_buttons.xml");

                foreach (var item in rdp.Elements())//<Button>
                {
                    Buttons.Add(new RDPbutton()
                    {
                        group      = item.Element("group").Value,
                        caption    = item.Element("caption").Value,
                        hint       = item.Element("hint").Value,
                        ipport     = IPPort.Parse(item.Element("ipport").Value),
                        parameters = item.Element("parameters").Value,
                        rdplogin   = new LoginRDP(item.Element("rdplogin").Element("user").Value,
                                                  Base64.DecodeBase64(item.Element("rdplogin").Element("pass").Value)),
                        vpnlogin = new LoginVPN(item.Element("vpnlogin").Element("name").Value,
                                                item.Element("vpnlogin").Element("user").Value,
                                                Base64.DecodeBase64(item.Element("vpnlogin").Element("pass").Value))
                    });
                }
            }
            else
            {
                Debug.WriteLine("Not found file 'rdp_buttons.xml'");
            }
        }
        public WWCP_Net_JSON_IO_Tests()
        {

            HTTPAPI = new HTTPServer<RoamingNetworks, RoamingNetwork>(
                          TCPPort:            IPPort.Parse(8000),
                          DefaultServerName: "GraphDefined WWCP Unit Tests",
                          DNSClient:          new DNSClient(SearchForIPv6DNSServers: false)
                      );

            HTTPAPI.AttachTCPPort(IPPort.Parse(8001));

            //WWCPAPI = OpenChargingCloudAPI.AttachToHTTPAPI(HTTPAPI);

            HTTPAPI.Start();

            //var RN_1    = WWCPAPI.CreateNewRoamingNetwork(RoamingNetworkId:  RoamingNetwork_Id.Parse("TEST_RN1"),
            //                                              Description:       I18NString.Create(Languages.de,  "Test Roaming Netz 1").
            //                                                                               Add(Languages.en,  "Test roaming network 1"));

            //var RN_2    = WWCPAPI.CreateNewRoamingNetwork(Hostname:          HTTPHostname.Parse("virtualhost"),
            //                                              RoamingNetworkId:  RoamingNetwork_Id.Parse("TEST_RN2"),
            //                                              Description:       I18NString.Create(Languages.de,  "Test Roaming Netz 2").
            //                                                                               Add(Languages.en,  "Test roaming network 2"));

            //var CPO_1   = RN_1.CreateNewEVSEOperator(EVSEOperatorId:  EVSEOperator_Id.Parse("DE*GEF"),
            //                                         Name:            I18NString.Create(Languages.de, "GraphDefined"),
            //                                         Description:     I18NString.Create(Languages.de, "GraphDefined Test EVSE Operator"),
            //                                         Configurator:    evseoperator => {
            //                                                              evseoperator.DataLicense = DataLicenses.OpenDatabaseLicense;
            //                                                          });

            //var Pool_1  = CPO_1.CreateNewChargingPool(ChargingPoolId:  ChargingPool_Id.Parse(CPO_1.Id, "1111"),
            //                                          Configurator:    pool => {
            //                                                               pool.Address = new Address(Country.Germany,
            //                                                                                          "07749",
            //                                                                                          I18NString.Create(Languages.de, "Jena"),
            //                                                                                          "Biberweg", "18");
            //                                                           });

            //var Pool_2  = CPO_1.CreateNewChargingPool(ChargingPoolId:  ChargingPool_Id.Parse(CPO_1.Id, "2222"),
            //                                          Configurator:    pool => {
            //                                                               pool.Address = new Address(Country.Germany,
            //                                                                                          "07749",
            //                                                                                          I18NString.Create(Languages.de, "Jena"),
            //                                                                                          "Biberweg", "18");
            //                                                           });

            //var Pool_3  = CPO_1.CreateNewChargingPool(ChargingPoolId:  ChargingPool_Id.Parse(CPO_1.Id, "3333"),
            //                                          Configurator:    pool => {
            //                                                               pool.Address = new Address(Country.Germany,
            //                                                                                          "07749",
            //                                                                                          I18NString.Create(Languages.de, "Jena"),
            //                                                                                          "Biberweg", "18");
            //                                                           });

            //var Sta1_P1  = Pool_1.CreateNewStation(ChargingStationId:  ChargingStation_Id.Parse(CPO_1.Id, "11115678"),
            //                                       Configurator:       station => {
            //                                                           });

        }
Example #11
0
        /// <summary>
        /// 如果可用则会自动更改
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="tcpp"></param>
        /// <param name="udpp"></param>
        /// <returns></returns>
        public async Task <string> CheckServerAvailable(string ip, string tcpp, string udpp)
        {
            var info = new IPPort {
                IP = ip, TcpPort = tcpp, UdpPort = udpp
            };

            return(await Task.Run(async() => {
                try {
                    UdpClient_ udpClient_ = new UdpClient_();
                    var res = await httpClient.GetAsync($"{Domain( info )}/ping");
                    string tcpRe = res.ResponseString;
                    string udpRe = udpClient_.SendMessage("ping@", info);
                    if (tcpRe != "OK")
                    {
                        return "TCP端口不可用";
                    }
                    if (udpRe != "OK")
                    {
                        return "UDP端口不可用";
                    }
                    CurrentServer = info;
                    return "OK";
                } catch (Exception ex) {
                    return $"发生错误:{ex.Message}";
                }
            }));
        }
Example #12
0
        /// <summary> Generate string with contents describing this UDP packet.</summary>
        /// <param name="colored">whether or not the string should contain ansi
        /// color escape sequences.
        /// </param>
        public override System.String ToColoredString(bool colored)
        {
            System.Text.StringBuilder buffer = new System.Text.StringBuilder();
            buffer.Append('[');
            if (colored)
            {
                buffer.Append(Color);
            }
            buffer.Append("UDPPacket");
            if (colored)
            {
                buffer.Append(AnsiEscapeSequences_Fields.RESET);
            }
            buffer.Append(": ");
            buffer.Append(SourceAddress);
            buffer.Append('.');
            buffer.Append(IPPort.getName(SourcePort));
            buffer.Append(" -> ");
            buffer.Append(DestinationAddress);
            buffer.Append('.');
            buffer.Append(IPPort.getName(DestinationPort));
            buffer.Append(" l=" + UDPFields_Fields.UDP_HEADER_LEN + "," + (Length - UDPFields_Fields.UDP_HEADER_LEN));
            buffer.Append(']');

            return(buffer.ToString());
        }
Example #13
0
        /// <summary>
        /// Create an instance of the OCPI HTTP API for Charge Point Operators
        /// using a newly created HTTP server.
        /// </summary>
        public CPOAPI(RoamingNetwork    RoamingNetwork,
                      String            HTTPServerName    = DefaultHTTPServerName,
                      IPPort            HTTPServerPort    = null,
                      String            URIPrefix         = "",

                      String            ServiceName       = DefaultHTTPServerName,
                      EMailAddress      APIEMailAddress   = null,
                      PgpSecretKeyRing  APISecretKeyRing  = null,
                      String            APIPassphrase     = null,
                      EMailAddressList  APIAdminEMail     = null,
                      SMTPClient        APISMTPClient     = null,

                      DNSClient         DNSClient         = null,
                      String            LogfileName       = DefaultLogfileName)
            : base(RoamingNetwork,
                   HTTPServerName,
                   HTTPServerPort != null ? HTTPServerPort : DefaultHTTPServerPort,
                   URIPrefix,
                   ResourceName => typeof(CPOAPI).Assembly.GetManifestResourceStream("org.GraphDefined.WWCP.OCPIv2_1.HTTPAPI.CPOAPI.HTTPRoot." + ResourceName),

                   ServiceName,
                   APIEMailAddress,
                   null,//OpenPGP.ReadPublicKeyRing(typeof(CPOAPI).Assembly.GetManifestResourceStream("org.GraphDefined.WWCP.OCPIv2_1.HTTPAPI.GenericAPI.HTTPRoot.robot@offenes-jena_pubring.gpg")),
                   APISecretKeyRing,
                   APIPassphrase,
                   APIAdminEMail,
                   APISMTPClient,

                   DNSClient,
                   LogfileName)
        {
            RegisterCPOURITemplates();
        }
Example #14
0
        /// <summary>
        /// Create an abstract SOAP client.
        /// </summary>
        /// <param name="ClientId">A unqiue identification of this client.</param>
        /// <param name="Hostname">The hostname to connect to.</param>
        /// <param name="RemotePort">The remote TCP port to connect to.</param>
        /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
        /// <param name="ClientCert">The TLS client certificate to use.</param>
        /// <param name="HTTPVirtualHost">An optional HTTP virtual host name to use.</param>
        /// <param name="URIPrefix">An default URI prefix.</param>
        /// <param name="WSSLoginPassword">The WebService-Security username/password.</param>
        /// <param name="UserAgent">An optional HTTP user agent to use.</param>
        /// <param name="QueryTimeout">An optional timeout for upstream queries.</param>
        /// <param name="DNSClient">An optional DNS client.</param>
        public ASOAPClient(String ClientId,
                           String Hostname,
                           IPPort RemotePort,
                           RemoteCertificateValidationCallback RemoteCertificateValidator = null,
                           X509Certificate ClientCert = null,
                           String HTTPVirtualHost     = null,
                           String URIPrefix           = null,
                           Tuple <String, String> WSSLoginPassword = null,
                           String UserAgent      = DefaultHTTPUserAgent,
                           TimeSpan?QueryTimeout = null,
                           DNSClient DNSClient   = null)

            : base(ClientId,
                   Hostname,
                   RemotePort,
                   RemoteCertificateValidator,
                   ClientCert,
                   HTTPVirtualHost,
                   UserAgent,
                   QueryTimeout,
                   DNSClient)

        {
            this.URIPrefix        = URIPrefix.Trim();
            this.WSSLoginPassword = WSSLoginPassword;
        }
Example #15
0
        internal GenericAPI(RoamingNetwork RoamingNetwork,
                            String HTTPServerName = DefaultHTTPServerName,
                            IPPort HTTPServerPort = null,
                            String URIPrefix      = "",
                            Func <String, Stream> GetRessources = null,

                            String ServiceName                = DefaultHTTPServerName,
                            EMailAddress APIEMailAddress      = null,
                            PgpPublicKeyRing APIPublicKeyRing = null,
                            PgpSecretKeyRing APISecretKeyRing = null,
                            String APIPassphrase              = null,
                            EMailAddressList APIAdminEMail    = null,
                            SMTPClient APISMTPClient          = null,

                            DNSClient DNSClient = null,
                            String LogfileName  = DefaultLogfileName)

            : this(RoamingNetwork,
                   new HTTPServer(DefaultServerName : DefaultHTTPServerName).AttachTCPPorts(HTTPServerPort != null ? HTTPServerPort : DefaultHTTPServerPort),
                   URIPrefix,
                   GetRessources,

                   ServiceName,
                   APIEMailAddress,
                   APIPublicKeyRing,
                   APISecretKeyRing,
                   APIPassphrase,
                   APIAdminEMail,
                   APISMTPClient,

                   LogfileName)

        {
        }
Example #16
0
        /// <summary>
        /// Initialize a new HTTP server for the HTTP/SOAP/XML Server API using IPAddress.Any.
        /// </summary>
        /// <param name="HTTPServerName">An optional identification string for the HTTP server.</param>
        /// <param name="TCPPort">An optional TCP port for the HTTP server.</param>
        /// <param name="URIPrefix">An optional prefix for the HTTP URIs.</param>
        /// <param name="SOAPContentType">The HTTP content type for SOAP messages.</param>
        /// <param name="DNSClient">An optional DNS client to use.</param>
        /// <param name="RegisterHTTPRootService">Register HTTP root services for sending a notice to clients connecting via HTML or plain text.</param>
        /// <param name="AutoStart">Start the server immediately.</param>
        public ASOAPServer(String HTTPServerName           = DefaultHTTPServerName,
                           IPPort TCPPort                  = null,
                           String URIPrefix                = DefaultURIPrefix,
                           HTTPContentType SOAPContentType = null,
                           Boolean RegisterHTTPRootService = true,
                           DNSClient DNSClient             = null,
                           Boolean AutoStart               = false)

            : this(new SOAPServer(TCPPort ?? DefaultHTTPServerPort,
                                  HTTPServerName,
                                  SOAPContentType ?? DefaultContentType,
                                  DNSClient :  DNSClient,
                                  Autostart :  false),
                   URIPrefix)

        {
            if (RegisterHTTPRootService)
            {
                RegisterRootService();
            }

            if (AutoStart)
#pragma warning disable RECS0021
            {
                Start();
            }
#pragma warning restore RECS0021
        }
Example #17
0
        internal GenericAPI(RoamingNetwork        RoamingNetwork,
                            String                HTTPServerName          = DefaultHTTPServerName,
                            IPPort                HTTPServerPort          = null,
                            String                URIPrefix               = "",
                            Func<String, Stream>  GetRessources           = null,

                            String                ServiceName             = DefaultHTTPServerName,
                            EMailAddress          APIEMailAddress         = null,
                            PgpPublicKeyRing      APIPublicKeyRing        = null,
                            PgpSecretKeyRing      APISecretKeyRing        = null,
                            String                APIPassphrase           = null,
                            EMailAddressList      APIAdminEMail           = null,
                            SMTPClient            APISMTPClient           = null,

                            DNSClient             DNSClient               = null,
                            String                LogfileName             = DefaultLogfileName)
            : this(RoamingNetwork,
                   new HTTPServer(DefaultServerName: DefaultHTTPServerName).AttachTCPPorts(HTTPServerPort != null ? HTTPServerPort : DefaultHTTPServerPort),
                   URIPrefix,
                   GetRessources,

                   ServiceName,
                   APIEMailAddress,
                   APIPublicKeyRing,
                   APISecretKeyRing,
                   APIPassphrase,
                   APIAdminEMail,
                   APISMTPClient,

                   LogfileName)
        {
        }
Example #18
0
        /// <summary>
        /// Create a new UDP receiver using IPAddress.Any and the given parameters.
        /// </summary>
        /// <param name="Port">The port to listen.</param>
        /// <param name="ServiceBanner">Service banner.</param>
        /// <param name="Mapper">A delegate to transform the incoming UDP packets into custom data structures.</param>
        /// <param name="ReceiverThreadName">The optional name of the UDP receiver thread.</param>
        /// <param name="ReceiverThreadPriority">The optional priority of the UDP receiver thread.</param>
        /// <param name="ReceiverThreadIsBackground">Whether the UDP receiver thread is a background thread or not.</param>
        /// <param name="PacketThreadsNameCreator">An optional delegate to set the name of the UDP packet threads.</param>
        /// <param name="PacketThreadsPriority">The optional priority of the UDP packet threads.</param>
        /// <param name="PacketThreadsAreBackground">Whether the UDP packet threads are background threads or not.</param>
        /// <param name="Autostart">Start the UDP receiver thread immediately.</param>
        public UDPReceiver(IPPort Port,
                           String ServiceBanner                  = DefaultServiceBanner,
                           MapperDelegate Mapper                 = null,
                           String ReceiverThreadName             = "UDP receiver thread",
                           ThreadPriority ReceiverThreadPriority = ThreadPriority.AboveNormal,
                           Boolean ReceiverThreadIsBackground    = true,
                           Func <UDPPacket <TData>, String> PacketThreadsNameCreator = null,
                           ThreadPriority PacketThreadsPriority = ThreadPriority.AboveNormal,
                           Boolean PacketThreadsAreBackground   = true,
                           Boolean Autostart = false)


            : this(IPv4Address.Any,
                   Port,
                   ServiceBanner,
                   Mapper,
                   null,
                   ReceiverThreadName,
                   ReceiverThreadPriority,
                   ReceiverThreadIsBackground,
                   PacketThreadsNameCreator,
                   PacketThreadsPriority,
                   PacketThreadsAreBackground,
                   Autostart)

        {
        }
Example #19
0
        /// <summary>
        /// Create a new SMTP client for sending e-mails.
        /// </summary>
        /// <param name="RemoteHost"></param>
        /// <param name="RemotePort"></param>
        /// <param name="Login"></param>
        /// <param name="Password"></param>
        /// <param name="LocalDomain"></param>
        /// <param name="UseIPv4">Whether to use IPv4 as networking protocol.</param>
        /// <param name="UseIPv6">Whether to use IPv6 as networking protocol.</param>
        /// <param name="PreferIPv6">Prefer IPv6 (instead of IPv4) as networking protocol.</param>
        /// <param name="UseTLS">Whether Transport Layer Security should be used or not.</param>
        /// <param name="ValidateServerCertificate">A callback for validating the remote server certificate.</param>
        /// <param name="ConnectionTimeout">The timeout connecting to the remote service.</param>
        /// <param name="DNSClient">An optional DNS client used to resolve DNS names.</param>
        /// <param name="AutoConnect">Connect to the TCP service automatically on startup. Default is false.</param>
        /// <param name="CancellationToken"></param>
        public SMTPClient(String RemoteHost,
                          IPPort RemotePort,
                          String Login       = null,
                          String Password    = null,
                          String LocalDomain = null,
                          Boolean UseIPv4    = true,
                          Boolean UseIPv6    = false,
                          Boolean PreferIPv6 = false,
                          TLSUsage UseTLS    = TLSUsage.STARTTLS,
                          ValidateRemoteCertificateDelegate ValidateServerCertificate = null,
                          TimeSpan?ConnectionTimeout          = null,
                          DNSClient DNSClient                 = null,
                          Boolean AutoConnect                 = false,
                          CancellationToken?CancellationToken = null)

            : base(RemoteHost,
                   RemotePort,
                   UseIPv4,
                   UseIPv6,
                   PreferIPv6,
                   UseTLS,
                   ValidateServerCertificate,
                   ConnectionTimeout,
                   DNSClient,
                   AutoConnect,
                   CancellationToken)

        {
            this._Login              = Login;
            this._Password           = Password;
            this._LocalDomain        = (LocalDomain != null) ? LocalDomain : System.Net.Dns.GetHostName();
            this._UnknownAuthMethods = new List <String>();
        }
Example #20
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="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(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)

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

        {
        }
        public void ShowChatWindow(IPPort iPPort, String message = null)
        {
            ChatWindow chatWindow = listChatWindow.Where((chatwin) => { return(chatwin.UserID == iPPort.UserId); }).FirstOrDefault();

            if (chatWindow == null)
            {
                chatWindow = new ChatWindow(mess =>
                {
                    SendChatMess(mess, iPPort);
                },
                                            iPPort.UserId);

                chatWindow.SetCloseAction(() =>
                {
                    listChatWindow.Remove(chatWindow);
                });

                listChatWindow.Add(chatWindow);
            }

            chatWindow.Dispatcher.Invoke(() =>
            {
                chatWindow.Show();
            });

            if (message != null)
            {
                chatWindow.Dispatcher.Invoke(() =>
                {
                    chatWindow.PushMessage(message, false);
                });
            }
        }
Example #22
0
        /// <summary>
        /// Create a new UDP receiver listening on the given IP address and port.
        /// </summary>
        /// <param name="IPAddress">The IP address to listen.</param>
        /// <param name="Port">The port to listen.</param>
        /// <param name="ServiceBanner">Service banner.</param>
        /// <param name="Mapper">A delegate to transform the incoming UDP packets into custom data structures.</param>
        /// <param name="ReceiverThreadName">The optional name of the UDP receiver thread.</param>
        /// <param name="ReceiverThreadPriority">The optional priority of the UDP receiver thread.</param>
        /// <param name="ReceiverThreadIsBackground">Whether the UDP receiver thread is a background thread or not.</param>
        /// <param name="PacketThreadsNameCreator">An optional delegate to set the name of the UDP packet threads.</param>
        /// <param name="PacketThreadsPriority">The optional priority of the UDP packet threads.</param>
        /// <param name="PacketThreadsAreBackground">Whether the UDP packet threads are background threads or not.</param>
        /// <param name="Autostart">Start the UDP receiver thread immediately.</param>
        public UDPReceiver(IIPAddress IPAddress,
                           IPPort Port,
                           String ServiceBanner                  = DefaultServiceBanner,
                           MapperDelegate Mapper                 = null,
                           MapReduceDelegate MapReduce           = null,
                           String ReceiverThreadName             = "UDP receiver thread",
                           ThreadPriority ReceiverThreadPriority = ThreadPriority.AboveNormal,
                           Boolean ReceiverThreadIsBackground    = true,
                           Func <UDPPacket <TData>, String> PacketThreadsNameCreator = null,
                           ThreadPriority PacketThreadsPriority = ThreadPriority.AboveNormal,
                           Boolean PacketThreadsAreBackground   = true,
                           Boolean Autostart = false)

        {
            if (Mapper == null && MapReduce == null)
            {
                throw new ArgumentNullException("The mapper and mapreduce delegate can not be both null!");
            }

            this._IPAddress               = IPAddress;
            this._IsMulticast             = IPAddress.IsMulticast;
            this._Port                    = Port;
            this._IPSocket                = new IPSocket(_IPAddress, _Port);
            this.ServiceBanner            = ServiceBanner;
            this.Mapper                   = Mapper;
            this.MapReduce                = MapReduce;
            this._ReceiverThreadName      = ReceiverThreadName;
            this._ReceiverThreadPriority  = ReceiverThreadPriority;
            this.PacketThreadsNameCreator = (PacketThreadsNameCreator == null)
                                                  ? UDPpacket => "UDP packet from " + UDPpacket.RemoteSocket.IPAddress + ":" + UDPpacket.RemoteSocket.Port
                                                  : PacketThreadsNameCreator;
            this._PacketThreadsPriority      = PacketThreadsPriority;
            this._PacketThreadsAreBackground = PacketThreadsAreBackground;

            var LocalIPEndPoint = new IPEndPoint(new System.Net.IPAddress(_IPAddress.GetBytes()), _Port.ToInt32());

            this.LocalSocket       = new IPSocket(LocalIPEndPoint);
            this.LocalDotNetSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            this.LocalDotNetSocket.Bind(LocalIPEndPoint);

            this.BufferSize     = 65536;
            this.ReceiveTimeout = 5000;

            if (IsMulticast)
            {
                LocalDotNetSocket.SetSocketOption(SocketOptionLevel.IP,
                                                  SocketOptionName.AddMembership,
                                                  new MulticastOption(System.Net.IPAddress.Parse(_IPAddress.ToString()),
                                                                      System.Net.IPAddress.Any));
            }

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

            if (Autostart)
            {
                Start();
            }
        }
Example #23
0
        public void ChangeServer(string ipOrDomain, string tcp, string udp)
        {
            string ip = Regex.Match(ipOrDomain, @"^[a-zA-Z0-9]+([a-zA-Z0-9\-\.]+)?\.$").Success ? DNSHelper.ParseIPFromDomain(ipOrDomain) : ipOrDomain;

            CurrentServer = new IPPort {
                IP = ip, TcpPort = tcp, UdpPort = udp
            };
        }
Example #24
0
        /// <summary>
        /// Create a new DNS resolver client.
        /// </summary>
        /// <param name="DNSServer">The DNS server to query.</param>
        /// <param name="Port">The IP port of the DNS server to query.</param>
        public DNSClient(IIPAddress DNSServer, IPPort Port)

            : this(new IPSocket[1] {
            new IPSocket(DNSServer, Port)
        })

        {
        }
Example #25
0
        public void ShowFileExplorerWindow(IPPort ipport)
        {
            FileExplorerWindow fileExplorerWindow = listFileExplorerWindow.Where(win => { return(win.UserID == ipport.UserId); }).FirstOrDefault();

            if (fileExplorerWindow == null)
            {
            }
        }
        private void CkbOverServer_Unchecked(object sender, RoutedEventArgs e)
        {
            udpProtocol.isServerOver = false;
            User   user   = listViewUsers.SelectedItem as User;
            IPPort ipport = listIPPort.Where(ipp => { return(ipp.UserId == user.ID); }).FirstOrDefault();

            udpProtocol.UdpSocketSend(udpProtocol.serverIP, udpProtocol.serverPort, new byte[] { 12, 1, (byte)user.ID, 0 });
        }
Example #27
0
 public LobbyBorrower(IPPort ipport, string lobbyName, string lobbyPassword)
 {
     this.ipport   = ipport;
     LobbyName     = lobbyName;
     LobbyPassword = lobbyPassword;
     LobbyName     = lobbyName;
     udpClient     = new UdpClient_();
 }
Example #28
0
File: SCTP.cs Project: sgf/SCTP
 /// <summary>
 /// 连接到远程服务器
 /// </summary>
 /// <param name="ipport">Remote EndPoint</param>
 /// <param name="TimeOut"> timeout time(Second)</param>
 /// <returns></returns>
 public ValueTask<(bool ok, string msg)> ConnectAsync(string ipport, ushort timeout = 2)
 {
     var (ok, ipp) = IPPort.Prase(ipport);
     if (!ok) return new ValueTask<(bool ok, string msg)>((false, "ipport 格式不正确"));
     var (okBind, msgBind) = Bind(ipp);
     if (!okBind) return new ValueTask<(bool ok, string msg)>((false, msgBind));
     RemoteEnd = ipp;
     //SCTP 发包收包
 }
Example #29
0
File: SCTP.cs Project: sgf/SCTP
        /// <summary>
        /// 绑定端口
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        private static (bool ok, string msg) Bind(IPPort end)
        {

            //获取进程ID int pid = Process.GetCurrentProcess().Id;
            var key = $"SCTP{end}"; //SCTP+IP[固定长度]+端口  //+进程ID 先排除
            using var mx = new Mutex(true, key);
            if (!mx.WaitOne(100, true)) return (false, "端口已被占用");
            return (true, "");
        }
Example #30
0
 public VtClientCore()
 {
     ReserveName   = Environment.MachineName;
     CurrentServer = new IPPort {
         IP      = "127.0.0.1",
         TcpPort = "2334",
         UdpPort = "2333"
     };
 }
Example #31
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 #32
0
 public RDPbutton(string group, string caption, string hint, IPPort ipport, string parameters, LoginRDP rdplogin, LoginVPN vpnlogin)
 {
     this.group      = group;
     this.caption    = caption;
     this.hint       = hint;
     this.ipport     = ipport;
     this.parameters = parameters;
     this.rdplogin   = rdplogin;
     this.vpnlogin   = vpnlogin;
 }
Example #33
0
        public static void SendTo(this UDPClient UDPClient, String UDPPacketString, IIPAddress RemoteIPAddress, IPPort IPPort, Encoding Encoding = null, SocketFlags SocketFlags = SocketFlags.None)
        {
            if (Encoding == null)
                Encoding = Encoding.UTF8;

            var UDPPacketData = Encoding.GetBytes(UDPPacketString);
            var RemoteIPEndPoint = new IPEndPoint(new IPAddress(RemoteIPAddress.GetBytes()), IPPort.ToInt32());

            UDPClient.SendTo(UDPPacketData, RemoteIPEndPoint, SocketFlags);
        }
Example #34
0
 /// <summary>
 /// Start a new TCP/HTTP/REST based graph server.
 /// </summary>
 /// <param name="Graph">A graph.</param>
 /// <param name="Port">The listening port.</param>
 /// <param name="Autostart">Autostart the server.</param>
 public static IBifrostHTTPServer StartHTTPServer(this IGenericPropertyGraph<String, Int64, String, String, Object,
                                                                       String, Int64, String, String, Object,
                                                                       String, Int64, String, String, Object,
                                                                       String, Int64, String, String, Object> Graph,
                                            IPPort Port,
                                            Boolean Autostart = false)
 {
     var Server = new BifrostHTTPServer(Port, Autostart);
     Server.AddGraph(Graph);
     return Server;
 }
Example #35
0
 /// <summary>
 /// Create a new HTTPClient using the given optional parameters.
 /// </summary>
 /// <param name="RemoteIPAddress">The remote IP address to connect to.</param>
 /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
 /// <param name="ClientCert">The TLS client certificate to use.</param>
 /// <param name="RemotePort">An optional remote IP port to connect to [default: 443].</param>
 /// <param name="DNSClient">An optional DNS client.</param>
 public HTTPSClient(IIPAddress                           RemoteIPAddress,
                    RemoteCertificateValidationCallback  RemoteCertificateValidator,
                    X509Certificate                      ClientCert  = null,
                    IPPort                               RemotePort  = null,
                    DNSClient                            DNSClient   = null)
     : base(RemoteIPAddress,
            RemotePort != null ? RemotePort : IPPort.Parse(443),
            RemoteCertificateValidator,
            ClientCert,
            DNSClient)
 {
 }
Example #36
0
 /// <summary>
 /// Create an abstract HTTP/JSON client.
 /// </summary>
 /// <param name="ClientId">A unqiue identification of this client.</param>
 /// <param name="Hostname">The hostname to connect to.</param>
 /// <param name="RemotePort">The remote TCP port to connect to.</param>
 /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
 /// <param name="ClientCert">The TLS client certificate to use.</param>
 /// <param name="HTTPVirtualHost">An optional HTTP virtual host name to use.</param>
 /// <param name="UserAgent">An optional HTTP user agent to use.</param>
 /// <param name="QueryTimeout">An optional timeout for upstream queries.</param>
 /// <param name="DNSClient">An optional DNS client.</param>
 public AJSONClient(String                               ClientId,
                    String                               Hostname,
                    IPPort                               RemotePort,
                    RemoteCertificateValidationCallback  RemoteCertificateValidator  = null,
                    X509Certificate                      ClientCert                  = null,
                    String                               HTTPVirtualHost             = null,
                    String                               UserAgent                   = DefaultHTTPUserAgent,
                    TimeSpan?                            QueryTimeout                = null,
                    DNSClient                            DNSClient                   = null)
     : base(ClientId,
            Hostname,
            RemotePort,
            RemoteCertificateValidator,
            ClientCert,
            HTTPVirtualHost,
            UserAgent,
            QueryTimeout,
            DNSClient)
 {
 }
Example #37
0
        /// <summary>
        /// Initialize a new HTTP server for the HTTP/SOAP/XML Server API using IPAddress.Any.
        /// </summary>
        /// <param name="HTTPServerName">An optional identification string for the HTTP server.</param>
        /// <param name="TCPPort">An optional TCP port for the HTTP server.</param>
        /// <param name="URIPrefix">An optional prefix for the HTTP URIs.</param>
        /// <param name="SOAPContentType">The HTTP content type for SOAP messages.</param>
        /// <param name="DNSClient">An optional DNS client to use.</param>
        /// <param name="RegisterHTTPRootService">Register HTTP root services for sending a notice to clients connecting via HTML or plain text.</param>
        /// <param name="AutoStart">Start the server immediately.</param>
        public ASOAPServer(String          HTTPServerName           = DefaultHTTPServerName,
                           IPPort          TCPPort                  = null,
                           String          URIPrefix                = DefaultURIPrefix,
                           HTTPContentType SOAPContentType          = null,
                           Boolean         RegisterHTTPRootService  = true,
                           DNSClient       DNSClient                = null,
                           Boolean         AutoStart                = false)
            : this(new SOAPServer(TCPPort ?? DefaultHTTPServerPort,
                                  HTTPServerName,
                                  SOAPContentType ?? DefaultContentType,
                                  DNSClient:  DNSClient,
                                  Autostart:  false),
                   URIPrefix)
        {
            if (RegisterHTTPRootService)
                RegisterRootService();

            if (AutoStart)
            #pragma warning disable RECS0021
                Start();
            #pragma warning restore RECS0021
        }
Example #38
0
        /// <summary>
        /// Create an abstract HTTP client.
        /// </summary>
        /// <param name="ClientId">A unqiue identification of this client.</param>
        /// <param name="Hostname">The hostname to connect to.</param>
        /// <param name="RemotePort">The remote TCP port to connect to.</param>
        /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
        /// <param name="ClientCert">The TLS client certificate to use.</param>
        /// <param name="HTTPVirtualHost">An optional HTTP virtual host name to use.</param>
        /// <param name="UserAgent">An optional HTTP user agent to use.</param>
        /// <param name="QueryTimeout">An optional timeout for upstream queries.</param>
        /// <param name="DNSClient">An optional DNS client.</param>
        public AHTTPClient(String                               ClientId,
                           String                               Hostname,
                           IPPort                               RemotePort,
                           RemoteCertificateValidationCallback  RemoteCertificateValidator  = null,
                           X509Certificate                      ClientCert                  = null,
                           String                               HTTPVirtualHost             = null,
                           String                               UserAgent                   = DefaultHTTPUserAgent,
                           TimeSpan?                            QueryTimeout                = null,
                           DNSClient                            DNSClient                   = null)
        {
            #region Initial checks

            if (Hostname.IsNullOrEmpty())
                throw new ArgumentNullException(nameof(Hostname), "The given parameter must not be null or empty!");

            #endregion

            this.ClientId                    = ClientId;
            this.Hostname                    = Hostname;
            this.RemotePort                  = RemotePort ?? DefaultRemotePort;

            this.RemoteCertificateValidator  = RemoteCertificateValidator;
            this.ClientCert                  = ClientCert;

            this.HTTPVirtualHost             = HTTPVirtualHost.IsNotNullOrEmpty()
                                                    ? HTTPVirtualHost
                                                    : Hostname;

            this.UserAgent                   = UserAgent ?? DefaultHTTPUserAgent;

            this.RequestTimeout              = QueryTimeout != null
                                                  ? QueryTimeout.Value
                                                  : DefaultQueryTimeout;

            this.DNSClient                   = DNSClient == null
                                                  ? new DNSClient()
                                                  : DNSClient;
        }
Example #39
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 #40
0
 /// <summary>
 /// Create a new HTTPClient using the given optional parameters.
 /// </summary>
 /// <param name="RemoteIPAddress">The IP address to connect to.</param>
 /// <param name="RemotePort">The IP port to connect to.</param>
 public HTTPClient(IIPAddress RemoteIPAddress = null, IPPort RemotePort = null)
 {
     this.RemoteIPAddress = RemoteIPAddress;
     this.RemotePort      = RemotePort;
 }
        /// <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 #42
0
 public ArrowIPSource(String _IPAddress, IPPort _Port)
 {
     Address = _IPAddress;
     Port    = _Port;
 }
Example #43
0
 public static void SendTo(this UDPClient UDPClient, Byte[] UDPPacketData, IIPAddress RemoteIPAddress, IPPort IPPort, SocketFlags SocketFlags = SocketFlags.None)
 {
     var RemoteIPEndPoint = new IPEndPoint(new IPAddress(RemoteIPAddress.GetBytes()), IPPort.ToInt32());
     UDPClient.SendTo(UDPPacketData, RemoteIPEndPoint, SocketFlags);
 }
Example #44
0
        /// <summary>
        /// Create a new HTTPClient using the given optional parameters.
        /// </summary>
        /// <param name="RemoteHost">The remote hostname to connect to.</param>
        /// <param name="RemotePort">The remote IP port to connect to.</param>
        /// <param name="ClientCert">The TLS client certificate to use.</param>
        /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
        /// <param name="DNSClient">An optional DNS client.</param>
        public HTTPClient(String                               RemoteHost,
                          IPPort                               RemotePort                  = null,
                          RemoteCertificateValidationCallback  RemoteCertificateValidator  = null,
                          X509Certificate                      ClientCert                  = null,
                          DNSClient                            DNSClient                   = null)
        {

            this.Hostname                    = RemoteHost;
            this.RemotePort                  = RemotePort != null
                                                   ? RemotePort
                                                   : IPPort.Parse(80);

            this.RemoteCertificateValidator  = RemoteCertificateValidator;

            this.ClientCert                  = ClientCert;

            this.DNSClient                   = DNSClient != null
                                                   ? DNSClient
                                                   : new DNSClient();

        }
Example #45
0
        //    public LocalCertificateSelectionCallback ClientCertificateSelector { get; set; }

        #endregion

        #region Events


        #endregion

        #region Constructor(s)

        #region HTTPClient(RemoteIPAddress, RemotePort, RemoteCertificateValidator = null, ClientCert = null, DNSClient = null)

        /// <summary>
        /// Create a new HTTPClient using the given optional parameters.
        /// </summary>
        /// <param name="RemoteIPAddress">The remote IP address to connect to.</param>
        /// <param name="RemotePort">The remote IP port to connect to.</param>
        /// <param name="RemoteCertificateValidator">A delegate to verify the remote TLS certificate.</param>
        /// <param name="ClientCert">The TLS client certificate to use.</param>
        /// <param name="DNSClient">An optional DNS client.</param>
        public HTTPClient(IIPAddress                           RemoteIPAddress,
                          IPPort                               RemotePort,
                          RemoteCertificateValidationCallback  RemoteCertificateValidator  = null,
                          X509Certificate                      ClientCert                  = null,
                          DNSClient                            DNSClient                   = null)
        {

            this.RemoteIPAddress             = RemoteIPAddress;
            this.Hostname                    = RemoteIPAddress.ToString();
            this.RemotePort                  = RemotePort;
            this.RemoteCertificateValidator  = RemoteCertificateValidator;
            this.ClientCert                  = ClientCert;
            this.DNSClient                   = DNSClient == null
                                                   ? new DNSClient()
                                                   : DNSClient;

        }
Example #46
0
        private Socket CreateAndConnectTCPSocket(IIPAddress _IPAddress, IPPort Port)
        {
            Socket _TCPSocket = null;

            if (_IPAddress is IPv4Address)
                _TCPSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            else if (_IPAddress is IPv6Address)
                _TCPSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);

            _TCPSocket.Connect(IPAddress.Parse(_IPAddress.ToString()), Port.ToUInt16());

            return _TCPSocket;
        }
Example #47
0
        /// <summary>
        /// Create a new http request header based on the given string representation.
        /// </summary>
        /// <param name="HTTPHeader">A valid string representation of a http request header.</param>
        public HTTPRequest(IIPAddress RemoteHost, IPPort RemotePort, String HTTPHeader)
        {
            this.RemoteHost = RemoteHost;
            this.RemotePort = RemotePort;

            if (!ParseHeader(HTTPHeader))
                return;

            #region Parse HTTPMethod (first line of the http request)

            var _HTTPMethodHeader = FirstPDULine.Split(_SpaceSeperator, StringSplitOptions.RemoveEmptyEntries);

            // e.g: PROPFIND /file/file Name HTTP/1.1
            if (_HTTPMethodHeader.Length != 3)
            {
                this.HTTPStatusCode = HTTPStatusCode.BadRequest;
                return;
            }

            // Parse HTTP method
            // Propably not usefull to define here, as we can not send a response having an "Allow-header" here!
            HTTPMethod _HTTPMethod = null;
            if (!HTTPMethod.TryParseString(_HTTPMethodHeader[0], out _HTTPMethod))
            {
                this.HTTPStatusCode = HTTPStatusCode.MethodNotAllowed;
                return;
            }

            this.HTTPMethod = _HTTPMethod;

            #endregion

            #region Parse URL and QueryString (first line of the http request)

            var RawUrl     = _HTTPMethodHeader[1];
            var _ParsedURL = RawUrl.Split(_URLSeperator, 2, StringSplitOptions.RemoveEmptyEntries);
            UrlPath        = _ParsedURL[0];

            if (UrlPath == "" || UrlPath == null)
                UrlPath = "/";

            // Parse QueryString after '?'
            if (RawUrl.IndexOf('?') > -1)
            {
                //var a = HttpUtility.ParseQueryString(_ParsedURL[1]);
                //foreach (var b in a.AllKeys)
                //    QueryString.Add(b, a[b]);
                this.QueryString = new QueryString(_ParsedURL[1]);
            }

            #endregion

            #region Parse protocol name and -version (first line of the http request)

            var _ProtocolArray  = _HTTPMethodHeader[2].Split(_SlashSeperator, 2, StringSplitOptions.RemoveEmptyEntries);
            ProtocolName        = _ProtocolArray[0].ToUpper();

            if (ProtocolName.ToUpper() != "HTTP")
            {
                this.HTTPStatusCode = HTTPStatusCode.InternalServerError;
                return;
            }

            HTTPVersion _HTTPVersion = null;
            if (HTTPVersion.TryParseVersionString(_ProtocolArray[1], out _HTTPVersion))
                ProtocolVersion = _HTTPVersion;
            if (ProtocolVersion != HTTPVersion.HTTP_1_1)
            {
                this.HTTPStatusCode = HTTPStatusCode.HTTPVersionNotSupported;
                return;
            }

            #endregion

            if (!HeaderFields.ContainsKey("Host"))
                HeaderFields.Add("Host", "*");

            this.HTTPStatusCode = HTTPStatusCode.OK;
        }
Example #48
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="RemoteHost"></param>
        /// <param name="RemotePort"></param>
        /// <param name="UseIPv4">Whether to use IPv4 as networking protocol.</param>
        /// <param name="UseIPv6">Whether to use IPv6 as networking protocol.</param>
        /// <param name="PreferIPv6">Prefer IPv6 (instead of IPv4) as networking protocol.</param>
        /// <param name="UseTLS">Whether Transport Layer Security should be used or not.</param>
        /// <param name="ValidateServerCertificate">A callback for validating the remote server certificate.</param>
        /// <param name="ConnectionTimeout">The timeout connecting to the remote service.</param>
        /// <param name="DNSClient">An optional DNS client used to resolve DNS names.</param>
        /// <param name="AutoConnect">Connect to the TCP service automatically on startup. Default is false.</param>
        /// <param name="CancellationToken"></param>
        public TCPClient(String                             RemoteHost,
                         IPPort                             RemotePort,
                         Boolean                            UseIPv4                     = true,
                         Boolean                            UseIPv6                     = false,
                         Boolean                            PreferIPv6                  = false,
                         TLSUsage                           UseTLS                      = TLSUsage.STARTTLS,
                         ValidateRemoteCertificateDelegate  ValidateServerCertificate   = null,
                         TimeSpan?                          ConnectionTimeout           = null,
                         DNSClient                          DNSClient                   = null,
                         Boolean                            AutoConnect                 = false,
                         CancellationToken?                 CancellationToken           = null)
        {
            this._RemoteHost                = RemoteHost;
            this._RemotePort                = RemotePort;
            this.CancellationToken          = CancellationToken != null ? CancellationToken : new CancellationToken();
            this._UseIPv4                   = UseIPv4;
            this._UseIPv6                   = UseIPv6;
            this._PreferIPv6                = PreferIPv6;
            this._UseTLS                    = UseTLS;
            this.ValidateServerCertificate  = ValidateServerCertificate != null
                                                  ? ValidateServerCertificate
                                                  : (TCPClient, Certificate, CertificateChain, PolicyErrors) => false;

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

            this._DNSClient                 = (DNSClient == null)
                                                  ? new DNSClient(SearchForIPv6DNSServers: true)
                                                  : DNSClient;

            if (AutoConnect)
                Connect();
        }
Example #49
0
 /// <summary>
 /// Create a new SMTP client for sending e-mails.
 /// </summary>
 /// <param name="RemoteHost"></param>
 /// <param name="RemotePort"></param>
 /// <param name="Login"></param>
 /// <param name="Password"></param>
 /// <param name="LocalDomain"></param>
 /// <param name="UseIPv4">Whether to use IPv4 as networking protocol.</param>
 /// <param name="UseIPv6">Whether to use IPv6 as networking protocol.</param>
 /// <param name="PreferIPv6">Prefer IPv6 (instead of IPv4) as networking protocol.</param>
 /// <param name="UseTLS">Whether Transport Layer Security should be used or not.</param>
 /// <param name="ValidateServerCertificate">A callback for validating the remote server certificate.</param>
 /// <param name="ConnectionTimeout">The timeout connecting to the remote service.</param>
 /// <param name="DNSClient">An optional DNS client used to resolve DNS names.</param>
 /// <param name="AutoConnect">Connect to the TCP service automatically on startup. Default is false.</param>
 /// <param name="CancellationToken"></param>
 public SMTPClient(String                             RemoteHost,
                   IPPort                             RemotePort,
                   String                             Login                      = null,
                   String                             Password                   = null,
                   String                             LocalDomain                = null,
                   Boolean                            UseIPv4                    = true,
                   Boolean                            UseIPv6                    = false,
                   Boolean                            PreferIPv6                 = false,
                   TLSUsage                           UseTLS                     = TLSUsage.STARTTLS,
                   ValidateRemoteCertificateDelegate  ValidateServerCertificate  = null,
                   TimeSpan?                          ConnectionTimeout          = null,
                   DNSClient                          DNSClient                  = null,
                   Boolean                            AutoConnect                = false,
                   CancellationToken?                 CancellationToken          = null)
     : base(RemoteHost,
            RemotePort,
            UseIPv4,
            UseIPv6,
            PreferIPv6,
            UseTLS,
            ValidateServerCertificate,
            ConnectionTimeout,
            DNSClient,
            AutoConnect,
            CancellationToken)
 {
     this._Login               = Login;
     this._Password            = Password;
     this._LocalDomain         = (LocalDomain != null) ? LocalDomain : System.Net.Dns.GetHostName();
     this._UnknownAuthMethods  = new List<String>();
 }