Esempio n. 1
0
        private Ice.Properties createServiceProperties(string service)
        {
            Ice.Properties properties;
            Ice.Properties communicatorProperties = _communicator.getProperties();
            if (communicatorProperties.getPropertyAsInt("IceBox.InheritProperties") > 0)
            {
                properties = communicatorProperties.ice_clone_();
                // Inherit all except Ice.Admin.xxx properties
                foreach (string p in properties.getPropertiesForPrefix("Ice.Admin.").Keys)
                {
                    properties.setProperty(p, "");
                }
            }
            else
            {
                properties = Ice.Util.createProperties();
            }

            string programName = communicatorProperties.getProperty("Ice.ProgramName");

            if (programName.Length == 0)
            {
                properties.setProperty("Ice.ProgramName", service);
            }
            else
            {
                properties.setProperty("Ice.ProgramName", programName + "-" + service);
            }
            return(properties);
        }
Esempio n. 2
0
 internal LoggerAdminI(Ice.Properties props, LoggerAdminLoggerI logger)
 {
     _maxLogCount   = props.getPropertyAsIntWithDefault("Ice.Admin.Logger.KeepLogs", 100);
     _maxTraceCount = props.getPropertyAsIntWithDefault("Ice.Admin.Logger.KeepTraces", 100);
     _traceLevel    = props.getPropertyAsInt("Ice.Trace.Admin.Logger");
     _logger        = logger;
 }
Esempio n. 3
0
        public ServiceManagerI(Ice.Communicator communicator, string[] args)
        {
            _communicator = communicator;
            _logger       = _communicator.getLogger();

            Ice.Properties props = _communicator.getProperties();

            if (props.getProperty("Ice.Admin.Enabled").Length == 0)
            {
                _adminEnabled = props.getProperty("Ice.Admin.Endpoints").Length > 0;
            }
            else
            {
                _adminEnabled = props.getPropertyAsInt("Ice.Admin.Enabled") > 0;
            }

            if (_adminEnabled)
            {
                string[] facetFilter = props.getPropertyAsList("Ice.Admin.Facets");
                if (facetFilter.Length > 0)
                {
                    _adminFacetFilter = new HashSet <string>(facetFilter);
                }
                else
                {
                    _adminFacetFilter = new HashSet <string>();
                }
            }

            _argv = args;
            _traceServiceObserver = _communicator.getProperties().getPropertyAsInt("IceBox.Trace.ServiceObserver");
        }
Esempio n. 4
0
        LocatorI(string name, LookupPrx lookup, Ice.Properties properties, string instanceName,
                 Ice.LocatorPrx voidLocator)
        {
            _lookup            = lookup;
            _timeout           = properties.getPropertyAsIntWithDefault(name + ".Timeout", 300);
            _retryCount        = properties.getPropertyAsIntWithDefault(name + ".RetryCount", 3);
            _retryDelay        = properties.getPropertyAsIntWithDefault(name + ".RetryDelay", 2000);
            _timer             = IceInternal.Util.getInstance(lookup.ice_getCommunicator()).timer();
            _traceLevel        = properties.getPropertyAsInt(name + ".Trace.Lookup");
            _instanceName      = instanceName;
            _warned            = false;
            _locator           = lookup.ice_getCommunicator().getDefaultLocator();
            _voidLocator       = voidLocator;
            _pendingRetryCount = 0;
            _failureCount      = 0;
            _warnOnce          = true;

            //
            // Create one lookup proxy per endpoint from the given proxy. We want to send a multicast
            // datagram on each endpoint.
            //
            var single = new Ice.Endpoint[1];

            foreach (var endpt in lookup.ice_getEndpoints())
            {
                single[0] = endpt;
                _lookups[(LookupPrx)lookup.ice_endpoints(single)] = null;
            }
            Debug.Assert(_lookups.Count > 0);
        }
Esempio n. 5
0
        private Ice.Properties createServiceProperties(String service)
        {
            Ice.Properties properties;
            Ice.Properties communicatorProperties = _communicator.getProperties();
            if (communicatorProperties.getPropertyAsInt("IceBox.InheritProperties") > 0)
            {
                properties = communicatorProperties.ice_clone_();
                properties.setProperty("Ice.Admin.Endpoints", ""); // Inherit all except Ice.Admin.Endpoints!
            }
            else
            {
                properties = Ice.Util.createProperties();
            }

            String programName = communicatorProperties.getProperty("Ice.ProgramName");

            if (programName.Length == 0)
            {
                properties.setProperty("Ice.ProgramName", service);
            }
            else
            {
                properties.setProperty("Ice.ProgramName", programName + "-" + service);
            }
            return(properties);
        }
Esempio n. 6
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) &&
                IceUtilInternal.Collections.DictionaryEquals(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);
        }
Esempio n. 7
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;
            }
        }
Esempio n. 8
0
        internal TraceLevels(Ice.Properties properties)
        {
            networkCat    = "Network";
            protocolCat   = "Protocol";
            retryCat      = "Retry";
            locationCat   = "Locator";
            slicingCat    = "Slicing";
            threadPoolCat = "ThreadPool";

            string keyBase = "Ice.Trace.";

            network    = properties.getPropertyAsInt(keyBase + networkCat);
            protocol   = properties.getPropertyAsInt(keyBase + protocolCat);
            retry      = properties.getPropertyAsInt(keyBase + retryCat);
            location   = properties.getPropertyAsInt(keyBase + locationCat);
            slicing    = properties.getPropertyAsInt(keyBase + slicingCat);
            threadPool = properties.getPropertyAsInt(keyBase + threadPoolCat);
        }
Esempio n. 9
0
 internal LocatorManager(Ice.Properties properties)
 {
     _table         = new Dictionary <Ice.LocatorPrx, LocatorInfo>();
     _locatorTables = new Dictionary <LocatorKey, LocatorTable>();
     _background    = properties.getPropertyAsInt("Ice.BackgroundLocatorCacheUpdates") > 0;
 }
Esempio n. 10
0
        public void initialize()
        {
            Ice.Properties properties = _communicator.getProperties();

            bool   ipv4       = properties.getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0;
            bool   preferIPv6 = properties.getPropertyAsInt("Ice.PreferIPv6Address") > 0;
            string address;

            if (ipv4 && !preferIPv6)
            {
                address = properties.getPropertyWithDefault("IceDiscovery.Address", "239.255.0.1");
            }
            else
            {
                address = properties.getPropertyWithDefault("IceDiscovery.Address", "ff15::1");
            }
            int    port = properties.getPropertyAsIntWithDefault("IceDiscovery.Port", 4061);
            string intf = properties.getProperty("IceDiscovery.Interface");

            if (properties.getProperty("IceDiscovery.Multicast.Endpoints").Length == 0)
            {
                StringBuilder s = new StringBuilder();
                s.Append("udp -h \"").Append(address).Append("\" -p ").Append(port);
                if (intf.Length != 0)
                {
                    s.Append(" --interface \"").Append(intf).Append("\"");
                }
                properties.setProperty("IceDiscovery.Multicast.Endpoints", s.ToString());
            }

            string lookupEndpoints = properties.getProperty("IceDiscovery.Lookup");

            if (lookupEndpoints.Length == 0)
            {
                int protocol   = ipv4 && !preferIPv6 ? IceInternal.Network.EnableIPv4 : IceInternal.Network.EnableIPv6;
                var interfaces = IceInternal.Network.getInterfacesForMulticast(intf, protocol);
                foreach (string p in interfaces)
                {
                    if (p != interfaces[0])
                    {
                        lookupEndpoints += ":";
                    }
                    lookupEndpoints += "udp -h \"" + address + "\" -p " + port + " --interface \"" + p + "\"";
                }
            }

            if (properties.getProperty("IceDiscovery.Reply.Endpoints").Length == 0)
            {
                properties.setProperty("IceDiscovery.Reply.Endpoints",
                                       "udp -h " + (intf.Length == 0 ? "*" : "\"" + intf + "\""));
            }

            if (properties.getProperty("IceDiscovery.Locator.Endpoints").Length == 0)
            {
                properties.setProperty("IceDiscovery.Locator.AdapterId", Guid.NewGuid().ToString());
            }

            _multicastAdapter = _communicator.createObjectAdapter("IceDiscovery.Multicast");
            _replyAdapter     = _communicator.createObjectAdapter("IceDiscovery.Reply");
            _locatorAdapter   = _communicator.createObjectAdapter("IceDiscovery.Locator");

            //
            // Setup locatory registry.
            //
            LocatorRegistryI locatorRegistry = new LocatorRegistryI(_communicator);

            Ice.LocatorRegistryPrx locatorRegistryPrx = Ice.LocatorRegistryPrxHelper.uncheckedCast(
                _locatorAdapter.addWithUUID(locatorRegistry));

            Ice.ObjectPrx lookupPrx = _communicator.stringToProxy("IceDiscovery/Lookup -d:" + lookupEndpoints);
            // No colloc optimization or router for the multicast proxy!
            lookupPrx = lookupPrx.ice_collocationOptimized(false).ice_router(null);

            //
            // Add lookup and lookup reply Ice objects
            //
            LookupI lookup = new LookupI(locatorRegistry, LookupPrxHelper.uncheckedCast(lookupPrx), properties);

            _multicastAdapter.add(lookup, Ice.Util.stringToIdentity("IceDiscovery/Lookup"));

            _replyAdapter.addDefaultServant(new LookupReplyI(lookup), "");
            Ice.Identity id = new Ice.Identity("dummy", "");
            lookup.setLookupReply(LookupReplyPrxHelper.uncheckedCast(_replyAdapter.createProxy(id).ice_datagram()));

            //
            // Setup locator on the communicator.
            //
            Ice.ObjectPrx loc;
            loc = _locatorAdapter.addWithUUID(
                new LocatorI(lookup, Ice.LocatorRegistryPrxHelper.uncheckedCast(locatorRegistryPrx)));
            _defaultLocator = _communicator.getDefaultLocator();
            _locator        = Ice.LocatorPrxHelper.uncheckedCast(loc);
            _communicator.setDefaultLocator(_locator);

            _multicastAdapter.activate();
            _replyAdapter.activate();
            _locatorAdapter.activate();
        }
Esempio n. 11
0
            public override void run(string[] args)
            {
                Ice.Properties properties = createTestProperties(ref args);
                properties.setProperty("Ice.Warn.Connections", "0");
                properties.setProperty("Ice.UDP.RcvSize", "16384");
                if (IceInternal.AssemblyUtil.isMacOS && properties.getPropertyAsInt("Ice.IPv6") > 0)
                {
                    // Disable dual mode sockets on macOS, see https://github.com/dotnet/corefx/issues/31182
                    properties.setProperty("Ice.IPv4", "0");
                }

                using (var communicator = initialize(properties))
                {
                    int num = 0;
                    try
                    {
                        num = args.Length == 1 ? Int32.Parse(args[0]) : 0;
                    }
                    catch (FormatException)
                    {
                    }

                    communicator.Properties.setProperty("ControlAdapter.Endpoints", getTestEndpoint(num, "tcp"));
                    Ice.ObjectAdapter adapter = communicator.createObjectAdapter("ControlAdapter");
                    adapter.Add(new TestIntfI(), "control");
                    adapter.Activate();
                    serverReady();
                    if (num == 0)
                    {
                        communicator.Properties.setProperty("TestAdapter.Endpoints", getTestEndpoint(num, "udp"));
                        Ice.ObjectAdapter adapter2 = communicator.createObjectAdapter("TestAdapter");
                        adapter2.Add(new TestIntfI(), "test");
                        adapter2.Activate();
                    }

                    StringBuilder endpoint = new StringBuilder();
                    //
                    // Use loopback to prevent other machines to answer.
                    //
                    if (properties.getProperty("Ice.IPv6").Equals("1"))
                    {
                        endpoint.Append("udp -h \"ff15::1:1\"");
                        if (IceInternal.AssemblyUtil.isWindows || IceInternal.AssemblyUtil.isMacOS)
                        {
                            endpoint.Append(" --interface \"::1\"");
                        }
                    }
                    else
                    {
                        endpoint.Append("udp -h 239.255.1.1");
                        if (IceInternal.AssemblyUtil.isWindows || IceInternal.AssemblyUtil.isMacOS)
                        {
                            endpoint.Append(" --interface 127.0.0.1");
                        }
                    }
                    endpoint.Append(" -p ");
                    endpoint.Append(getTestPort(properties, 10));
                    communicator.Properties.setProperty("McastTestAdapter.Endpoints", endpoint.ToString());
                    Ice.ObjectAdapter mcastAdapter = communicator.createObjectAdapter("McastTestAdapter");
                    mcastAdapter.Add(new TestIntfI(), "test");
                    mcastAdapter.Activate();

                    communicator.waitForShutdown();
                }
            }
Esempio n. 12
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);
        }
Esempio n. 13
0
        initialize()
        {
            Ice.Properties properties = _communicator.getProperties();

            bool   ipv4       = properties.getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0;
            bool   preferIPv6 = properties.getPropertyAsInt("Ice.PreferIPv6Address") > 0;
            string address;

            if (ipv4 && !preferIPv6)
            {
                address = properties.getPropertyWithDefault(_name + ".Address", "239.255.0.1");
            }
            else
            {
                address = properties.getPropertyWithDefault(_name + ".Address", "ff15::1");
            }
            int    port = properties.getPropertyAsIntWithDefault(_name + ".Port", 4061);
            string intf = properties.getProperty(_name + ".Interface");

            string lookupEndpoints = properties.getProperty(_name + ".Lookup");

            if (lookupEndpoints.Length == 0)
            {
                int protocol   = ipv4 && !preferIPv6 ? IceInternal.Network.EnableIPv4 : IceInternal.Network.EnableIPv6;
                var interfaces = IceInternal.Network.getInterfacesForMulticast(intf, protocol);
                foreach (string p in interfaces)
                {
                    if (p != interfaces[0])
                    {
                        lookupEndpoints += ":";
                    }
                    lookupEndpoints += "udp -h \"" + address + "\" -p " + port + " --interface \"" + p + "\"";
                }
            }

            if (properties.getProperty(_name + ".Reply.Endpoints").Length == 0)
            {
                properties.setProperty(_name + ".Reply.Endpoints",
                                       "udp -h " + (intf.Length == 0 ? "*" : "\"" + intf + "\""));
            }

            if (properties.getProperty(_name + ".Locator.Endpoints").Length == 0)
            {
                properties.setProperty(_name + ".Locator.AdapterId", Guid.NewGuid().ToString());
            }

            _replyAdapter   = _communicator.createObjectAdapter(_name + ".Reply");
            _locatorAdapter = _communicator.createObjectAdapter(_name + ".Locator");

            // We don't want those adapters to be registered with the locator so clear their locator.
            _replyAdapter.setLocator(null);
            _locatorAdapter.setLocator(null);

            Ice.ObjectPrx lookupPrx = _communicator.stringToProxy("IceLocatorDiscovery/Lookup -d:" + lookupEndpoints);
            // No colloc optimization or router for the multicast proxy!
            lookupPrx = lookupPrx.ice_collocationOptimized(false).ice_router(null);

            Ice.LocatorPrx voidLo = Ice.LocatorPrxHelper.uncheckedCast(_locatorAdapter.addWithUUID(new VoidLocatorI()));

            string instanceName = properties.getProperty(_name + ".InstanceName");

            Ice.Identity id = new Ice.Identity();
            id.name     = "Locator";
            id.category = instanceName.Length > 0 ? instanceName : Guid.NewGuid().ToString();

            _defaultLocator = _communicator.getDefaultLocator();
            _locator        = new LocatorI(_name, LookupPrxHelper.uncheckedCast(lookupPrx), properties, instanceName, voidLo);
            _locatorPrx     = Ice.LocatorPrxHelper.uncheckedCast(_locatorAdapter.addWithUUID(_locator));
            _communicator.setDefaultLocator(_locatorPrx);

            Ice.ObjectPrx lookupReply = _replyAdapter.addWithUUID(new LookupReplyI(_locator)).ice_datagram();
            _locator.setLookupReply(LookupReplyPrxHelper.uncheckedCast(lookupReply));

            _replyAdapter.activate();
            _locatorAdapter.activate();
        }
Esempio n. 14
0
        initialize()
        {
            Ice.Properties properties = _communicator.getProperties();

            bool   ipv4       = properties.getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0;
            bool   preferIPv6 = properties.getPropertyAsInt("Ice.PreferIPv6Address") > 0;
            string address;

            if (ipv4 && !preferIPv6)
            {
                address = properties.getPropertyWithDefault("IceLocatorDiscovery.Address", "239.255.0.1");
            }
            else
            {
                address = properties.getPropertyWithDefault("IceLocatorDiscovery.Address", "ff15::1");
            }
            int    port = properties.getPropertyAsIntWithDefault("IceLocatorDiscovery.Port", 4061);
            string intf = properties.getProperty("IceLocatorDiscovery.Interface");

            if (properties.getProperty("IceLocatorDiscovery.Reply.Endpoints").Length == 0)
            {
                System.Text.StringBuilder s = new System.Text.StringBuilder();
                s.Append("udp");
                if (intf.Length > 0)
                {
                    s.Append(" -h \"");
                    s.Append(intf);
                    s.Append("\"");
                }
                properties.setProperty("IceLocatorDiscovery.Reply.Endpoints", s.ToString());
            }
            if (properties.getProperty("IceLocatorDiscovery.Locator.Endpoints").Length == 0)
            {
                properties.setProperty("IceLocatorDiscovery.Locator.AdapterId", Guid.NewGuid().ToString());
            }

            _replyAdapter   = _communicator.createObjectAdapter("IceLocatorDiscovery.Reply");
            _locatorAdapter = _communicator.createObjectAdapter("IceLocatorDiscovery.Locator");

            // We don't want those adapters to be registered with the locator so clear their locator.
            _replyAdapter.setLocator(null);
            _locatorAdapter.setLocator(null);

            string lookupEndpoints = properties.getProperty("IceLocatorDiscovery.Lookup");

            if (lookupEndpoints.Length == 0)
            {
                System.Text.StringBuilder s = new System.Text.StringBuilder();
                s.Append("udp -h \"");
                s.Append(address);
                s.Append("\" -p ");
                s.Append(port);
                if (intf.Length > 0)
                {
                    s.Append(" --interface \"");
                    s.Append(intf);
                    s.Append("\"");
                }
                lookupEndpoints = s.ToString();
            }

            Ice.ObjectPrx lookupPrx = _communicator.stringToProxy("IceLocatorDiscovery/Lookup -d:" + lookupEndpoints);
            lookupPrx = lookupPrx.ice_collocationOptimized(false); // No colloc optimization for the multicast proxy!
            try
            {
                lookupPrx.ice_getConnection(); // Ensure we can establish a connection to the multicast proxy
            }
            catch (Ice.LocalException ex)
            {
                System.Text.StringBuilder s = new System.Text.StringBuilder();
                s.Append("IceLocatorDiscovery is unable to establish a multicast connection:\n");
                s.Append("proxy = ");
                s.Append(lookupPrx.ToString());
                s.Append("\n");
                s.Append(ex);
                throw new Ice.PluginInitializationException(s.ToString());
            }

            Ice.LocatorPrx voidLo = Ice.LocatorPrxHelper.uncheckedCast(_locatorAdapter.addWithUUID(new VoidLocatorI()));

            string instanceName = properties.getProperty("IceLocatorDiscovery.InstanceName");

            Ice.Identity id = new Ice.Identity();
            id.name     = "Locator";
            id.category = instanceName.Length > 0 ? instanceName : Guid.NewGuid().ToString();

            LocatorI locator = new LocatorI(LookupPrxHelper.uncheckedCast(lookupPrx), properties, instanceName, voidLo);

            _communicator.setDefaultLocator(Ice.LocatorPrxHelper.uncheckedCast(_locatorAdapter.addWithUUID(locator)));

            Ice.ObjectPrx lookupReply = _replyAdapter.addWithUUID(new LookupReplyI(locator)).ice_datagram();
            locator.setLookupReply(LookupReplyPrxHelper.uncheckedCast(lookupReply));

            _replyAdapter.activate();
            _locatorAdapter.activate();
        }
Esempio n. 15
0
        public void initialize()
        {
            Ice.Properties properties = _communicator.getProperties();

            bool   ipv4       = properties.getPropertyAsIntWithDefault("Ice.IPv4", 1) > 0;
            bool   preferIPv6 = properties.getPropertyAsInt("Ice.PreferIPv6Address") > 0;
            string address;

            if (ipv4 && !preferIPv6)
            {
                address = properties.getPropertyWithDefault("IceDiscovery.Address", "239.255.0.1");
            }
            else
            {
                address = properties.getPropertyWithDefault("IceDiscovery.Address", "ff15::1");
            }
            int    port = properties.getPropertyAsIntWithDefault("IceDiscovery.Port", 4061);
            string intf = properties.getProperty("IceDiscovery.Interface");

            if (properties.getProperty("IceDiscovery.Multicast.Endpoints").Length == 0)
            {
                StringBuilder s = new StringBuilder();
                s.Append("udp -h \"").Append(address).Append("\" -p ").Append(port);
                if (intf.Length != 0)
                {
                    s.Append(" --interface \"").Append(intf).Append("\"");
                }
                properties.setProperty("IceDiscovery.Multicast.Endpoints", s.ToString());
            }
            if (properties.getProperty("IceDiscovery.Reply.Endpoints").Length == 0)
            {
                StringBuilder s = new StringBuilder();
                s.Append("udp");
                if (intf.Length != 0)
                {
                    s.Append(" -h \"").Append(intf).Append("\"");
                }
                properties.setProperty("IceDiscovery.Reply.Endpoints", s.ToString());
            }
            if (properties.getProperty("IceDiscovery.Locator.Endpoints").Length == 0)
            {
                properties.setProperty("IceDiscovery.Locator.AdapterId", Guid.NewGuid().ToString());
            }

            _multicastAdapter = _communicator.createObjectAdapter("IceDiscovery.Multicast");
            _replyAdapter     = _communicator.createObjectAdapter("IceDiscovery.Reply");
            _locatorAdapter   = _communicator.createObjectAdapter("IceDiscovery.Locator");

            //
            // Setup locatory registry.
            //
            LocatorRegistryI locatorRegistry = new LocatorRegistryI(_communicator);

            Ice.LocatorRegistryPrx locatorRegistryPrx = Ice.LocatorRegistryPrxHelper.uncheckedCast(
                _locatorAdapter.addWithUUID(locatorRegistry));

            string lookupEndpoints = properties.getProperty("IceDiscovery.Lookup");

            if (lookupEndpoints.Length == 0)
            {
                lookupEndpoints = "udp -h \"" + address + "\" -p " + port;
                if (intf.Length > 0)
                {
                    lookupEndpoints += " --interface \"" + intf + "\"";
                }
            }

            Ice.ObjectPrx lookupPrx = _communicator.stringToProxy("IceDiscovery/Lookup -d:" + lookupEndpoints);
            lookupPrx = lookupPrx.ice_collocationOptimized(false);
            try
            {
                lookupPrx.ice_getConnection();
            }
            catch (Ice.LocalException ex)
            {
                StringBuilder b = new StringBuilder();
                b.Append("IceDiscovery is unable to establish a multicast connection:\n");
                b.Append("proxy = ");
                b.Append(lookupPrx.ToString());
                b.Append('\n');
                b.Append(ex.ToString());
                throw new Ice.PluginInitializationException(b.ToString());
            }

            //
            // Add lookup and lookup reply Ice objects
            //
            LookupI lookup = new LookupI(locatorRegistry, LookupPrxHelper.uncheckedCast(lookupPrx), properties);

            _multicastAdapter.add(lookup, Ice.Util.stringToIdentity("IceDiscovery/Lookup"));

            Ice.ObjectPrx lookupReply = _replyAdapter.addWithUUID(new LookupReplyI(lookup)).ice_datagram();
            lookup.setLookupReply(LookupReplyPrxHelper.uncheckedCast(lookupReply));

            //
            // Setup locator on the communicator.
            //
            Ice.ObjectPrx loc;
            loc = _locatorAdapter.addWithUUID(
                new LocatorI(lookup, Ice.LocatorRegistryPrxHelper.uncheckedCast(locatorRegistryPrx)));
            _communicator.setDefaultLocator(Ice.LocatorPrxHelper.uncheckedCast(loc));

            _multicastAdapter.activate();
            _replyAdapter.activate();
            _locatorAdapter.activate();
        }
Esempio n. 16
0
        public ThreadPool(Instance instance, string prefix, int timeout)
        {
            Ice.Properties properties = instance.initializationData().properties;

            _instance       = instance;
            _dispatcher     = instance.initializationData().dispatcher;
            _destroyed      = false;
            _prefix         = prefix;
            _threadIndex    = 0;
            _inUse          = 0;
            _serialize      = properties.getPropertyAsInt(_prefix + ".Serialize") > 0;
            _serverIdleTime = timeout;

            string programName = properties.getProperty("Ice.ProgramName");

            if (programName.Length > 0)
            {
                _threadPrefix = programName + "-" + _prefix;
            }
            else
            {
                _threadPrefix = _prefix;
            }

            //
            // We use just one thread as the default. This is the fastest
            // possible setting, still allows one level of nesting, and
            // doesn't require to make the servants thread safe.
            //
            int size = properties.getPropertyAsIntWithDefault(_prefix + ".Size", 1);

            if (size < 1)
            {
                string s = _prefix + ".Size < 1; Size adjusted to 1";
                _instance.initializationData().logger.warning(s);
                size = 1;
            }

            int sizeMax = properties.getPropertyAsIntWithDefault(_prefix + ".SizeMax", size);

            if (sizeMax < size)
            {
                string s = _prefix + ".SizeMax < " + _prefix + ".Size; SizeMax adjusted to Size (" + size + ")";
                _instance.initializationData().logger.warning(s);
                sizeMax = size;
            }

            int sizeWarn = properties.getPropertyAsInt(_prefix + ".SizeWarn");

            if (sizeWarn != 0 && sizeWarn < size)
            {
                string s = _prefix + ".SizeWarn < " + _prefix + ".Size; adjusted SizeWarn to Size (" + size + ")";
                _instance.initializationData().logger.warning(s);
                sizeWarn = size;
            }
            else if (sizeWarn > sizeMax)
            {
                string s = _prefix + ".SizeWarn > " + _prefix + ".SizeMax; adjusted SizeWarn to SizeMax ("
                           + sizeMax + ")";
                _instance.initializationData().logger.warning(s);
                sizeWarn = sizeMax;
            }

            int threadIdleTime = properties.getPropertyAsIntWithDefault(_prefix + ".ThreadIdleTime", 60);

            if (threadIdleTime < 0)
            {
                string s = _prefix + ".ThreadIdleTime < 0; ThreadIdleTime adjusted to 0";
                _instance.initializationData().logger.warning(s);
                threadIdleTime = 0;
            }

            _size           = size;
            _sizeMax        = sizeMax;
            _sizeWarn       = sizeWarn;
            _threadIdleTime = threadIdleTime;

            int stackSize = properties.getPropertyAsInt(_prefix + ".StackSize");

            if (stackSize < 0)
            {
                string s = _prefix + ".StackSize < 0; Size adjusted to OS default";
                _instance.initializationData().logger.warning(s);
                stackSize = 0;
            }
            _stackSize = stackSize;

            _priority = properties.getProperty(_prefix + ".ThreadPriority").Length > 0 ?
                        Util.stringToThreadPriority(properties.getProperty(_prefix + ".ThreadPriority")) :
                        Util.stringToThreadPriority(properties.getProperty("Ice.ThreadPriority"));

            if (_instance.traceLevels().threadPool >= 1)
            {
                string s = "creating " + _prefix + ": Size = " + _size + ", SizeMax = " + _sizeMax + ", SizeWarn = " +
                           _sizeWarn;
                _instance.initializationData().logger.trace(_instance.traceLevels().threadPoolCat, s);
            }

            _workItems = new Queue <ThreadPoolWorkItem>();

            try
            {
                _threads = new List <WorkerThread>();
                for (int i = 0; i < _size; ++i)
                {
                    WorkerThread thread = new WorkerThread(this, _threadPrefix + "-" + _threadIndex++);
                    thread.start(_priority);
                    _threads.Add(thread);
                }
            }
            catch (System.Exception ex)
            {
                string s = "cannot create thread for `" + _prefix + "':\n" + ex;
                _instance.initializationData().logger.error(s);

                destroy();
                joinWithAllThreads();
                throw;
            }
        }
Esempio n. 17
0
        internal DefaultsAndOverrides(Ice.Properties properties, Ice.Logger logger)
        {
            string val;

            defaultProtocol = properties.getPropertyWithDefault("Ice.Default.Protocol", "tcp");

            val = properties.getProperty("Ice.Default.Host");
            if (val.Length != 0)
            {
                defaultHost = val;
            }
            else
            {
                defaultHost = null;
            }

            val = properties.getProperty("Ice.Default.SourceAddress");
            if (val.Length > 0)
            {
                defaultSourceAddress = Network.getNumericAddress(val);
                if (defaultSourceAddress == null)
                {
                    throw new Ice.InitializationException("invalid IP address set for Ice.Default.SourceAddress: `" +
                                                          val + "'");
                }
            }
            else
            {
                defaultSourceAddress = null;
            }

            val = properties.getProperty("Ice.Override.Timeout");
            if (val.Length > 0)
            {
                overrideTimeout      = true;
                overrideTimeoutValue = properties.getPropertyAsInt("Ice.Override.Timeout");
                if (overrideTimeoutValue < 1 && overrideTimeoutValue != -1)
                {
                    overrideTimeoutValue = -1;
                    StringBuilder msg = new StringBuilder("invalid value for Ice.Override.Timeout `");
                    msg.Append(properties.getProperty("Ice.Override.Timeout"));
                    msg.Append("': defaulting to -1");
                    logger.warning(msg.ToString());
                }
            }
            else
            {
                overrideTimeout      = false;
                overrideTimeoutValue = -1;
            }

            val = properties.getProperty("Ice.Override.ConnectTimeout");
            if (val.Length > 0)
            {
                overrideConnectTimeout      = true;
                overrideConnectTimeoutValue = properties.getPropertyAsInt("Ice.Override.ConnectTimeout");
                if (overrideConnectTimeoutValue < 1 && overrideConnectTimeoutValue != -1)
                {
                    overrideConnectTimeoutValue = -1;
                    StringBuilder msg = new StringBuilder("invalid value for Ice.Override.ConnectTimeout `");
                    msg.Append(properties.getProperty("Ice.Override.ConnectTimeout"));
                    msg.Append("': defaulting to -1");
                    logger.warning(msg.ToString());
                }
            }
            else
            {
                overrideConnectTimeout      = false;
                overrideConnectTimeoutValue = -1;
            }

            val = properties.getProperty("Ice.Override.CloseTimeout");
            if (val.Length > 0)
            {
                overrideCloseTimeout      = true;
                overrideCloseTimeoutValue = properties.getPropertyAsInt("Ice.Override.CloseTimeout");
                if (overrideCloseTimeoutValue < 1 && overrideCloseTimeoutValue != -1)
                {
                    overrideCloseTimeoutValue = -1;
                    StringBuilder msg = new StringBuilder("invalid value for Ice.Override.CloseTimeout `");
                    msg.Append(properties.getProperty("Ice.Override.CloseTimeout"));
                    msg.Append("': defaulting to -1");
                    logger.warning(msg.ToString());
                }
            }
            else
            {
                overrideCloseTimeout      = false;
                overrideCloseTimeoutValue = -1;
            }

            val = properties.getProperty("Ice.Override.Compress");
            if (val.Length > 0)
            {
                overrideCompress      = true;
                overrideCompressValue = properties.getPropertyAsInt("Ice.Override.Compress") > 0;
                if (!BZip2.supported() && overrideCompressValue)
                {
                    string lib = AssemblyUtil.isWindows ? "bzip2.dll" : "libbz2.so.1";
                    Console.Error.WriteLine("warning: " + lib + " not found, Ice.Override.Compress ignored.");
                    overrideCompressValue = false;
                }
            }
            else
            {
                overrideCompress      = !BZip2.supported();
                overrideCompressValue = false;
            }

            val = properties.getProperty("Ice.Override.Secure");
            if (val.Length > 0)
            {
                overrideSecure      = true;
                overrideSecureValue = properties.getPropertyAsInt("Ice.Override.Secure") > 0;
            }
            else
            {
                overrideSecure      = false;
                overrideSecureValue = false;
            }

            defaultCollocationOptimization =
                properties.getPropertyAsIntWithDefault("Ice.Default.CollocationOptimized", 1) > 0;

            val = properties.getPropertyWithDefault("Ice.Default.EndpointSelection", "Random");
            if (val.Equals("Random"))
            {
                defaultEndpointSelection = Ice.EndpointSelectionType.Random;
            }
            else if (val.Equals("Ordered"))
            {
                defaultEndpointSelection = Ice.EndpointSelectionType.Ordered;
            }
            else
            {
                Ice.EndpointSelectionTypeParseException ex = new Ice.EndpointSelectionTypeParseException();
                ex.str = "illegal value `" + val + "'; expected `Random' or `Ordered'";
                throw ex;
            }

            defaultTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.Timeout", 60000);
            if (defaultTimeout < 1 && defaultTimeout != -1)
            {
                defaultTimeout = 60000;
                StringBuilder msg = new StringBuilder("invalid value for Ice.Default.Timeout `");
                msg.Append(properties.getProperty("Ice.Default.Timeout"));
                msg.Append("': defaulting to 60000");
                logger.warning(msg.ToString());
            }

            defaultLocatorCacheTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.LocatorCacheTimeout", -1);
            if (defaultLocatorCacheTimeout < -1)
            {
                defaultLocatorCacheTimeout = -1;
                StringBuilder msg = new StringBuilder("invalid value for Ice.Default.LocatorCacheTimeout `");
                msg.Append(properties.getProperty("Ice.Default.LocatorCacheTimeout"));
                msg.Append("': defaulting to -1");
                logger.warning(msg.ToString());
            }

            defaultInvocationTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.InvocationTimeout", -1);
            if (defaultInvocationTimeout < 1 && defaultInvocationTimeout != -1 && defaultInvocationTimeout != -2)
            {
                defaultInvocationTimeout = -1;
                StringBuilder msg = new StringBuilder("invalid value for Ice.Default.InvocationTimeout `");
                msg.Append(properties.getProperty("Ice.Default.InvocationTimeout"));
                msg.Append("': defaulting to -1");
                logger.warning(msg.ToString());
            }

            defaultPreferSecure = properties.getPropertyAsIntWithDefault("Ice.Default.PreferSecure", 0) > 0;

            val = properties.getPropertyWithDefault("Ice.Default.EncodingVersion",
                                                    Ice.Util.encodingVersionToString(Ice.Util.currentEncoding));
            defaultEncoding = Ice.Util.stringToEncodingVersion(val);
            Protocol.checkSupportedEncoding(defaultEncoding);

            bool slicedFormat = properties.getPropertyAsIntWithDefault("Ice.Default.SlicedFormat", 0) > 0;

            defaultFormat = slicedFormat ? Ice.FormatType.SlicedFormat : Ice.FormatType.CompactFormat;
        }
Esempio n. 18
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;
        }
Esempio n. 19
0
        internal DefaultsAndOverrides(Ice.Properties properties)
        {
            string val;

            defaultProtocol = properties.getPropertyWithDefault("Ice.Default.Protocol", "tcp");

            val = properties.getProperty("Ice.Default.Host");
            if (val.Length != 0)
            {
                defaultHost = val;
            }
            else
            {
                defaultHost = null;
            }

            val = properties.getProperty("Ice.Override.Timeout");
            if (val.Length > 0)
            {
                overrideTimeout      = true;
                overrideTimeoutValue = properties.getPropertyAsInt("Ice.Override.Timeout");
            }
            else
            {
                overrideTimeout      = false;
                overrideTimeoutValue = -1;
            }

            val = properties.getProperty("Ice.Override.ConnectTimeout");
            if (val.Length > 0)
            {
                overrideConnectTimeout      = true;
                overrideConnectTimeoutValue = properties.getPropertyAsInt("Ice.Override.ConnectTimeout");
            }
            else
            {
                overrideConnectTimeout      = false;
                overrideConnectTimeoutValue = -1;
            }

            val = properties.getProperty("Ice.Override.CloseTimeout");
            if (val.Length > 0)
            {
                overrideCloseTimeout      = true;
                overrideCloseTimeoutValue = properties.getPropertyAsInt("Ice.Override.CloseTimeout");
            }
            else
            {
                overrideCloseTimeout      = false;
                overrideCloseTimeoutValue = -1;
            }

#if COMPACT
            overrideCompress      = false;
            overrideCompressValue = false;
#else
            val = properties.getProperty("Ice.Override.Compress");
            if (val.Length > 0)
            {
                overrideCompress      = true;
                overrideCompressValue = properties.getPropertyAsInt("Ice.Override.Compress") != 0;
                if (!BasicStream.compressible() && overrideCompressValue)
                {
                    string lib = AssemblyUtil.runtime_ == AssemblyUtil.Runtime.Mono ? "bzip2 library" : "bzip2.dll";
                    Console.Error.WriteLine("warning: " + lib + " not found, Ice.Override.Compress ignored.");
                    overrideCompressValue = false;
                }
            }
            else
            {
                overrideCompress      = !BasicStream.compressible();
                overrideCompressValue = false;
            }
#endif

            val = properties.getProperty("Ice.Override.Secure");
            if (val.Length > 0)
            {
                overrideSecure      = true;
                overrideSecureValue = properties.getPropertyAsInt("Ice.Override.Secure") > 0;
            }
            else
            {
                overrideSecure      = false;
                overrideSecureValue = false;
            }

            defaultCollocationOptimization =
                properties.getPropertyAsIntWithDefault("Ice.Default.CollocationOptimized", 1) > 0;

            val = properties.getPropertyWithDefault("Ice.Default.EndpointSelection", "Random");
            if (val.Equals("Random"))
            {
                defaultEndpointSelection = Ice.EndpointSelectionType.Random;
            }
            else if (val.Equals("Ordered"))
            {
                defaultEndpointSelection = Ice.EndpointSelectionType.Ordered;
            }
            else
            {
                Ice.EndpointSelectionTypeParseException ex = new Ice.EndpointSelectionTypeParseException();
                ex.str = "illegal value `" + val + "'; expected `Random' or `Ordered'";
                throw ex;
            }

            defaultLocatorCacheTimeout = properties.getPropertyAsIntWithDefault("Ice.Default.LocatorCacheTimeout", -1);

            defaultPreferSecure = properties.getPropertyAsIntWithDefault("Ice.Default.PreferSecure", 0) > 0;

            val = properties.getPropertyWithDefault("Ice.Default.EncodingVersion",
                                                    Ice.Util.encodingVersionToString(Ice.Util.currentEncoding));
            defaultEncoding = Ice.Util.stringToEncodingVersion(val);
            Protocol.checkSupportedEncoding(defaultEncoding);

            bool slicedFormat = properties.getPropertyAsIntWithDefault("Ice.Default.SlicedFormat", 0) > 0;
            defaultFormat = slicedFormat ? Ice.FormatType.SlicedFormat : Ice.FormatType.CompactFormat;
        }