Example #1
0
        internal bool addOrUpdateMap(Ice.Properties properties, 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 = properties.getPropertiesForPrefix(mapsPrefix);

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

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

            if (properties.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, properties);
            }
            catch (Exception ex)
            {
                logger.warning("unexpected exception while creating metrics map:\n" + ex);
                _maps.Remove(mapName);
            }
            return(true);
        }
Example #2
0
 private static void copyProperties(string prefix, Ice.Properties from, Ice.Properties to)
 {
     foreach (var p in from.getPropertiesForPrefix(prefix))
     {
         to.setProperty(p.Key, p.Value);
     }
 }
Example #3
0
        private Dictionary <string, Regex> parseRule(Ice.Properties properties, string name)
        {
            Dictionary <string, Regex>  pats  = new Dictionary <string, Regex>();
            Dictionary <string, string> rules = properties.getPropertiesForPrefix(name + '.');

            foreach (KeyValuePair <string, string> e in rules)
            {
                pats.Add(e.Key.Substring(name.Length + 1), new Regex(e.Value));
            }
            return(pats);
        }
Example #4
0
            public override int run(string[] args)
            {
                List <string> argSeq = new List <string>(args);
                const string  prefix = "IceBox.Service.";

                Ice.Properties properties            = communicator().getProperties();
                Dictionary <string, string> services = properties.getPropertiesForPrefix(prefix);

                foreach (KeyValuePair <string, string> pair in services)
                {
                    string name = pair.Key.Substring(prefix.Length);
                    for (int i = 0; i < argSeq.Count; ++i)
                    {
                        if (argSeq[i].StartsWith("--" + name, StringComparison.CurrentCulture))
                        {
                            argSeq.RemoveAt(i);
                            i--;
                        }
                    }
                }

                foreach (string s in argSeq)
                {
                    if (s.Equals("-h") || s.Equals("--help"))
                    {
                        usage();
                        return(0);
                    }
                    else if (s.Equals("-v") || s.Equals("--version"))
                    {
                        Console.Out.WriteLine(Ice.Util.stringVersion());
                        return(0);
                    }
                    else
                    {
                        Console.Error.WriteLine("Server: unknown option `" + s + "'");
                        usage();
                        return(1);
                    }
                }

                ServiceManagerI serviceManagerImpl = new ServiceManagerI(communicator(), args);

                return(serviceManagerImpl.run());
            }
Example #5
0
        internal TrustManager(Ice.Communicator communicator)
        {
            Debug.Assert(communicator != null);
            communicator_ = communicator;
            Ice.Properties properties = communicator.getProperties();
            traceLevel_ = properties.getPropertyAsInt("IceSSL.Trace.Security");
            string key = null;

            try
            {
                key = "IceSSL.TrustOnly";
                parse(properties.getProperty(key), rejectAll_, acceptAll_);
                key = "IceSSL.TrustOnly.Client";
                parse(properties.getProperty(key), rejectClient_, acceptClient_);
                key = "IceSSL.TrustOnly.Server";
                parse(properties.getProperty(key), rejectAllServer_, acceptAllServer_);
                Dictionary <string, string> dict = properties.getPropertiesForPrefix("IceSSL.TrustOnly.Server.");
                foreach (KeyValuePair <string, string> entry in dict)
                {
                    key = entry.Key;
                    string name = key.Substring("IceSSL.TrustOnly.Server.".Length);
                    List <List <RFC2253.RDNPair> > reject = new List <List <RFC2253.RDNPair> >();
                    List <List <RFC2253.RDNPair> > 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 (RFC2253.ParseException e)
            {
                Ice.PluginInitializationException ex = new Ice.PluginInitializationException();
                ex.reason = "IceSSL: invalid property " + key + ":\n" + e.reason;
                throw ex;
            }
        }
Example #6
0
        private static int run(Ice.Communicator communicator, string[] args)
        {
            const string prefix = "IceBox.Service.";

            Ice.Properties properties            = communicator.getProperties();
            Dictionary <string, string> services = properties.getPropertiesForPrefix(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);
                }
            }

            ServiceManagerI serviceManagerImpl = new ServiceManagerI(communicator, args);

            return(serviceManagerImpl.run());
        }
Example #7
0
        public static void validateProperties(string prefix, Ice.Properties properties)
        {
            Dictionary <string, string> props = properties.getPropertiesForPrefix(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 && properties.getPropertyAsIntWithDefault("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());
            }
        }
Example #8
0
        internal void initialize()
        {
            if (_initialized)
            {
                return;
            }

            const string prefix = "IceSSL.";

            Ice.Properties properties = communicator().getProperties();

            //
            // Check for a default directory. We look in this directory for
            // files mentioned in the configuration.
            //
            _defaultDir = properties.getProperty(prefix + "DefaultDir");

            string        certStoreLocation = properties.getPropertyWithDefault(prefix + "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, by default we only enable TLS1.0
            // TLS1.1 and TLS1.2 to avoid security issues with SSLv3
            //
            _protocols = parseProtocols(
                properties.getPropertyAsListWithDefault(prefix + "Protocols", new string[] { "TLS1_0", "TLS1_1", "TLS1_2" }));
            //
            // CheckCertName determines whether we compare the name in a peer's
            // certificate against its hostname.
            //
            _checkCertName = properties.getPropertyAsIntWithDefault(prefix + "CheckCertName", 0) > 0;

            //
            // 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 = properties.getPropertyAsIntWithDefault(prefix + "VerifyDepthMax", 3);

            //
            // CheckCRL determines whether the certificate revocation list is checked, and how strictly.
            //
            _checkCRL = properties.getPropertyAsIntWithDefault(prefix + "CheckCRL", 0);

            //
            // Check for a certificate verifier.
            //
            string certVerifierClass = properties.getProperty(prefix + "CertVerifier");

            if (certVerifierClass.Length > 0)
            {
                if (_verifier != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: certificate verifier already installed";
                    throw e;
                }

                Type cls = _facade.findType(certVerifierClass);
                if (cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load certificate verifier class " + certVerifierClass;
                    throw e;
                }

                try
                {
                    _verifier = (CertificateVerifier)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch (Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }

                if (_verifier == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }
            }

            //
            // Check for a password callback.
            //
            string passwordCallbackClass = properties.getProperty(prefix + "PasswordCallback");

            if (passwordCallbackClass.Length > 0)
            {
                if (_passwordCallback != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: password callback already installed";
                    throw e;
                }

                Type cls = _facade.findType(passwordCallbackClass);
                if (cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                try
                {
                    _passwordCallback = (PasswordCallback)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch (Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                if (_passwordCallback == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }
            }

            //
            // 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    = properties.getProperty(prefix + "CertFile");
                string       passwordStr = properties.getProperty(prefix + "Password");
                string       findCert    = properties.getProperty(prefix + "FindCert");
                const string findPrefix  = prefix + "FindCert.";
                Dictionary <string, string> findCertProps = properties.getPropertiesForPrefix(findPrefix);

                if (certFile.Length > 0)
                {
                    if (!checkPath(ref certFile))
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: certificate file not found: " + certFile;
                        throw e;
                    }

                    SecureString password = null;
                    if (passwordStr.Length > 0)
                    {
                        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)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                        e.reason = "IceSSL: error while attempting to load certificate from " + certFile;
                        throw e;
                    }
                }
                else if (findCert.Length > 0)
                {
                    string certStore = properties.getPropertyWithDefault("IceSSL.CertStore", "My");
                    _certs.AddRange(findCertificates("IceSSL.FindCert", storeLocation, certStore, findCert));
                    if (_certs.Count == 0)
                    {
                        throw new Ice.PluginInitializationException("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)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: no certificates found";
                        throw e;
                    }
                }
            }

            if (_caCerts == null)
            {
                string certAuthFile = properties.getProperty(prefix + "CAs");
                if (certAuthFile.Length == 0)
                {
                    certAuthFile = properties.getProperty(prefix + "CertAuthFile");
                }
                if (certAuthFile.Length > 0 || properties.getPropertyAsInt(prefix + "UsePlatformCAs") <= 0)
                {
                    _caCerts = new X509Certificate2Collection();
                }
                if (certAuthFile.Length > 0)
                {
                    if (!checkPath(ref certAuthFile))
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: CA certificate file not found: " + certAuthFile;
                        throw e;
                    }

                    try
                    {
                        using (System.IO.FileStream fs = System.IO.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];
                                    System.Buffer.BlockCopy(data, startpos, cert, 0, size);
                                    _caCerts.Import(cert);
                                    first = false;
                                }
                            }
                            else
                            {
                                _caCerts.Import(data);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                        e.reason = "IceSSL: error while attempting to load CA certificate from " + certAuthFile;
                        throw e;
                    }
                }
            }
            _initialized = true;
        }
Example #9
0
        internal MetricsMap(string mapPrefix, Ice.Properties props, Dictionary <string, ISubMapFactory> subMaps)
        {
            MetricsAdminI.validateProperties(mapPrefix, props);
            _properties = props.getPropertiesForPrefix(mapPrefix);

            _retain            = props.getPropertyAsIntWithDefault(mapPrefix + "RetainDetached", 10);
            _accept            = parseRule(props, mapPrefix + "Accept");
            _reject            = parseRule(props, mapPrefix + "Reject");
            _groupByAttributes = new List <string>();
            _groupBySeparators = new List <string>();

            string groupBy = props.getPropertyWithDefault(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 (props.getPropertiesForPrefix(subMapPrefix).Count == 0)
                    {
                        if (props.getPropertiesForPrefix(subMapsPrefix).Count == 0)
                        {
                            subMapPrefix = mapPrefix;
                        }
                        else
                        {
                            continue; // This sub-map isn't configured.
                        }
                    }

                    _subMaps.Add(e.Key, e.Value.createCloneFactory(subMapPrefix, props));
                }
            }
            else
            {
                _subMaps = null;
            }
        }
Example #10
0
        public int run()
        {
            try
            {
                Ice.Properties properties = _communicator.getProperties();

                //
                // Create an object adapter. Services probably should NOT share
                // this object adapter, as the endpoint(s) for this object adapter
                // will most likely need to be firewalled for security reasons.
                //
                Ice.ObjectAdapter adapter = null;
                if (properties.getProperty("IceBox.ServiceManager.Endpoints").Length != 0)
                {
                    adapter = _communicator.createObjectAdapter("IceBox.ServiceManager");

                    Ice.Identity identity = new Ice.Identity();
                    identity.category = properties.getPropertyWithDefault("IceBox.InstanceName", "IceBox");
                    identity.name     = "ServiceManager";
                    adapter.add(this, identity);
                }

                //
                // Parse the property set with the prefix "IceBox.Service.". These
                // properties should have the following format:
                //
                // IceBox.Service.Foo=<assembly>:Package.Foo [args]
                //
                // We parse the service properties specified in IceBox.LoadOrder
                // first, then the ones from remaining services.
                //
                string prefix = "IceBox.Service.";
                Dictionary <string, string> services = properties.getPropertiesForPrefix(prefix);
                string[] loadOrder = properties.getPropertyAsList("IceBox.LoadOrder");
                List <StartServiceInfo> servicesInfo = new List <StartServiceInfo>();
                for (int i = 0; i < loadOrder.Length; ++i)
                {
                    if (loadOrder[i].Length > 0)
                    {
                        string key   = prefix + loadOrder[i];
                        string value = services[key];
                        if (value == null)
                        {
                            FailureException ex = new FailureException();
                            ex.reason = "ServiceManager: no service definition for `" + loadOrder[i] + "'";
                            throw ex;
                        }
                        servicesInfo.Add(new StartServiceInfo(loadOrder[i], value, _argv));
                        services.Remove(key);
                    }
                }
                foreach (KeyValuePair <string, string> entry in services)
                {
                    string name  = entry.Key.Substring(prefix.Length);
                    string value = entry.Value;
                    servicesInfo.Add(new StartServiceInfo(name, value, _argv));
                }

                //
                // Check if some services are using the shared communicator in which
                // case we create the shared communicator now with a property set that
                // is the union of all the service properties (from services that use
                // the shared communicator).
                //
                if (properties.getPropertiesForPrefix("IceBox.UseSharedCommunicator.").Count > 0)
                {
                    Ice.InitializationData initData = new Ice.InitializationData();
                    initData.properties = createServiceProperties("SharedCommunicator");
                    foreach (StartServiceInfo service in servicesInfo)
                    {
                        if (properties.getPropertyAsInt("IceBox.UseSharedCommunicator." + service.name) <= 0)
                        {
                            continue;
                        }

                        //
                        // Load the service properties using the shared communicator properties as
                        // the default properties.
                        //
                        Ice.Properties svcProperties = Ice.Util.createProperties(ref service.args, initData.properties);

                        //
                        // Remove properties from the shared property set that a service explicitly clears.
                        //
                        Dictionary <string, string> allProps = initData.properties.getPropertiesForPrefix("");
                        foreach (string key in allProps.Keys)
                        {
                            if (svcProperties.getProperty(key).Length == 0)
                            {
                                initData.properties.setProperty(key, "");
                            }
                        }

                        //
                        // Add the service properties to the shared communicator properties.
                        //
                        foreach (KeyValuePair <string, string> entry in svcProperties.getPropertiesForPrefix(""))
                        {
                            initData.properties.setProperty(entry.Key, entry.Value);
                        }

                        //
                        // Parse <service>.* command line options (the Ice command line options
                        // were parsed by the call to createProperties above).
                        //
                        service.args = initData.properties.parseCommandLineOptions(service.name, service.args);
                    }

                    string facetNamePrefix = "IceBox.SharedCommunicator.";
                    bool   addFacets       = configureAdmin(initData.properties, facetNamePrefix);

                    _sharedCommunicator = Ice.Util.initialize(initData);

                    if (addFacets)
                    {
                        // Add all facets created on shared communicator to the IceBox communicator
                        // but renamed <prefix>.<facet-name>, except for the Process facet which is
                        // never added.
                        foreach (KeyValuePair <string, Ice.Object> p in _sharedCommunicator.findAllAdminFacets())
                        {
                            if (!p.Key.Equals("Process"))
                            {
                                _communicator.addAdminFacet(p.Value, facetNamePrefix + p.Key);
                            }
                        }
                    }
                }

                foreach (StartServiceInfo s in servicesInfo)
                {
                    startService(s.name, s.entryPoint, s.args);
                }

                //
                // We may want to notify external scripts that the services
                // have started. This is done by defining the property:
                //
                // PrintServicesReady=bundleName
                //
                // Where bundleName is whatever you choose to call this set of
                // services. It will be echoed back as "bundleName ready".
                //
                // This must be done after start() has been invoked on the
                // services.
                //
                string bundleName = properties.getProperty("IceBox.PrintServicesReady");
                if (bundleName.Length > 0)
                {
                    Console.Out.WriteLine(bundleName + " ready");
                }

                //
                // Don't move after the adapter activation. This allows
                // applications to wait for the service manager to be
                // reachable before sending a signal to shutdown the
                //
                //
                Ice.Application.shutdownOnInterrupt();

                //
                // Register "this" as a facet to the Admin object and create Admin object
                //
                try
                {
                    _communicator.addAdminFacet(this, "IceBox.ServiceManager");
                    _communicator.getAdmin();
                }
                catch (Ice.ObjectAdapterDeactivatedException)
                {
                    //
                    // Expected if the communicator has been shutdown.
                    //
                }

                //
                // Start request dispatching after we've started the services.
                //
                if (adapter != null)
                {
                    try
                    {
                        adapter.activate();
                    }
                    catch (Ice.ObjectAdapterDeactivatedException)
                    {
                        //
                        // Expected if the communicator has been shutdown.
                        //
                    }
                }

                _communicator.waitForShutdown();
            }
            catch (FailureException ex)
            {
                _logger.error(ex.ToString());
                return(1);
            }
            catch (Exception ex)
            {
                _logger.error("ServiceManager: caught exception:\n" + ex.ToString());
                return(1);
            }
            finally
            {
                //
                // Invoke stop() on the services.
                //
                stopAll();
            }

            return(0);
        }
Example #11
0
        private Reference create(Ice.Identity ident,
                                 string facet,
                                 Reference.Mode mode,
                                 bool secure,
                                 Ice.ProtocolVersion protocol,
                                 Ice.EncodingVersion encoding,
                                 EndpointI[] endpoints,
                                 string adapterId,
                                 string propertyPrefix)
        {
            DefaultsAndOverrides defaultsAndOverrides = instance_.defaultsAndOverrides();

            //
            // Default local proxy options.
            //
            LocatorInfo locatorInfo = null;

            if (_defaultLocator != null)
            {
                if (!((Ice.ObjectPrxHelperBase)_defaultLocator).reference__().getEncoding().Equals(encoding))
                {
                    locatorInfo = instance_.locatorManager().get(
                        (Ice.LocatorPrx)_defaultLocator.ice_encodingVersion(encoding));
                }
                else
                {
                    locatorInfo = instance_.locatorManager().get(_defaultLocator);
                }
            }
            RouterInfo routerInfo      = instance_.routerManager().get(_defaultRouter);
            bool       collocOptimized = defaultsAndOverrides.defaultCollocationOptimization;
            bool       cacheConnection = true;
            bool       preferSecure    = defaultsAndOverrides.defaultPreferSecure;

            Ice.EndpointSelectionType endpointSelection = defaultsAndOverrides.defaultEndpointSelection;
            int locatorCacheTimeout             = defaultsAndOverrides.defaultLocatorCacheTimeout;
            int invocationTimeout               = defaultsAndOverrides.defaultInvocationTimeout;
            Dictionary <string, string> context = null;

            //
            // Override the defaults with the proxy properties if a property prefix is defined.
            //
            if (propertyPrefix != null && propertyPrefix.Length > 0)
            {
                Ice.Properties properties = instance_.initializationData().properties;

                //
                // Warn about unknown properties.
                //
                if (properties.getPropertyAsIntWithDefault("Ice.Warn.UnknownProperties", 1) > 0)
                {
                    checkForUnknownProperties(propertyPrefix);
                }

                string property;

                property = propertyPrefix + ".Locator";
                Ice.LocatorPrx locator = Ice.LocatorPrxHelper.uncheckedCast(_communicator.propertyToProxy(property));
                if (locator != null)
                {
                    if (!((Ice.ObjectPrxHelperBase)locator).reference__().getEncoding().Equals(encoding))
                    {
                        locatorInfo = instance_.locatorManager().get(
                            (Ice.LocatorPrx)locator.ice_encodingVersion(encoding));
                    }
                    else
                    {
                        locatorInfo = instance_.locatorManager().get(locator);
                    }
                }

                property = propertyPrefix + ".Router";
                Ice.RouterPrx router = Ice.RouterPrxHelper.uncheckedCast(_communicator.propertyToProxy(property));
                if (router != null)
                {
                    if (propertyPrefix.EndsWith(".Router", StringComparison.Ordinal))
                    {
                        string s = "`" + property + "=" + properties.getProperty(property) +
                                   "': cannot set a router on a router; setting ignored";
                        instance_.initializationData().logger.warning(s);
                    }
                    else
                    {
                        routerInfo = instance_.routerManager().get(router);
                    }
                }

                property        = propertyPrefix + ".CollocationOptimized";
                collocOptimized = properties.getPropertyAsIntWithDefault(property, collocOptimized ? 1 : 0) > 0;

                property        = propertyPrefix + ".ConnectionCached";
                cacheConnection = properties.getPropertyAsIntWithDefault(property, cacheConnection ? 1 : 0) > 0;

                property     = propertyPrefix + ".PreferSecure";
                preferSecure = properties.getPropertyAsIntWithDefault(property, preferSecure ? 1 : 0) > 0;

                property = propertyPrefix + ".EndpointSelection";
                if (properties.getProperty(property).Length > 0)
                {
                    string type = properties.getProperty(property);
                    if (type.Equals("Random"))
                    {
                        endpointSelection = Ice.EndpointSelectionType.Random;
                    }
                    else if (type.Equals("Ordered"))
                    {
                        endpointSelection = Ice.EndpointSelectionType.Ordered;
                    }
                    else
                    {
                        throw new Ice.EndpointSelectionTypeParseException("illegal value `" + type +
                                                                          "'; expected `Random' or `Ordered'");
                    }
                }

                property = propertyPrefix + ".LocatorCacheTimeout";
                string val = properties.getProperty(property);
                if (val.Length > 0)
                {
                    locatorCacheTimeout = properties.getPropertyAsIntWithDefault(property, locatorCacheTimeout);
                    if (locatorCacheTimeout < -1)
                    {
                        locatorCacheTimeout = -1;

                        StringBuilder msg = new StringBuilder("invalid value for ");
                        msg.Append(property);
                        msg.Append(" `");
                        msg.Append(properties.getProperty(property));
                        msg.Append("': defaulting to -1");
                        instance_.initializationData().logger.warning(msg.ToString());
                    }
                }

                property = propertyPrefix + ".InvocationTimeout";
                val      = properties.getProperty(property);
                if (val.Length > 0)
                {
                    invocationTimeout = properties.getPropertyAsIntWithDefault(property, invocationTimeout);
                    if (invocationTimeout < 1 && invocationTimeout != -1)
                    {
                        invocationTimeout = -1;

                        StringBuilder msg = new StringBuilder("invalid value for ");
                        msg.Append(property);
                        msg.Append(" `");
                        msg.Append(properties.getProperty(property));
                        msg.Append("': defaulting to -1");
                        instance_.initializationData().logger.warning(msg.ToString());
                    }
                }

                property = propertyPrefix + ".Context.";
                Dictionary <string, string> contexts = properties.getPropertiesForPrefix(property);
                if (contexts.Count != 0)
                {
                    context = new Dictionary <string, string>();
                    foreach (KeyValuePair <string, string> e in contexts)
                    {
                        context.Add(e.Key.Substring(property.Length), e.Value);
                    }
                }
            }

            //
            // Create new reference
            //
            return(new RoutableReference(instance_,
                                         _communicator,
                                         ident,
                                         facet,
                                         mode,
                                         secure,
                                         protocol,
                                         encoding,
                                         endpoints,
                                         adapterId,
                                         locatorInfo,
                                         routerInfo,
                                         collocOptimized,
                                         cacheConnection,
                                         preferSecure,
                                         endpointSelection,
                                         locatorCacheTimeout,
                                         invocationTimeout,
                                         context));
        }
Example #12
0
        public static int Main(string[] args)
        {
            int           status = 0;
            List <string> argSeq = new List <string>();
            const string  prefix = "IceBox.Service.";

            Ice.InitializationData initData = new Ice.InitializationData();
            initData.properties = Ice.Util.createProperties();
            initData.properties.setProperty("Ice.Admin.DelayCreation", "1");

            try
            {
                using (var communicator = Ice.Util.initialize(ref args, initData))
                {
                    Console.CancelKeyPress += (sender, eventArgs) =>
                    {
                        eventArgs.Cancel = true;
                        communicator.shutdown();
                    };

                    Ice.Properties properties            = communicator.getProperties();
                    Dictionary <string, string> services = properties.getPropertiesForPrefix(prefix);

                    foreach (string arg in argSeq)
                    {
                        bool valid = false;
                        foreach (KeyValuePair <string, string> pair in services)
                        {
                            string name = pair.Key.Substring(prefix.Length);
                            if (arg.StartsWith("--" + name, StringComparison.CurrentCulture))
                            {
                                valid = true;
                                break;
                            }
                        }
                        if (!valid)
                        {
                            if (arg.Equals("-h") || arg.Equals("--help"))
                            {
                                usage();
                                status = 1;
                                break;
                            }
                            else if (arg.Equals("-v") || arg.Equals("--version"))
                            {
                                Console.Out.WriteLine(Ice.Util.stringVersion());
                                status = 1;
                                break;
                            }
                            else
                            {
                                Console.Error.WriteLine("IceBox.Server: unknown option `" + arg + "'");
                                usage();
                                status = 1;
                                break;
                            }
                        }
                    }

                    ServiceManagerI serviceManagerImpl = new ServiceManagerI(communicator, argSeq.ToArray());
                    status = serviceManagerImpl.run();
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                status = 1;
            }

            return(status);
        }
Example #13
0
        internal void initialize()
        {
            if (_initialized)
            {
                return;
            }

            const string prefix = "IceSSL.";

            Ice.Properties properties = communicator().getProperties();

            //
            // Check for a default directory. We look in this directory for
            // files mentioned in the configuration.
            //
            _defaultDir = properties.getProperty(prefix + "DefaultDir");

            string keySet = properties.getPropertyWithDefault(prefix + "KeySet", "DefaultKeySet");

            if (!keySet.Equals("DefaultKeySet") && !keySet.Equals("UserKeySet") && !keySet.Equals("MachineKeySet"))
            {
                _logger.warning("Invalid IceSSL.KeySet value `" + keySet + "' adjusted to `DefaultKeySet'");
                keySet = "DefaultKeySet";
            }

            X509KeyStorageFlags keyStorageFlags = X509KeyStorageFlags.DefaultKeySet;

            if (keySet.Equals("UserKeySet"))
            {
                keyStorageFlags = X509KeyStorageFlags.UserKeySet;
            }
            else if (keySet.Equals("MachineKeySet"))
            {
                keyStorageFlags = X509KeyStorageFlags.MachineKeySet;
            }

            if (properties.getPropertyAsIntWithDefault(prefix + "PersistKeySet", 0) > 0)
            {
                keyStorageFlags |= X509KeyStorageFlags.PersistKeySet;
            }

            //
            // Process IceSSL.ImportCert.* properties.
            //
            Dictionary <string, string> certs = properties.getPropertiesForPrefix(prefix + "ImportCert.");

            foreach (KeyValuePair <string, string> entry in certs)
            {
                string name = entry.Key;
                string val  = entry.Value;
                if (val.Length > 0)
                {
                    importCertificate(name, val, keyStorageFlags);
                }
            }

            //
            // Select protocols.
            //
            _protocols = parseProtocols(prefix + "Protocols");

            //
            // CheckCertName determines whether we compare the name in a peer's
            // certificate against its hostname.
            //
            _checkCertName = properties.getPropertyAsIntWithDefault(prefix + "CheckCertName", 0) > 0;

            //
            // 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 = properties.getPropertyAsIntWithDefault(prefix + "VerifyDepthMax", 2);

            //
            // CheckCRL determines whether the certificate revocation list is checked, and how strictly.
            //
            _checkCRL = properties.getPropertyAsIntWithDefault(prefix + "CheckCRL", 0);

            //
            // Check for a certificate verifier.
            //
            string certVerifierClass = properties.getProperty(prefix + "CertVerifier");

            if (certVerifierClass.Length > 0)
            {
                if (_verifier != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: certificate verifier already installed";
                    throw e;
                }

                Type cls = _facade.findType(certVerifierClass);
                if (cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load certificate verifier class " + certVerifierClass;
                    throw e;
                }

                try
                {
                    _verifier = (CertificateVerifier)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch (Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }

                if (_verifier == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }
            }

            //
            // Check for a password callback.
            //
            string passwordCallbackClass = properties.getProperty(prefix + "PasswordCallback");

            if (passwordCallbackClass.Length > 0)
            {
                if (_passwordCallback != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: password callback already installed";
                    throw e;
                }

                Type cls = _facade.findType(passwordCallbackClass);
                if (cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                try
                {
                    _passwordCallback = (PasswordCallback)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch (Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                if (_passwordCallback == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }
            }

            //
            // 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    = properties.getProperty(prefix + "CertFile");
                string passwordStr = properties.getProperty(prefix + "Password");

                if (certFile.Length > 0)
                {
                    if (!checkPath(ref certFile))
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: certificate file not found: " + certFile;
                        throw e;
                    }

                    SecureString password = null;
                    if (passwordStr.Length > 0)
                    {
                        password = createSecureString(passwordStr);
                    }
                    else if (_passwordCallback != null)
                    {
                        password = _passwordCallback.getPassword(certFile);
                    }

                    try
                    {
                        X509Certificate2 cert;
                        if (password != null)
                        {
                            cert = new X509Certificate2(certFile, password, keyStorageFlags);
                        }
                        else
                        {
                            cert = new X509Certificate2(certFile, "", keyStorageFlags);
                        }
                        _certs.Add(cert);
                    }
                    catch (CryptographicException ex)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                        e.reason = "IceSSL: error while attempting to load certificate from " + certFile;
                        throw e;
                    }
                }

                //
                // If IceSSL.FindCert.* properties are defined, add the selected certificates
                // to the collection.
                //
                // TODO: tracing?
                const string findPrefix = prefix + "FindCert.";
                Dictionary <string, string> certProps = properties.getPropertiesForPrefix(findPrefix);
                if (certProps.Count > 0)
                {
                    foreach (KeyValuePair <string, string> entry in certProps)
                    {
                        string name = entry.Key;
                        string val  = entry.Value;
                        if (val.Length > 0)
                        {
                            string storeSpec = name.Substring(findPrefix.Length);
                            X509Certificate2Collection coll = findCertificates(name, storeSpec, val);
                            _certs.AddRange(coll);
                        }
                    }
                    if (_certs.Count == 0)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: no certificates found";
                        throw e;
                    }
                }
            }

            _initialized = true;
        }