Esempio n. 1
0
 /// <summary>
 /// Sets the default values.
 /// </summary>
 protected override void SetToDefault()
 {
     GeneralOptions  = new GeneralOptions();
     ListenerOptions = new ListenerOptions();
     ModuleCodes     = new List <string>();
     Archives        = new List <ArchiveConfig>();
 }
Esempio n. 2
0
        /// <summary>
        /// Saves the configuration to the specified writer.
        /// </summary>
        protected override void Save(TextWriter writer)
        {
            XmlDocument    xmlDoc  = new XmlDocument();
            XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

            xmlDoc.AppendChild(xmlDecl);

            XmlElement rootElem = xmlDoc.CreateElement("ScadaServerConfig");

            xmlDoc.AppendChild(rootElem);

            GeneralOptions.SaveToXml(rootElem.AppendElem("GeneralOptions"));
            ListenerOptions.SaveToXml(rootElem.AppendElem("ListenerOptions"));

            XmlElement modulesElem = rootElem.AppendElem("Modules");

            foreach (string moduleCode in ModuleCodes)
            {
                modulesElem.AppendElem("Module").SetAttribute("code", moduleCode);
            }

            XmlElement archivesElem = rootElem.AppendElem("Archives");

            foreach (ArchiveConfig archiveConfig in Archives)
            {
                archiveConfig.SaveToXml(archivesElem.AppendElem("Archive"));
            }

            xmlDoc.Save(writer);
        }
Esempio n. 3
0
    public KerberosExecutor(ITestOutputHelper testOutputHelper, string realm)
    {
        var krb5Config = Krb5Config.Default();

        krb5Config.KdcDefaults.RegisterDefaultPkInitPreAuthHandler = false;

        var logger = new KerberosDelegateLogger(
            (level, categoryName, eventId, scopeState, logState, exception, log) =>
            testOutputHelper.WriteLine($"[{level}] [{categoryName}] {log}")
            );

        _principalService = new FakePrincipalService(realm);

        byte[] krbtgtPassword = new byte[16];

        var krbtgt = new FakeKerberosPrincipal(PrincipalType.Service, "krbtgt", realm, krbtgtPassword);

        _principalService.Add("krbtgt", krbtgt);
        _principalService.Add($"krbtgt/{realm}", krbtgt);

        _options = new ListenerOptions
        {
            Configuration = krb5Config,
            DefaultRealm  = realm,
            RealmLocator  = realm => new FakeRealmService(realm, krb5Config, _principalService),
            Log           = logger,
            IsDebug       = true,
        };

        _kdcListener       = new FakeKdcServer(_options);
        _realm             = realm;
        _servicePrincipals = new List <FakeKerberosPrincipal>();
        _testOutputHelper  = testOutputHelper;
    }
        public async Task ReceiveTimeout()
        {
            var port = NextPort();
            var log  = new FakeExceptionLoggerFactory();

            var options = new ListenerOptions
            {
                ListeningOn    = new IPEndPoint(IPAddress.Loopback, port),
                DefaultRealm   = "corp2.identityintervention.com".ToUpper(),
                IsDebug        = true,
                RealmLocator   = realm => LocateRealm(realm, slow: true),
                ReceiveTimeout = TimeSpan.FromMilliseconds(1),
                Log            = log
            };

            KdcServiceListener listener = new KdcServiceListener(options);

            _ = listener.Start();

            try
            {
                await RequestAndValidateTickets(AdminAtCorpUserName, FakeAdminAtCorpPassword, $"127.0.0.1:{port}");
            }
            catch
            {
            }

            listener.Stop();

            var timeout = log.Exceptions.FirstOrDefault(e => e is TimeoutException);

            Assert.IsNotNull(timeout);

            throw timeout;
        }
Esempio n. 5
0
 public RabbitOptions()
 {
     Ssl      = new SslOptions();
     Cache    = new CacheOptions();
     Listener = new ListenerOptions();
     Template = new TemplateOptions();
 }
Esempio n. 6
0
 public DotNettyListenerAdapter(ListenerOptions options, IServiceProvider serviceProvider)
 {
     _options         = options;
     _serviceProvider = serviceProvider;
     InternalLoggerFactory.DefaultFactory = _serviceProvider.GetService <ILoggerFactory>();
     _packetCodec = _serviceProvider.GetRequiredService <IPacketCodec>();
 }
Esempio n. 7
0
        public Task Setup()
        {
            this.Port = new Random().Next(20000, 40000);

            var options = new ListenerOptions
            {
                DefaultRealm = "corp2.identityintervention.com".ToUpper(),
                RealmLocator = realm => LocateRealm(realm),
                Log          = Logger
            };

            options.Configuration.KdcDefaults.TcpListenBacklog = int.MaxValue;
            options.Configuration.KdcDefaults.ReceiveTimeout   = TimeSpan.FromSeconds(15);
            options.Configuration.KdcDefaults.KdcTcpListenEndpoints.Clear();
            options.Configuration.KdcDefaults.KdcTcpListenEndpoints.Add($"127.0.0.1:{this.Port}");

            this.listener = new KdcServiceListener(options);
            _             = this.listener.Start();

            this.credential = Creds.GetOrAdd(this.AlgorithmType, a => new KerberosPasswordCredential(a + this.user, this.password));

            this.asReq = new ReadOnlySequence <byte>(KrbAsReq.CreateAsReq(this.credential, DefaultAuthentication).EncodeApplication());

            return(Task.CompletedTask);
        }
Esempio n. 8
0
        public void Setup()
        {
            options = new ListenerOptions
            {
                DefaultRealm = Realm,
                RealmLocator = LocateRealm
            };

            credential = Creds.GetOrAdd(AlgorithmType, a => new KerberosPasswordCredential(a + user, password));

            asReq = KrbAsReq.CreateAsReq(credential, DefaultAuthentication).EncodeApplication();

            switch (AlgorithmType)
            {
            case "RC4":
                etype = EncryptionType.RC4_HMAC_NT;
                break;

            case "AES128":
                etype = EncryptionType.AES128_CTS_HMAC_SHA1_96;
                break;

            case "AES256":
                etype = EncryptionType.AES256_CTS_HMAC_SHA1_96;
                break;
            }
        }
Esempio n. 9
0
        static async Task Main()
        {
            var builder = new HostBuilder()
                          .ConfigureLogging((_, factory) =>
            {
                factory.AddConsole(opt => opt.IncludeScopes = true);
                factory.AddFilter <ConsoleLoggerProvider>(level => level >= LogLevel.Trace);
            });

            var host = builder.Build();

            var logger = (ILoggerFactory)host.Services.GetService(typeof(ILoggerFactory));

            var options = new ListenerOptions
            {
                Log          = logger,
                DefaultRealm = "corp2.identityintervention.com".ToUpper(),
                IsDebug      = true,
                RealmLocator = realm => new FakeRealmService(realm)
            };

            options.Configuration.KdcDefaults.KdcTcpListenEndpoints.Clear();
            options.Configuration.KdcDefaults.KdcTcpListenEndpoints.Add("127.0.0.1:8888");
            options.Configuration.KdcDefaults.ReceiveTimeout = TimeSpan.FromHours(1);

            var listener = new KdcServiceListener(options);

            await listener.Start();

            listener.Dispose();
        }
Esempio n. 10
0
 /// <summary>
 /// Sets the default values.
 /// </summary>
 private void SetToDefault()
 {
     GeneralOptions  = new GeneralOptions();
     ListenerOptions = new ListenerOptions();
     PathOptions     = new PathOptions();
     Archives        = new List <ArchiveConfig>();
     ModuleCodes     = new List <string>();
 }
Esempio n. 11
0
        public WebSocketServerHandler(IServiceProvider serviceProvider, ListenerOptions netListenerOptions)
        {
            this._appSessionContainer = serviceProvider.GetRequiredService <AppSessionContainer <AppSession> >();
            this._serviceProvider     = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
            this._netListenerOptions  = netListenerOptions ?? throw new ArgumentNullException(nameof(netListenerOptions));

            this._commandContainer = serviceProvider.GetRequiredService <ICommandDescriptorContainer>();
            this._commandActivator = serviceProvider.GetRequiredService <ICommandActivator>();
            this._packetCodec      = serviceProvider.GetRequiredService <IPacketCodec>();
            ILoggerFactory loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();

            _logger = loggerFactory.CreateLogger <WebSocketServerHandler>();
        }
Esempio n. 12
0
        /// <summary>
        /// Loads the configuration from the specified reader.
        /// </summary>
        protected override void Load(TextReader reader)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(reader);
            XmlElement rootElem = xmlDoc.DocumentElement;

            if (rootElem.SelectSingleNode("GeneralOptions") is XmlNode generalOptionsNode)
            {
                GeneralOptions.LoadFromXml(generalOptionsNode);
            }

            if (rootElem.SelectSingleNode("ListenerOptions") is XmlNode listenerOptionsNode)
            {
                ListenerOptions.LoadFromXml(listenerOptionsNode);
            }

            HashSet <string> moduleCodeSet = new HashSet <string>();

            void AddModuleCode(string moduleCode)
            {
                if (!string.IsNullOrEmpty(moduleCode) && moduleCodeSet.Add(moduleCode.ToLowerInvariant()))
                {
                    ModuleCodes.Add(moduleCode);
                }
            }

            if (rootElem.SelectSingleNode("Modules") is XmlNode modulesNode)
            {
                foreach (XmlElement moduleElem in modulesNode.SelectNodes("Module"))
                {
                    string moduleCode = ScadaUtils.RemoveFileNameSuffixes(moduleElem.GetAttribute("code"));
                    AddModuleCode(moduleCode);
                }
            }

            if (rootElem.SelectSingleNode("Archives") is XmlNode archivesNode)
            {
                foreach (XmlElement archiveElem in archivesNode.SelectNodes("Archive"))
                {
                    ArchiveConfig archiveConfig = new ArchiveConfig();
                    archiveConfig.LoadFromXml(archiveElem);
                    Archives.Add(archiveConfig);

                    if (archiveConfig.Active)
                    {
                        AddModuleCode(archiveConfig.Module);
                    }
                }
            }
        }
        public async Task U2U()
        {
            var port = new Random().Next(20000, 40000);

            var options = new ListenerOptions
            {
                ListeningOn    = new IPEndPoint(IPAddress.Loopback, port),
                DefaultRealm   = "corp2.identityintervention.com".ToUpper(),
                IsDebug        = true,
                RealmLocator   = realm => LocateRealm(realm),
                ReceiveTimeout = TimeSpan.FromHours(1)
            };

            KdcServiceListener listener = new KdcServiceListener(options);

            _ = listener.Start();

            var kerbClientCred = new KerberosPasswordCredential("*****@*****.**", "P@ssw0rd!");
            var client         = new KerberosClient($"127.0.0.1:{port}");

            await client.Authenticate(kerbClientCred);

            var kerbServerCred = new KerberosPasswordCredential("*****@*****.**", "P@ssw0rd!");
            var server         = new KerberosClient($"127.0.0.1:{port}");

            await server.Authenticate(kerbClientCred);

            var serverEntry = await server.Cache.Get <KerberosClientCacheEntry>($"krbtgt/{server.DefaultDomain}");

            var serverTgt = serverEntry.Ticket.Ticket;

            var apReq = await client.GetServiceTicket("host/u2u", ApOptions.MutualRequired | ApOptions.UseSessionKey, u2uServerTicket : serverTgt);

            Assert.IsNotNull(apReq);

            var decrypted = new DecryptedKrbApReq(apReq);

            Assert.IsNull(decrypted.Ticket);

            decrypted.Decrypt(serverEntry.SessionKey.AsKey());

            decrypted.Validate(ValidationActions.All);

            Assert.IsNotNull(decrypted.Ticket);

            Assert.AreEqual("host/u2u/CORP.IDENTITYINTERVENTION.COM", decrypted.SName.FullyQualifiedName);

            listener.Stop();
        }
Esempio n. 14
0
        public static TcpKdcListener StartTcpListener(int port, bool slow = false)
        {
            var options = new ListenerOptions
            {
                ListeningOn    = new IPEndPoint(IPAddress.Loopback, port),
                DefaultRealm   = "corp2.identityintervention.com".ToUpper(),
                IsDebug        = true,
                RealmLocator   = realm => LocateRealm(realm, slow),
                ReceiveTimeout = TimeSpan.FromHours(1)
            };

            KdcServiceListener server = new KdcServiceListener(options);

            return(new TcpKdcListener(server));
        }
Esempio n. 15
0
        public void Setup()
        {
            port = new Random().Next(20000, 40000);

            var options = new ListenerOptions
            {
                ListeningOn    = new IPEndPoint(IPAddress.Loopback, port),
                DefaultRealm   = "corp2.identityintervention.com".ToUpper(),
                IsDebug        = true,
                RealmLocator   = realm => LocateRealm(realm),
                ReceiveTimeout = TimeSpan.FromHours(1)
            };

            listener = new KdcServiceListener(options);
            _        = listener.Start();
        }
Esempio n. 16
0
        public void Setup()
        {
            Port = new Random().Next(20000, 40000);

            var options = new ListenerOptions
            {
                ListeningOn    = new IPEndPoint(IPAddress.Loopback, Port),
                DefaultRealm   = "corp2.identityintervention.com".ToUpper(),
                RealmLocator   = realm => LocateRealm(realm),
                QueueLength    = 10 * 1000,
                ReceiveTimeout = TimeSpan.FromMinutes(60),
                Log            = null
            };

            listener = new KdcServiceListener(options);
            _        = listener.Start();
        }
Esempio n. 17
0
        public void Setup()
        {
            this.port = new Random().Next(20000, 40000);

            var options = new ListenerOptions
            {
                DefaultRealm = "corp2.identityintervention.com".ToUpper(),
                IsDebug      = true,
                RealmLocator = realm => this.LocateRealm(realm)
            };

            options.Configuration.KdcDefaults.ReceiveTimeout = TimeSpan.FromHours(1);
            options.Configuration.KdcDefaults.KdcTcpListenEndpoints.Clear();
            options.Configuration.KdcDefaults.KdcTcpListenEndpoints.Add($"127.0.0.1:{this.port}");

            this.listener = new KdcServiceListener(options);
            _             = this.listener.Start();
        }
Esempio n. 18
0
        /// <summary>
        /// Sets the configuration according to the controls.
        /// </summary>
        private void ControlsToConfing()
        {
            // general options
            GeneralOptions generalOptions = serverConfig.GeneralOptions;

            generalOptions.UnrelIfInactive       = decimal.ToInt32(numUnrelIfInactive.Value);
            generalOptions.GenerateAckCmd        = chkGenerateAckCmd.Checked;
            generalOptions.MaxLogSize            = decimal.ToInt32(numMaxLogSize.Value);
            generalOptions.DisableFormulas       = chkDisableFormulas.Checked;
            generalOptions.EnableFormulasObjNums = ScadaUtils.ParseRange(txtEnableFormulasObjNums.Text, true, true);

            // listener options
            ListenerOptions listenerOptions = serverConfig.ListenerOptions;

            listenerOptions.Port      = decimal.ToInt32(numPort.Value);
            listenerOptions.Timeout   = decimal.ToInt32(numTimeout.Value);
            listenerOptions.SecretKey = ScadaUtils.HexToBytes(txtSecretKey.Text.Trim());
        }
Esempio n. 19
0
        public static Listener GetListener(ListenerOptions option)
        {
            Listener listener = null;

            switch (option)
            {
            case ListenerOptions.Save:
                listener = SaveListener.Instance;
                break;

            case ListenerOptions.Refresh:
                listener = RefreshListener.Instance;
                break;

            default:
                break;
            }
            return(listener);
        }
Esempio n. 20
0
        private DateTime heartbeatDT;                                       // the last time a heartbeat was sent to remote Agents


        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        public AgentListener(CoreLogic coreLogic, ListenerOptions listenerOptions,
                             ReverseConnectionOptions reverseConnectionOptions)
            : base(listenerOptions, coreLogic.Log)
        {
            this.coreLogic = coreLogic ?? throw new ArgumentNullException(nameof(coreLogic));
            this.reverseConnectionOptions = reverseConnectionOptions ??
                                            throw new ArgumentNullException(nameof(reverseConnectionOptions));
            clientBundles = new Dictionary <string, ClientBundle>();

            reverseClient           = null;
            reverseClientThread     = null;
            reverseClientTerminated = false;
            heartbeatDT             = DateTime.MinValue;

            CustomFunctions = new HashSet <int>
            {
                FunctionID.DownloadFile,
                FunctionID.UploadFile
            };
        }
Esempio n. 21
0
        /// <summary>
        /// Loads the configuration from the specified file.
        /// </summary>
        public bool Load(string fileName, out string errMsg)
        {
            try
            {
                SetToDefault();

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(fileName);
                XmlElement rootElem = xmlDoc.DocumentElement;

                if (rootElem.SelectSingleNode("ListenerOptions") is XmlNode listenerOptionsNode)
                {
                    ListenerOptions.LoadFromXml(listenerOptionsNode);
                }

                if (rootElem.SelectSingleNode("ReverseConnection") is XmlElement reverseConnectionElem)
                {
                    ReverseConnectionOptions.Enabled = reverseConnectionElem.GetAttrAsBool("enabled");
                    ReverseConnectionOptions.LoadFromXml(reverseConnectionElem);
                }

                if (rootElem.SelectSingleNode("Instances") is XmlNode instancesNode)
                {
                    foreach (XmlElement instanceElem in instancesNode.SelectNodes("Instance"))
                    {
                        InstanceOptions instanceConfig = new InstanceOptions();
                        instanceConfig.LoadFromXml(instanceElem);
                        Instances.Add(instanceConfig);
                    }
                }

                errMsg = "";
                return(true);
            }
            catch (Exception ex)
            {
                errMsg = ex.BuildErrorMessage(CommonPhrases.LoadConfigError);
                return(false);
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Sets the controls according to the configuration.
        /// </summary>
        private void ConfigToControls()
        {
            changing = true;

            // general options
            GeneralOptions generalOptions = serverConfig.GeneralOptions;

            numUnrelIfInactive.SetValue(generalOptions.UnrelIfInactive);
            chkGenerateAckCmd.Checked = generalOptions.GenerateAckCmd;
            numMaxLogSize.SetValue(generalOptions.MaxLogSize);
            chkDisableFormulas.Checked    = generalOptions.DisableFormulas;
            txtEnableFormulasObjNums.Text = generalOptions.EnableFormulasObjNums.ToRangeString();

            // listener options
            ListenerOptions listenerOptions = serverConfig.ListenerOptions;

            numPort.SetValue(listenerOptions.Port);
            numTimeout.SetValue(listenerOptions.Timeout);
            txtSecretKey.Text = ScadaUtils.BytesToHex(listenerOptions.SecretKey);

            changing = false;
        }
        public async Task TestE2E()
        {
            var port = new Random().Next(20000, 40000);

            var options = new ListenerOptions
            {
                ListeningOn    = new IPEndPoint(IPAddress.Loopback, port),
                DefaultRealm   = "corp2.identityintervention.com".ToUpper(),
                IsDebug        = true,
                RealmLocator   = realm => LocateRealm(realm),
                ReceiveTimeout = TimeSpan.FromHours(1)
            };

            using (KdcServiceListener listener = new KdcServiceListener(options))
            {
                _ = listener.Start();

                await RequestAndValidateTickets("*****@*****.**", "P@ssw0rd!", $"127.0.0.1:{port}");

                listener.Stop();
            }
        }
        public async Task TestReceiveTimeout()
        {
            var port = new Random().Next(20000, 40000);
            var log  = new ExceptionTraceLog();

            var options = new ListenerOptions
            {
                ListeningOn    = new IPEndPoint(IPAddress.Loopback, port),
                DefaultRealm   = "corp2.identityintervention.com".ToUpper(),
                IsDebug        = true,
                RealmLocator   = realm => LocateRealm(realm, slow: true),
                ReceiveTimeout = TimeSpan.FromMilliseconds(1),
                Log            = log
            };

            options.Log.Enabled = true;
            options.Log.Level   = LogLevel.Verbose;

            KdcServiceListener listener = new KdcServiceListener(options);

            _ = listener.Start();

            try
            {
                await RequestAndValidateTickets("*****@*****.**", "P@ssw0rd!", $"127.0.0.1:{port}");
            }
            catch
            {
            }

            listener.Stop();

            var timeout = log.Exceptions.FirstOrDefault(e => e is TimeoutException);

            Assert.IsNotNull(timeout);

            throw timeout;
        }
Esempio n. 25
0
        public static KdcListener StartListener(int port, bool slow = false)
        {
            var options = new ListenerOptions
            {
                ListeningOn    = new IPEndPoint(IPAddress.Loopback, port),
                DefaultRealm   = "corp2.identityintervention.com".ToUpper(),
                IsDebug        = true,
                RealmLocator   = realm => LocateRealm(realm, slow),
                ReceiveTimeout = TimeSpan.FromHours(1)
            };

            var server = new KdcServer(options);

            server.RegisterPreAuthHandler(
                PaDataType.PA_PK_AS_REQ,
                service => new PaDataPkAsReqHandler(service)
            {
                IncludeOption = X509IncludeOption.EndCertOnly
            }
                );

            return(new KdcListener(server));
        }
Esempio n. 26
0
        public Task Setup()
        {
            Port = new Random().Next(20000, 40000);

            var options = new ListenerOptions
            {
                ListeningOn    = new IPEndPoint(IPAddress.Loopback, Port),
                DefaultRealm   = "corp2.identityintervention.com".ToUpper(),
                RealmLocator   = realm => LocateRealm(realm),
                QueueLength    = 10 * 1000,
                ReceiveTimeout = TimeSpan.FromMinutes(60),
                Log            = null
            };

            listener = new KdcServiceListener(options);
            _        = listener.Start();

            credential = Creds.GetOrAdd(AlgorithmType, a => new KerberosPasswordCredential(a + user, password));

            asReq = new ReadOnlySequence <byte>(KrbAsReq.CreateAsReq(credential, DefaultAuthentication).EncodeApplication());

            return(Task.CompletedTask);
        }
Esempio n. 27
0
        /// <summary>
        /// Saves the configuration to the specified file.
        /// </summary>
        public bool Save(string fileName, out string errMsg)
        {
            try
            {
                XmlDocument    xmlDoc  = new XmlDocument();
                XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                xmlDoc.AppendChild(xmlDecl);

                XmlElement rootElem = xmlDoc.CreateElement("ScadaServerConfig");
                xmlDoc.AppendChild(rootElem);

                GeneralOptions.SaveToXml(rootElem.AppendElem("GeneralOptions"));
                ListenerOptions.SaveToXml(rootElem.AppendElem("ListenerOptions"));
                PathOptions.SaveToXml(rootElem.AppendElem("PathOptions"));

                XmlElement modulesElem = rootElem.AppendElem("Modules");
                foreach (string moduleCode in ModuleCodes)
                {
                    modulesElem.AppendElem("Module").SetAttribute("code", moduleCode);
                }

                XmlElement archivesElem = rootElem.AppendElem("Archives");
                foreach (ArchiveConfig archiveConfig in Archives)
                {
                    archiveConfig.SaveToXml(archivesElem.AppendElem("Archive"));
                }

                xmlDoc.Save(fileName);
                errMsg = "";
                return(true);
            }
            catch (Exception ex)
            {
                errMsg = CommonPhrases.SaveAppConfigError + ": " + ex.Message;
                return(false);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Read data from the meter.
        /// </summary>
        private static void ReadMeter(object parameter)
        {
            GXDLMSReader reader = null;

            System.Net.Http.HttpClient httpClient = Helpers.client;
            using (GXNet media = (GXNet)parameter)
            {
                try
                {
                    var config = new ConfigurationBuilder()
                                 .SetBasePath(Directory.GetCurrentDirectory())
                                 .AddJsonFile("appsettings.json", optional: true)
                                 .Build();
                    ListenerOptions        listener = config.GetSection("Listener").Get <ListenerOptions>();
                    GXDLMSObjectCollection objects  = new GXDLMSObjectCollection();
                    GXDLMSSecureClient     client   = new GXDLMSSecureClient(listener.UseLogicalNameReferencing, listener.ClientAddress, listener.ServerAddress, (Authentication)listener.Authentication, listener.Password, (InterfaceType)listener.Interface);
                    reader = new GXDLMSReader(client, media, _logger);
                    GXDLMSData ldn = new GXDLMSData("0.0.42.0.0.255");
                    ldn.SetUIDataType(2, DataType.String);
                    reader.InitializeConnection();
                    reader.Read(ldn, 2);
                    Console.WriteLine("Meter connected: " + ldn.Value);
                    //Find device.
                    GXDevice            dev  = null;
                    ListDevicesResponse devs = null;
                    {
                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices()
                        {
                            Name = (string)ldn.Value
                        }).Result)
                        {
                            Helpers.CheckStatus(response);
                            devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result;
                        }
                        //If device is unknown.
                        if (devs.Devices.Length == 0)
                        {
                            if (listener.DefaultDeviceTemplate == 0)
                            {
                                string str = "Unknown Meter try to connect to the Gurux.DLMS.AMI server: " + ldn.Value;
                                Console.WriteLine(str);
                                AddSystemError info = new AddSystemError();
                                info.Error = new GXSystemError()
                                {
                                    Error = str
                                };
                                using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result)
                                {
                                    Helpers.CheckStatus(response);
                                }
                                return;
                            }
                            ListDeviceTemplates lt = new ListDeviceTemplates()
                            {
                                Ids = new UInt64[] { listener.DefaultDeviceTemplate }
                            };
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/template/ListDeviceTemplates", lt).Result)
                            {
                                Helpers.CheckStatus(response);
                                ListDeviceTemplatesResponse ret = response.Content.ReadAsAsync <ListDeviceTemplatesResponse>().Result;
                                if (ret.Devices.Length != 1)
                                {
                                    throw new Exception("DefaultDeviceTemplate value is invalid: " + listener.DefaultDeviceTemplate);
                                }
                                dev = new GXDevice();
                                GXDevice.Copy(dev, ret.Devices[0]);
                                dev.Name         = Convert.ToString(ldn.Value);
                                dev.TemplateId   = listener.DefaultDeviceTemplate;
                                dev.Manufacturer = ret.Devices[0].Name;
                            }
                            dev.Dynamic = true;
                            UpdateDevice update = new UpdateDevice();
                            update.Device = dev;
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/UpdateDevice", update).Result)
                            {
                                Helpers.CheckStatus(response);
                                UpdateDeviceResponse r = response.Content.ReadAsAsync <UpdateDeviceResponse>().Result;
                                dev.Id = r.DeviceId;
                            }
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices()
                            {
                                Ids = new UInt64[] { dev.Id }
                            }).Result)
                            {
                                Helpers.CheckStatus(response);
                                devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result;
                            }
                        }
                        else if (devs.Devices.Length != 1)
                        {
                            throw new Exception("There are multiple devices with same name: " + ldn.Value);
                        }
                        else
                        {
                            dev = devs.Devices[0];
                            if (dev.Security != Security.None)
                            {
                                Console.WriteLine("Reading frame counter.");
                                GXDLMSData fc = new GXDLMSData(listener.InvocationCounter);
                                reader.Read(fc, 2);
                                dev.InvocationCounter = 1 + Convert.ToUInt32(fc.Value);
                                Console.WriteLine("Device ID: " + dev.Id + " LDN: " + (string)ldn.Value);
                                Console.WriteLine("Frame counter: " + dev.FrameCounter);
                            }
                            GetNextTaskResponse ret;
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/GetNextTask", new GetNextTask()
                            {
                                Listener = true, DeviceId = dev.Id
                            }).Result)
                            {
                                Helpers.CheckStatus(response);
                                ret = response.Content.ReadAsAsync <GetNextTaskResponse>().Result;
                            }
                            if (ret.Tasks == null || ret.Tasks.Length == 0)
                            {
                                Console.WriteLine("No tasks to execute");
                            }
                            else
                            {
                                Console.WriteLine("Task count: " + ret.Tasks.Length);
                                if (client.ClientAddress != dev.ClientAddress || dev.Security != Security.None)
                                {
                                    reader.Release();
                                    reader.Disconnect();
                                    client             = new GXDLMSSecureClient(dev.UseLogicalNameReferencing, dev.ClientAddress, dev.PhysicalAddress, (Authentication)dev.Authentication, dev.Password, dev.InterfaceType);
                                    client.UtcTimeZone = dev.UtcTimeZone;
                                    client.Standard    = (Standard)dev.Standard;
                                    if (dev.Conformance != 0)
                                    {
                                        client.ProposedConformance = (Conformance)dev.Conformance;
                                    }
                                    client.Priority                    = dev.Priority;
                                    client.ServiceClass                = dev.ServiceClass;
                                    client.Ciphering.SystemTitle       = GXCommon.HexToBytes(dev.ClientSystemTitle);
                                    client.Ciphering.BlockCipherKey    = GXCommon.HexToBytes(dev.BlockCipherKey);
                                    client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(dev.AuthenticationKey);
                                    client.ServerSystemTitle           = GXCommon.HexToBytes(dev.DeviceSystemTitle);
                                    client.Ciphering.InvocationCounter = dev.InvocationCounter;
                                    client.Ciphering.Security          = (Security)dev.Security;
                                    reader = new GXDLMSReader(client, media, _logger);
                                    reader.InitializeConnection();
                                }
                                List <GXValue> values = new List <GXValue>();
                                foreach (GXTask task in ret.Tasks)
                                {
                                    GXDLMSObject obj = GXDLMSClient.CreateObject((ObjectType)task.Object.ObjectType);
                                    obj.LogicalName = task.Object.LogicalName;
                                    try
                                    {
                                        if (task.TaskType == TaskType.Write)
                                        {
                                            if (obj.LogicalName == "0.0.1.1.0.255" && task.Index == 2)
                                            {
                                                client.UpdateValue(obj, task.Index, GXDateTime.ToUnixTime(DateTime.UtcNow));
                                            }
                                            else
                                            {
                                                client.UpdateValue(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data));
                                            }
                                            reader.Write(obj, task.Index);
                                        }
                                        else if (task.TaskType == TaskType.Action)
                                        {
                                            reader.Method(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data), DataType.None);
                                        }
                                        else if (task.TaskType == TaskType.Read)
                                        {
                                            Reader.Reader.Read(null, httpClient, reader, task, media, obj);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        task.Result = ex.Message;
                                        AddError error = new AddError();
                                        error.Error = new GXError()
                                        {
                                            DeviceId = dev.Id,
                                            Error    = "Failed to " + task.TaskType + " " + task.Object.LogicalName + ":" + task.Index + ". " + ex.Message
                                        };
                                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error).Result)
                                        {
                                            Helpers.CheckStatus(response);
                                            response.Content.ReadAsAsync <AddErrorResponse>();
                                        }
                                    }
                                    using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/TaskReady", new TaskReady()
                                    {
                                        Tasks = new GXTask[] { task }
                                    }).Result)
                                    {
                                        Helpers.CheckStatus(response);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        AddSystemError info = new AddSystemError();
                        info.Error = new GXSystemError()
                        {
                            Error = ex.Message
                        };
                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result)
                        {
                            Helpers.CheckStatus(response);
                        }
                    }
                    catch (Exception ex2)
                    {
                    }
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }
Esempio n. 29
0
 /// <summary>
 ///  Create an <see cref="INetListener">.
 /// </summary>
 /// <param name="options"></param>
 /// <returns></returns>
 public INetListener CreateListener(ListenerOptions options)
 {
     return(new DotNettyListenerAdapter(options, _serviceProvider));
 }
Esempio n. 30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
#if !NETCOREAPP2_0 && !NETCOREAPP2_1
            services.AddControllers();
#endif//!NETCOREAPP2_0 && !NETCOREAPP2_1
            DatabaseOptions db       = Configuration.GetSection("Database").Get <DatabaseOptions>();
            string          settings = db.Settings;
            string          type     = db.Type;
            bool            disabled = db.Disabled;
            if (disabled)
            {
                Console.WriteLine("Database service is disabled.");
            }
            else
            {
                Console.WriteLine("Database type: " + type);
                Console.WriteLine("Connecting: " + settings);
            }
            DbConnection connection;
            if (disabled || string.IsNullOrEmpty(type))
            {
                //Gurux.DLMS.AMI DB is defined elsewhere.
                connection = null;
            }
            else if (string.Compare(type, "Oracle", true) == 0)
            {
                connection = new OracleConnection(settings);
            }
            else if (string.Compare(type, "MSSQL", true) == 0)
            {
                connection = new SqlConnection(settings);
            }
            else if (string.Compare(type, "MySQL", true) == 0)
            {
                connection = new MySql.Data.MySqlClient.MySqlConnection(settings);
            }
            else if (string.Compare(type, "SQLite", true) == 0)
            {
                connection = new SQLiteConnection(settings);
            }
            else
            {
                throw new Exception("Invalid connection type. " + type);
            }
            if (connection != null)
            {
                connection.Open();
                GXHost h = new GXHost()
                {
                    Connection = new GXDbConnection(connection, null)
                };
                h.Connection.OnSqlExecuted += Connection_OnSqlExecuted;
                if (!h.Connection.TableExist <GXDevice>())
                {
                    Console.WriteLine("Creating tables.");
                    h.Connection.CreateTable <GXSystemError>(false, false);
                    h.Connection.CreateTable <GXDeviceTemplate>(false, false);
                    h.Connection.CreateTable <GXDevice>(false, false);
                    h.Connection.CreateTable <GXObjectTemplate>(false, false);
                    h.Connection.CreateTable <GXAttributeTemplate>(false, false);
                    h.Connection.CreateTable <GXObject>(false, false);
                    h.Connection.CreateTable <GXAttribute>(false, false);
                    h.Connection.CreateTable <GXValue>(false, false);
                    h.Connection.CreateTable <GXTask>(false, false);
                    h.Connection.CreateTable <GXError>(false, false);
                    h.Connection.CreateTable <GXSchedule>(false, false);
                    h.Connection.CreateTable <GXScheduleToAttribute>(false, false);
                    h.Connection.CreateTable <GXSchedulerInfo>(false, false);
                    h.Connection.CreateTable <GXReaderInfo>(false, false);
                    h.Connection.CreateTable <GXDeviceToReader>(false, false);
                    h.Connection.CreateTable <GXDeviceLog>(false, false);
                    AddSchedule(h.Connection);
                }
                else
                {
                    h.Connection.UpdateTable <GXSystemError>();
                    h.Connection.UpdateTable <GXError>();
                    h.Connection.UpdateTable <GXReaderInfo>();
                    h.Connection.UpdateTable <GXObjectTemplate>();
                    h.Connection.UpdateTable <GXAttributeTemplate>();
                    h.Connection.UpdateTable <GXDeviceTemplate>();
                    h.Connection.UpdateTable <GXObject>();
                    h.Connection.UpdateTable <GXAttribute>();
                    h.Connection.UpdateTable <GXDevice>();
                    if (!h.Connection.TableExist <GXDeviceLog>())
                    {
                        h.Connection.CreateTable <GXDeviceLog>(false, false);
                    }
                    else
                    {
                        h.Connection.UpdateTable <GXDeviceLog>();
                    }
                }
                h.Connection.Insert(GXInsertArgs.Insert(new GXSystemError()
                {
                    Generation = DateTime.Now,
                    Error      = "Service started: " + ServerAddress
                }));;
                Console.WriteLine("Service started: " + ServerAddress);
                services.AddScoped <GXHost>(q =>
                {
                    return(h);
                });
            }
            services.Configure <ListenerOptions>(Configuration.GetSection("Listener"));
            ListenerOptions listener = Configuration.GetSection("Listener").Get <ListenerOptions>();
            if (!listener.Disabled)
            {
                services.AddHostedService <GXListenerService>();
            }
            else
            {
                Console.WriteLine("Listener service is disabled.");
            }
            services.Configure <NotifyOptions>(Configuration.GetSection("Notify"));
            NotifyOptions n = Configuration.GetSection("Notify").Get <NotifyOptions>();
            if (!n.Disabled && n.Port != 0)
            {
                services.AddHostedService <GXNotifyService>();
            }
            else
            {
                Console.WriteLine("Notify service is disabled.");
            }
            services.Configure <SchedulerOptions>(Configuration.GetSection("Scheduler"));
            SchedulerOptions s = Configuration.GetSection("Scheduler").Get <SchedulerOptions>();
            if (!s.Disabled)
            {
                services.AddHostedService <GXSchedulerService>();
            }
            else
            {
                Console.WriteLine("Scheduler service is disabled.");
            }
            services.Configure <ReaderOptions>(Configuration.GetSection("Reader"));
            ReaderOptions r = Configuration.GetSection("Reader").Get <ReaderOptions>();
            Console.WriteLine("Reader trace level is " + r.TraceLevel);
            Console.WriteLine("Listener trace level is " + listener.TraceLevel);
            if (r.Threads != 0 && !r.Disabled)
            {
                services.AddHostedService <ReaderService>();
            }
            else
            {
                Console.WriteLine("Reader '" + r.Name + "' ID: " + r.Id);
            }
#if NETCOREAPP2_0 || NETCOREAPP2_1
            services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);
#endif //NETCOREAPP2_0 || NETCOREAPP2_1
        }