Esempio n. 1
0
        internal bool addOrUpdateMap(Ice.Communicator communicator, string mapName, IMetricsMapFactory factory,
                                     Ice.Logger logger)
        {
            //
            // Add maps to views configured with the given map.
            //
            string viewPrefix = "IceMX.Metrics." + _name + ".";
            string mapsPrefix = viewPrefix + "Map.";
            Dictionary <string, string> mapsProps = communicator.GetProperties(forPrefix: mapsPrefix);

            string mapPrefix;
            Dictionary <string, string> mapProps = new Dictionary <string, string>();

            if (mapsProps.Count > 0)
            {
                mapPrefix = mapsPrefix + mapName + ".";
                mapProps  = communicator.GetProperties(forPrefix: mapPrefix);
                if (mapProps.Count == 0)
                {
                    // This map isn't configured for this view.
                    return(_maps.Remove(mapName));
                }
            }
            else
            {
                mapPrefix = viewPrefix;
                mapProps  = communicator.GetProperties(forPrefix: mapPrefix);
            }

            if (communicator.GetPropertyAsInt($"{mapPrefix}Disabled") > 0)
            {
                // This map is disabled for this view.
                return(_maps.Remove(mapName));
            }

            IMetricsMap m;

            if (_maps.TryGetValue(mapName, out m) && Ice.Collections.Equals(m.getProperties(), mapProps))
            {
                return(false); // The map configuration didn't change, no need to re-create.
            }

            try
            {
                _maps[mapName] = factory.create(mapPrefix, communicator);
            }
            catch (Exception ex)
            {
                logger.warning("unexpected exception while creating metrics map:\n" + ex);
                _maps.Remove(mapName);
            }
            return(true);
        }
Esempio n. 2
0
        private Dictionary <string, Regex> parseRule(Ice.Communicator communicator, string name)
        {
            Dictionary <string, Regex>  pats  = new Dictionary <string, Regex>();
            Dictionary <string, string> rules = communicator.GetProperties(forPrefix: $"{name}.");

            foreach (KeyValuePair <string, string> e in rules)
            {
                pats.Add(e.Key.Substring(name.Length + 1), new Regex(e.Value));
            }
            return(pats);
        }
Esempio n. 3
0
        internal TrustManager(Ice.Communicator communicator)
        {
            Debug.Assert(communicator != null);
            _communicator = communicator;
            _traceLevel   = _communicator.GetPropertyAsInt("IceSSL.Trace.Security") ?? 0;
            string key = "IceSSL.TrustOnly";

            try
            {
                Parse(_communicator.GetProperty(key) ?? "", _rejectAll, _acceptAll);
                key = "IceSSL.TrustOnly.Client";
                Parse(_communicator.GetProperty(key) ?? "", _rejectClient, _acceptClient);
                key = "IceSSL.TrustOnly.Server";
                Parse(_communicator.GetProperty(key) ?? "", _rejectAllServer, _acceptAllServer);
                Dictionary <string, string> dict = _communicator.GetProperties(forPrefix: "IceSSL.TrustOnly.Server.");
                foreach (KeyValuePair <string, string> entry in dict)
                {
                    key = entry.Key;
                    string name   = key.Substring("IceSSL.TrustOnly.Server.".Length);
                    var    reject = new List <List <RFC2253.RDNPair> >();
                    var    accept = new List <List <RFC2253.RDNPair> >();
                    Parse(entry.Value, reject, accept);
                    if (reject.Count > 0)
                    {
                        _rejectServer[name] = reject;
                    }

                    if (accept.Count > 0)
                    {
                        _acceptServer[name] = accept;
                    }
                }
            }
            catch (FormatException ex)
            {
                throw new FormatException($"IceSSL: invalid property `{key};", ex);
            }
        }
Esempio n. 4
0
        private static async Task <int> RunAsync(Ice.Communicator communicator, string[] args)
        {
            const string prefix = "IceBox.Service.";
            Dictionary <string, string> services = communicator.GetProperties(forPrefix: prefix);

            var argSeq = new List <string>(args);

            foreach (KeyValuePair <string, string> pair in services)
            {
                string name = pair.Key.Substring(prefix.Length);
                argSeq.RemoveAll(v => v.StartsWith("--" + name));
            }

            foreach (string arg in args)
            {
                if (arg.Equals("-h") || arg.Equals("--help"))
                {
                    Usage();
                    return(0);
                }
                else if (arg.Equals("-v") || arg.Equals("--version"))
                {
                    Console.Out.WriteLine(Ice.Runtime.StringVersion);
                    return(0);
                }
                else
                {
                    Console.Error.WriteLine($"IceBox.Server: unknown option `{arg}'");
                    Usage();
                    return(1);
                }
            }

            var serviceManager = new ServiceManager(communicator, args);

            return(await serviceManager.RunAsync().ConfigureAwait(false));
        }
Esempio n. 5
0
        private static int Run(Ice.Communicator communicator, string[] args)
        {
            const string prefix = "IceBox.Service.";
            Dictionary <string, string> services = communicator.GetProperties(forPrefix: prefix);

            var argSeq = new List <string>(args);

            foreach (KeyValuePair <string, string> pair in services)
            {
                string name = pair.Key.Substring(prefix.Length);
                argSeq.RemoveAll(v => v.StartsWith("--" + name));
            }

            foreach (string arg in args)
            {
                if (arg.Equals("-h") || arg.Equals("--help"))
                {
                    Usage();
                    return(0);
                }
                else if (arg.Equals("-v") || arg.Equals("--version"))
                {
                    Console.Out.WriteLine(Ice.Util.StringVersion());
                    return(0);
                }
                else
                {
                    Console.Error.WriteLine("IceBox.Server: unknown option `" + arg + "'");
                    Usage();
                    return(1);
                }
            }

            var serviceManagerImpl = new ServiceManager(communicator, args);

            return(serviceManagerImpl.Run());
        }
Esempio n. 6
0
        public static void validateProperties(string prefix, Ice.Communicator communicator)
        {
            Dictionary <string, string> props = communicator.GetProperties(forPrefix: prefix);
            List <string> unknownProps        = new List <string>();

            foreach (string prop in props.Keys)
            {
                bool valid = false;
                foreach (string suffix in suffixes)
                {
                    if (IceUtilInternal.StringUtil.match(prop, prefix + suffix, false))
                    {
                        valid = true;
                        break;
                    }
                }

                if (!valid)
                {
                    unknownProps.Add(prop);
                }
            }

            if (unknownProps.Count != 0 && (communicator.GetPropertyAsInt("Ice.Warn.UnknownProperties") ?? 1) > 0)
            {
                StringBuilder message = new StringBuilder("found unknown IceMX properties for `");
                message.Append(prefix.Substring(0, prefix.Length - 1));
                message.Append("':");
                foreach (string p in unknownProps)
                {
                    message.Append("\n    ");
                    message.Append(p);
                }
                Ice.Util.getProcessLogger().warning(message.ToString());
            }
        }
Esempio n. 7
0
            public static Test.ITestIntfPrx allTests(global::Test.TestHelper helper)
            {
                Ice.Communicator communicator = helper.communicator();
                var output = helper.getWriter();

                output.Write("testing stringToProxy... ");
                output.Flush();
                string @ref = "test:" + helper.getTestEndpoint(0);

                Ice.IObjectPrx @base = IObjectPrx.Parse(@ref, communicator);
                test(@base != null);
                output.WriteLine("ok");

                output.Write("testing checked cast... ");
                output.Flush();
                var obj = Test.ITestIntfPrx.CheckedCast(@base);

                test(obj != null);
                test(obj.Equals(@base));
                output.WriteLine("ok");

                {
                    output.Write("creating/destroying/recreating object adapter... ");
                    output.Flush();
                    ObjectAdapter adapter =
                        communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
                    try
                    {
                        communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
                        test(false);
                    }
                    catch (ArgumentException)
                    {
                    }
                    adapter.Destroy();

                    //
                    // Use a different port than the first adapter to avoid an "address already in use" error.
                    //
                    adapter = communicator.createObjectAdapterWithEndpoints("TransientTestAdapter", "default");
                    adapter.Destroy();
                    output.WriteLine("ok");
                }

                output.Write("creating/activating/deactivating object adapter in one operation... ");
                output.Flush();
                obj.transient();
                obj.transientAsync().Wait();
                output.WriteLine("ok");

                {
                    output.Write("testing connection closure... ");
                    output.Flush();
                    for (int i = 0; i < 10; ++i)
                    {
                        var comm = new Communicator(communicator.GetProperties());
                        IObjectPrx.Parse($"test:{helper.getTestEndpoint(0)}", communicator).IcePingAsync();
                        comm.destroy();
                    }
                    output.WriteLine("ok");
                }

                output.Write("testing object adapter published endpoints... ");
                output.Flush();
                {
                    communicator.SetProperty("PAdapter.PublishedEndpoints", "tcp -h localhost -p 12345 -t 30000");
                    var adapter = communicator.createObjectAdapter("PAdapter");
                    test(adapter.GetPublishedEndpoints().Length == 1);
                    var endpt = adapter.GetPublishedEndpoints()[0];
                    test(endpt.ToString().Equals("tcp -h localhost -p 12345 -t 30000"));
                    var prx = IObjectPrx.Parse("dummy:tcp -h localhost -p 12346 -t 20000:tcp -h localhost -p 12347 -t 10000", communicator);
                    adapter.SetPublishedEndpoints(prx.Endpoints);
                    test(adapter.GetPublishedEndpoints().Length == 2);
                    test(Collections.Equals(adapter.CreateProxy(new Identity("dummy", "")).Endpoints, prx.Endpoints));
                    test(Collections.Equals(adapter.GetPublishedEndpoints(), prx.Endpoints));
                    adapter.RefreshPublishedEndpoints();
                    test(adapter.GetPublishedEndpoints().Length == 1);
                    test(adapter.GetPublishedEndpoints()[0].Equals(endpt));
                    communicator.SetProperty("PAdapter.PublishedEndpoints", "tcp -h localhost -p 12345 -t 20000");
                    adapter.RefreshPublishedEndpoints();
                    test(adapter.GetPublishedEndpoints().Length == 1);
                    test(adapter.GetPublishedEndpoints()[0].ToString().Equals("tcp -h localhost -p 12345 -t 20000"));
                    adapter.Destroy();
                    test(adapter.GetPublishedEndpoints().Length == 0);
                }
                output.WriteLine("ok");

                if (obj.GetConnection() != null)
                {
                    output.Write("testing object adapter with bi-dir connection... ");
                    output.Flush();
                    var adapter = communicator.createObjectAdapter("");
                    obj.GetConnection().setAdapter(adapter);
                    obj.GetConnection().setAdapter(null);
                    adapter.Deactivate();
                    try
                    {
                        obj.GetConnection().setAdapter(adapter);
                        test(false);
                    }
                    catch (ObjectAdapterDeactivatedException)
                    {
                    }
                    output.WriteLine("ok");
                }

                output.Write("testing object adapter with router... ");
                output.Flush();
                {
                    var routerId = new Identity();
                    routerId.name = "router";
                    var router  = IRouterPrx.UncheckedCast(@base.Clone(routerId, connectionId: "rc"));
                    var adapter = communicator.createObjectAdapterWithRouter("", router);
                    test(adapter.GetPublishedEndpoints().Length == 1);
                    test(adapter.GetPublishedEndpoints()[0].ToString().Equals("tcp -h localhost -p 23456 -t 30000"));
                    adapter.RefreshPublishedEndpoints();
                    test(adapter.GetPublishedEndpoints().Length == 1);
                    test(adapter.GetPublishedEndpoints()[0].ToString().Equals("tcp -h localhost -p 23457 -t 30000"));
                    try
                    {
                        adapter.SetPublishedEndpoints(router.Endpoints);
                        test(false);
                    }
                    catch (ArgumentException)
                    {
                        // Expected.
                    }
                    adapter.Destroy();

                    try
                    {
                        routerId.name = "test";
                        router        = IRouterPrx.UncheckedCast(@base.Clone(routerId));
                        communicator.createObjectAdapterWithRouter("", router);
                        test(false);
                    }
                    catch (OperationNotExistException)
                    {
                        // Expected: the "test" object doesn't implement Ice::Router!
                    }

                    try
                    {
                        router = IRouterPrx.Parse($"test:{helper.getTestEndpoint(1)}", communicator);
                        communicator.createObjectAdapterWithRouter("", router);
                        test(false);
                    }
                    catch (ConnectFailedException)
                    {
                    }
                }
                output.WriteLine("ok");

                output.Write("testing object adapter creation with port in use... ");
                output.Flush();
                {
                    var adapter1 = communicator.createObjectAdapterWithEndpoints("Adpt1", helper.getTestEndpoint(10));
                    try
                    {
                        communicator.createObjectAdapterWithEndpoints("Adpt2", helper.getTestEndpoint(10));
                        test(false);
                    }
                    catch (LocalException)
                    {
                        // Expected can't re-use the same endpoint.
                    }
                    adapter1.Destroy();
                }
                output.WriteLine("ok");

                output.Write("deactivating object adapter in the server... ");
                output.Flush();
                obj.deactivate();
                output.WriteLine("ok");

                output.Write("testing whether server is gone... ");
                output.Flush();
                try
                {
                    obj.Clone(connectionTimeout: 100).IcePing(); // Use timeout to speed up testing on Windows
                    test(false);
                }
                catch (LocalException)
                {
                    output.WriteLine("ok");
                }

                return(obj);
            }
Esempio n. 8
0
        internal void Initialize()
        {
            if (_initialized)
            {
                return;
            }

            Ice.Communicator ic = Communicator();
            //
            // Check for a default directory. We look in this directory for
            // files mentioned in the configuration.
            //
            _defaultDir = ic.GetProperty("IceSSL.DefaultDir") ?? "";

            string        certStoreLocation = ic.GetProperty("IceSSL.CertStoreLocation") ?? "CurrentUser";
            StoreLocation storeLocation;

            if (certStoreLocation == "CurrentUser")
            {
                storeLocation = StoreLocation.CurrentUser;
            }
            else if (certStoreLocation == "LocalMachine")
            {
                storeLocation = StoreLocation.LocalMachine;
            }
            else
            {
                _logger.Warning($"Invalid IceSSL.CertStoreLocation value `{certStoreLocation}' adjusted to `CurrentUser'");
                storeLocation = StoreLocation.CurrentUser;
            }
            _useMachineContext = certStoreLocation == "LocalMachine";

            //
            // Protocols selects which protocols to enable
            //
            string[]? protocols = ic.GetPropertyAsList("IceSSL.Protocols");
            if (protocols != null)
            {
                _protocols = ParseProtocols(protocols);
            }

            //
            // CheckCertName determines whether we compare the name in a peer's
            // certificate against its hostname.
            //
            _checkCertName = ic.GetPropertyAsBool("IceSSL.CheckCertName") ?? false;

            //
            // VerifyDepthMax establishes the maximum length of a peer's certificate
            // chain, including the peer's certificate. A value of 0 means there is
            // no maximum.
            //
            _verifyDepthMax = ic.GetPropertyAsInt("IceSSL.VerifyDepthMax") ?? 3;

            //
            // CheckCRL determines whether the certificate revocation list is checked, and how strictly.
            //
            _checkCRL = ic.GetPropertyAsInt("IceSSL.CheckCRL") ?? 0;

            //
            // Check for a certificate verifier.
            //
            string?certVerifierClass = ic.GetProperty("IceSSL.CertVerifier");

            if (certVerifierClass != null)
            {
                if (_verifier != null)
                {
                    throw new InvalidOperationException("IceSSL: certificate verifier already installed");
                }

                Type?cls = _facade.FindType(certVerifierClass);
                if (cls == null)
                {
                    throw new InvalidConfigurationException(
                              $"IceSSL: unable to load certificate verifier class `{certVerifierClass}'");
                }

                try
                {
                    _verifier = (ICertificateVerifier?)Activator.CreateInstance(cls);
                }
                catch (Exception ex)
                {
                    throw new LoadException(
                              $"IceSSL: unable to instantiate certificate verifier class `{certVerifierClass}", ex);
                }
            }

            //
            // Check for a password callback.
            //
            string?passwordCallbackClass = ic.GetProperty("IceSSL.PasswordCallback");

            if (passwordCallbackClass != null)
            {
                if (_passwordCallback != null)
                {
                    throw new InvalidOperationException("IceSSL: password callback already installed");
                }

                Type?cls = _facade.FindType(passwordCallbackClass);
                if (cls == null)
                {
                    throw new InvalidConfigurationException(
                              $"IceSSL: unable to load password callback class `{passwordCallbackClass}'");
                }

                try
                {
                    _passwordCallback = (IPasswordCallback?)Activator.CreateInstance(cls);
                }
                catch (Exception ex)
                {
                    throw new LoadException(
                              $"IceSSL: unable to load password callback class {passwordCallbackClass}", ex);
                }
            }

            //
            // If the user hasn't supplied a certificate collection, we need to examine
            // the property settings.
            //
            if (_certs == null)
            {
                //
                // If IceSSL.CertFile is defined, load a certificate from a file and
                // add it to the collection.
                //
                // TODO: tracing?
                _certs = new X509Certificate2Collection();
                string?      certFile    = ic.GetProperty("IceSSL.CertFile");
                string?      passwordStr = ic.GetProperty("IceSSL.Password");
                string?      findCert    = ic.GetProperty("IceSSL.FindCert");
                const string findPrefix  = "IceSSL.FindCert.";
                Dictionary <string, string> findCertProps = ic.GetProperties(forPrefix: findPrefix);

                if (certFile != null)
                {
                    if (!CheckPath(ref certFile))
                    {
                        throw new FileNotFoundException($"IceSSL: certificate file not found: `{certFile}'", certFile);
                    }

                    SecureString?password = null;
                    if (passwordStr != null)
                    {
                        password = CreateSecureString(passwordStr);
                    }
                    else if (_passwordCallback != null)
                    {
                        password = _passwordCallback.GetPassword(certFile);
                    }

                    try
                    {
                        X509Certificate2    cert;
                        X509KeyStorageFlags importFlags;
                        if (_useMachineContext)
                        {
                            importFlags = X509KeyStorageFlags.MachineKeySet;
                        }
                        else
                        {
                            importFlags = X509KeyStorageFlags.UserKeySet;
                        }

                        if (password != null)
                        {
                            cert = new X509Certificate2(certFile, password, importFlags);
                        }
                        else
                        {
                            cert = new X509Certificate2(certFile, "", importFlags);
                        }
                        _certs.Add(cert);
                    }
                    catch (CryptographicException ex)
                    {
                        throw new InvalidConfigurationException(
                                  $"IceSSL: error while attempting to load certificate from `{certFile}'", ex);
                    }
                }
                else if (findCert != null)
                {
                    string certStore = ic.GetProperty("IceSSL.CertStore") ?? "My";
                    _certs.AddRange(FindCertificates("IceSSL.FindCert", storeLocation, certStore, findCert));
                    if (_certs.Count == 0)
                    {
                        throw new InvalidConfigurationException("IceSSL: no certificates found");
                    }
                }
                else if (findCertProps.Count > 0)
                {
                    //
                    // If IceSSL.FindCert.* properties are defined, add the selected certificates
                    // to the collection.
                    //
                    foreach (KeyValuePair <string, string> entry in findCertProps)
                    {
                        string name = entry.Key;
                        string val  = entry.Value;
                        if (val.Length > 0)
                        {
                            string        storeSpec = name.Substring(findPrefix.Length);
                            StoreLocation storeLoc  = 0;
                            StoreName     storeName = 0;
                            string?       sname     = null;
                            ParseStore(name, storeSpec, ref storeLoc, ref storeName, ref sname);
                            if (sname == null)
                            {
                                sname = storeName.ToString();
                            }
                            X509Certificate2Collection coll = FindCertificates(name, storeLoc, sname, val);
                            _certs.AddRange(coll);
                        }
                    }
                    if (_certs.Count == 0)
                    {
                        throw new InvalidConfigurationException("IceSSL: no certificates found");
                    }
                }
            }

            if (_caCerts == null)
            {
                string?certAuthFile = ic.GetProperty("IceSSL.CAs");
                if (certAuthFile == null)
                {
                    certAuthFile = ic.GetProperty("IceSSL.CertAuthFile");
                }

                if (certAuthFile != null || !(ic.GetPropertyAsBool("IceSSL.UsePlatformCAs") ?? false))
                {
                    _caCerts = new X509Certificate2Collection();
                }

                if (certAuthFile != null)
                {
                    if (!CheckPath(ref certAuthFile))
                    {
                        throw new FileNotFoundException("IceSSL: CA certificate file not found: `{certAuthFile}'",
                                                        certAuthFile);
                    }

                    try
                    {
                        using FileStream fs = File.OpenRead(certAuthFile);
                        byte[] data = new byte[fs.Length];
                        fs.Read(data, 0, data.Length);

                        string strbuf = "";
                        try
                        {
                            strbuf = System.Text.Encoding.UTF8.GetString(data);
                        }
                        catch (Exception)
                        {
                            // Ignore
                        }

                        if (strbuf.Length == data.Length)
                        {
                            int  size, startpos, endpos = 0;
                            bool first = true;
                            while (true)
                            {
                                startpos = strbuf.IndexOf("-----BEGIN CERTIFICATE-----", endpos);
                                if (startpos != -1)
                                {
                                    endpos = strbuf.IndexOf("-----END CERTIFICATE-----", startpos);
                                    size   = endpos - startpos + "-----END CERTIFICATE-----".Length;
                                }
                                else if (first)
                                {
                                    startpos = 0;
                                    endpos   = strbuf.Length;
                                    size     = strbuf.Length;
                                }
                                else
                                {
                                    break;
                                }

                                byte[] cert = new byte[size];
                                Buffer.BlockCopy(data, startpos, cert, 0, size);
                                _caCerts !.Import(cert);
                                first = false;
                            }
                        }
                        else
                        {
                            _caCerts !.Import(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidConfigurationException(
                                  $"IceSSL: error while attempting to load CA certificate from {certAuthFile}", ex);
                    }
                }
            }
            _initialized = true;
        }
Esempio n. 9
0
        internal MetricsMap(string mapPrefix, Ice.Communicator communicator, Dictionary <string, ISubMapFactory>?subMaps)
        {
            MetricsAdminI.validateProperties(mapPrefix, communicator);
            _properties = communicator.GetProperties(forPrefix: mapPrefix);

            _retain            = communicator.GetPropertyAsInt($"{mapPrefix}RetainDetached") ?? 10;
            _accept            = parseRule(communicator, $"{mapPrefix}Accept");
            _reject            = parseRule(communicator, $"{mapPrefix}Reject");
            _groupByAttributes = new List <string>();
            _groupBySeparators = new List <string>();

            string groupBy = communicator.GetProperty($"{mapPrefix}GroupBy") ?? "id";

            if (groupBy.Length > 0)
            {
                string v         = "";
                bool   attribute = char.IsLetter(groupBy[0]) || char.IsDigit(groupBy[0]);
                if (!attribute)
                {
                    _groupByAttributes.Add("");
                }

                foreach (char p in groupBy)
                {
                    bool isAlphaNum = char.IsLetter(p) || char.IsDigit(p) || p == '.';
                    if (attribute && !isAlphaNum)
                    {
                        _groupByAttributes.Add(v);
                        v         = "" + p;
                        attribute = false;
                    }
                    else if (!attribute && isAlphaNum)
                    {
                        _groupBySeparators.Add(v);
                        v         = "" + p;
                        attribute = true;
                    }
                    else
                    {
                        v += p;
                    }
                }

                if (attribute)
                {
                    _groupByAttributes.Add(v);
                }
                else
                {
                    _groupBySeparators.Add(v);
                }
            }

            if (subMaps != null && subMaps.Count > 0)
            {
                _subMaps = new Dictionary <string, ISubMapCloneFactory>();

                List <string> subMapNames = new List <string>();
                foreach (KeyValuePair <string, ISubMapFactory> e in subMaps)
                {
                    subMapNames.Add(e.Key);
                    string subMapsPrefix = mapPrefix + "Map.";
                    string subMapPrefix  = subMapsPrefix + e.Key + '.';
                    if (communicator.GetProperties(forPrefix: subMapPrefix).Count == 0)
                    {
                        if (communicator.GetProperties(forPrefix: subMapsPrefix).Count == 0)
                        {
                            subMapPrefix = mapPrefix;
                        }
                        else
                        {
                            continue; // This sub-map isn't configured.
                        }
                    }

                    _subMaps.Add(e.Key, e.Value.createCloneFactory(subMapPrefix, communicator));
                }
            }
            else
            {
                _subMaps = null;
            }
        }