예제 #1
0
        internal AsyncIOThread(Ice.Communicator communicator)
        {
            _communicator = communicator;

            _thread = new HelperThread(this);
            updateObserver();
            _thread.Start(Util.stringToThreadPriority(communicator.GetProperty("Ice.ThreadPriority")));
        }
예제 #2
0
 internal EndpointHostResolver(Ice.Communicator communicator)
 {
     _communicator = communicator;
     _protocol     = communicator.ProtocolSupport;
     _preferIPv6   = communicator.PreferIPv6;
     _thread       = new HelperThread(this);
     updateObserver();
     _thread.Start(Util.stringToThreadPriority(communicator.GetProperty("Ice.ThreadPriority")));
 }
예제 #3
0
        internal TrustManager(Ice.Communicator communicator)
        {
            Debug.Assert(communicator != null);
            _communicator = communicator;
            _traceLevel   = _communicator.GetPropertyAsInt("IceSSL.Trace.Security") ?? 0;
            string key = "IceSSL.TrustOnly";

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

                    if (accept.Count > 0)
                    {
                        _acceptServer[name] = accept;
                    }
                }
            }
            catch (FormatException ex)
            {
                throw new FormatException($"IceSSL: invalid property `{key};", ex);
            }
        }
예제 #4
0
파일: Timer.cs 프로젝트: yuwenyong/ice
        //
        // Only for use by Instance.
        //
        internal Timer(Ice.Communicator communicator, ThreadPriority priority = ThreadPriority.Normal)
        {
            _communicator = communicator;
            string?threadName = _communicator.GetProperty("Ice.ProgramName");

            if (threadName != null)
            {
                threadName += "-";
            }

            _thread = new Thread(new ThreadStart(Run));
            _thread.IsBackground = true;
            _thread.Name         = $"{threadName}Ice.Timer";
            _thread.Priority     = priority;
            _thread.Start();
        }
예제 #5
0
        public ACMConfig(Ice.Communicator communicator, Ice.Logger logger, string prefix, ACMConfig defaults)
        {
            Debug.Assert(prefix != null);

            string timeoutProperty;

            if ((prefix == "Ice.ACM.Client" || prefix == "Ice.ACM.Server") &&
                communicator.GetProperty($"{prefix}.Timeout") == null)
            {
                timeoutProperty = prefix; // Deprecated property.
            }
            else
            {
                timeoutProperty = prefix + ".Timeout";
            }

            timeout = communicator.GetPropertyAsInt(timeoutProperty) * 1000 ?? defaults.timeout;
            if (timeout < 0)
            {
                logger.warning($"invalid value for property `{timeoutProperty}', default value will be used instead");
                timeout = defaults.timeout;
            }

            int hb = communicator.GetPropertyAsInt($"{prefix}.Heartbeat") ?? (int)defaults.heartbeat;

            if (hb >= (int)Ice.ACMHeartbeat.HeartbeatOff && hb <= (int)Ice.ACMHeartbeat.HeartbeatAlways)
            {
                heartbeat = (Ice.ACMHeartbeat)hb;
            }
            else
            {
                logger.warning($"invalid value for property `{prefix}.Heartbeat', default value will be used instead");
                heartbeat = defaults.heartbeat;
            }

            int cl = communicator.GetPropertyAsInt($"{prefix}.Close") ?? (int)defaults.close;

            if (cl >= (int)Ice.ACMClose.CloseOff && cl <= (int)Ice.ACMClose.CloseOnIdleForceful)
            {
                close = (Ice.ACMClose)cl;
            }
            else
            {
                logger.warning($"invalid value for property `{prefix}.Close', default value will be used instead");
                close = defaults.close;
            }
        }
예제 #6
0
        internal DefaultsAndOverrides(Ice.Communicator communicator, Ice.ILogger logger)
        {
            string?val;

            DefaultProtocol = communicator.GetProperty("Ice.Default.Protocol") ?? "tcp";

            DefaultHost = communicator.GetProperty("Ice.Default.Host");

            val = communicator.GetProperty("Ice.Default.SourceAddress");
            if (val != null)
            {
                DefaultSourceAddress = Network.GetNumericAddress(val);
                if (DefaultSourceAddress == null)
                {
                    throw new Ice.InitializationException("invalid IP address set for Ice.Default.SourceAddress: `" +
                                                          val + "'");
                }
            }
            else
            {
                DefaultSourceAddress = null;
            }

            val = communicator.GetProperty("Ice.Override.Timeout");
            if (val != null)
            {
                OverrideTimeout      = true;
                OverrideTimeoutValue = communicator.GetPropertyAsInt("Ice.Override.Timeout") ?? 0;
                if (OverrideTimeoutValue < 1 && OverrideTimeoutValue != -1)
                {
                    OverrideTimeoutValue = -1;
                    var msg = new StringBuilder("invalid value for Ice.Override.Timeout `");
                    msg.Append(communicator.GetProperty("Ice.Override.Timeout"));
                    msg.Append("': defaulting to -1");
                    logger.Warning(msg.ToString());
                }
            }
            else
            {
                OverrideTimeout      = false;
                OverrideTimeoutValue = -1;
            }

            val = communicator.GetProperty("Ice.Override.ConnectTimeout");
            if (val != null)
            {
                OverrideConnectTimeout      = true;
                OverrideConnectTimeoutValue = communicator.GetPropertyAsInt("Ice.Override.ConnectTimeout") ?? -1;
                if (OverrideConnectTimeoutValue < 1 && OverrideConnectTimeoutValue != -1)
                {
                    OverrideConnectTimeoutValue = -1;
                    var msg = new StringBuilder("invalid value for Ice.Override.ConnectTimeout `");
                    msg.Append(communicator.GetProperty("Ice.Override.ConnectTimeout"));
                    msg.Append("': defaulting to -1");
                    logger.Warning(msg.ToString());
                }
            }
            else
            {
                OverrideConnectTimeout      = false;
                OverrideConnectTimeoutValue = -1;
            }

            val = communicator.GetProperty("Ice.Override.CloseTimeout");
            if (val != null)
            {
                OverrideCloseTimeout      = true;
                OverrideCloseTimeoutValue = communicator.GetPropertyAsInt("Ice.Override.CloseTimeout") ?? -1;
                if (OverrideCloseTimeoutValue < 1 && OverrideCloseTimeoutValue != -1)
                {
                    OverrideCloseTimeoutValue = -1;
                    var msg = new StringBuilder("invalid value for Ice.Override.CloseTimeout `");
                    msg.Append(communicator.GetProperty("Ice.Override.CloseTimeout"));
                    msg.Append("': defaulting to -1");
                    logger.Warning(msg.ToString());
                }
            }
            else
            {
                OverrideCloseTimeout      = false;
                OverrideCloseTimeoutValue = -1;
            }

            val = communicator.GetProperty("Ice.Override.Compress");
            if (val != null)
            {
                OverrideCompress      = true;
                OverrideCompressValue = communicator.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 = communicator.GetProperty("Ice.Override.Secure");
            if (val != null)
            {
                OverrideSecure      = true;
                OverrideSecureValue = communicator.GetPropertyAsInt("Ice.Override.Secure") > 0;
            }
            else
            {
                OverrideSecure      = false;
                OverrideSecureValue = false;
            }

            DefaultCollocationOptimization = (communicator.GetPropertyAsInt("Ice.Default.CollocationOptimized") ?? 1) > 0;

            val = communicator.GetProperty("Ice.Default.EndpointSelection") ?? "Random";
            if (val.Equals("Random"))
            {
                DefaultEndpointSelection = Ice.EndpointSelectionType.Random;
            }
            else if (val.Equals("Ordered"))
            {
                DefaultEndpointSelection = Ice.EndpointSelectionType.Ordered;
            }
            else
            {
                throw new ArgumentException($"illegal value `{val}'; expected `Random' or `Ordered'");
            }

            DefaultTimeout = communicator.GetPropertyAsInt("Ice.Default.Timeout") ?? 60000;
            if (DefaultTimeout < 1 && DefaultTimeout != -1)
            {
                DefaultTimeout = 60000;
                var msg = new StringBuilder("invalid value for Ice.Default.Timeout `");
                msg.Append(communicator.GetProperty("Ice.Default.Timeout"));
                msg.Append("': defaulting to 60000");
                logger.Warning(msg.ToString());
            }

            DefaultLocatorCacheTimeout = communicator.GetPropertyAsInt("Ice.Default.LocatorCacheTimeout") ?? -1;
            if (DefaultLocatorCacheTimeout < -1)
            {
                DefaultLocatorCacheTimeout = -1;
                var msg = new StringBuilder("invalid value for Ice.Default.LocatorCacheTimeout `");
                msg.Append(communicator.GetProperty("Ice.Default.LocatorCacheTimeout"));
                msg.Append("': defaulting to -1");
                logger.Warning(msg.ToString());
            }

            DefaultInvocationTimeout = communicator.GetPropertyAsInt("Ice.Default.InvocationTimeout") ?? -1;
            if (DefaultInvocationTimeout < 1 && DefaultInvocationTimeout != -1 && DefaultInvocationTimeout != -2)
            {
                DefaultInvocationTimeout = -1;
                var msg = new StringBuilder("invalid value for Ice.Default.InvocationTimeout `");
                msg.Append(communicator.GetProperty("Ice.Default.InvocationTimeout"));
                msg.Append("': defaulting to -1");
                logger.Warning(msg.ToString());
            }

            DefaultPreferSecure = communicator.GetPropertyAsInt("Ice.Default.PreferSecure") > 0;

            val             = communicator.GetProperty("Ice.Default.EncodingVersion") ?? Ice.Util.EncodingVersionToString(Ice.Util.CurrentEncoding);
            DefaultEncoding = Ice.Util.StringToEncodingVersion(val);
            Protocol.checkSupportedEncoding(DefaultEncoding);

            bool slicedFormat = communicator.GetPropertyAsInt("Ice.Default.SlicedFormat") > 0;

            DefaultFormat = slicedFormat ? Ice.FormatType.SlicedFormat : Ice.FormatType.CompactFormat;
        }
예제 #7
0
            public static void allTests(global::Test.TestHelper helper)
            {
                Ice.Communicator communicator = helper.communicator();
                var output = helper.getWriter();

                output.Write("testing proxy endpoint information... ");
                output.Flush();
                {
                    var p1 = IObjectPrx.Parse(
                        "test -t:default -h tcphost -p 10000 -t 1200 -z --sourceAddress 10.10.10.10:" +
                        "udp -h udphost -p 10001 --interface eth0 --ttl 5 --sourceAddress 10.10.10.10:" +
                        "opaque -e 1.8 -t 100 -v ABCD", communicator);

                    Ice.Endpoint[] endps = p1.Endpoints;

                    Ice.EndpointInfo    info        = endps[0].getInfo();
                    Ice.TCPEndpointInfo tcpEndpoint = getTCPEndpointInfo(info);
                    test(tcpEndpoint.host.Equals("tcphost"));
                    test(tcpEndpoint.port == 10000);
                    test(tcpEndpoint.sourceAddress.Equals("10.10.10.10"));
                    test(tcpEndpoint.timeout == 1200);
                    test(tcpEndpoint.compress);
                    test(!tcpEndpoint.datagram());

                    test(tcpEndpoint.type() == Ice.TCPEndpointType.value && !tcpEndpoint.secure() ||
                         tcpEndpoint.type() == Ice.SSLEndpointType.value && tcpEndpoint.secure() ||
                         tcpEndpoint.type() == Ice.WSEndpointType.value && !tcpEndpoint.secure() ||
                         tcpEndpoint.type() == Ice.WSSEndpointType.value && tcpEndpoint.secure());
                    test(tcpEndpoint.type() == Ice.TCPEndpointType.value && info is Ice.TCPEndpointInfo ||
                         tcpEndpoint.type() == Ice.SSLEndpointType.value && info is IceSSL.EndpointInfo ||
                         tcpEndpoint.type() == Ice.WSEndpointType.value && info is Ice.WSEndpointInfo ||
                         tcpEndpoint.type() == Ice.WSSEndpointType.value && info is Ice.WSEndpointInfo);

                    Ice.UDPEndpointInfo udpEndpoint = (Ice.UDPEndpointInfo)endps[1].getInfo();
                    test(udpEndpoint.host.Equals("udphost"));
                    test(udpEndpoint.port == 10001);
                    test(udpEndpoint.mcastInterface.Equals("eth0"));
                    test(udpEndpoint.mcastTtl == 5);
                    test(udpEndpoint.sourceAddress.Equals("10.10.10.10"));
                    test(udpEndpoint.timeout == -1);
                    test(!udpEndpoint.compress);
                    test(!udpEndpoint.secure());
                    test(udpEndpoint.datagram());
                    test(udpEndpoint.type() == 3);

                    Ice.OpaqueEndpointInfo opaqueEndpoint = (Ice.OpaqueEndpointInfo)endps[2].getInfo();
                    test(opaqueEndpoint.rawBytes.Length > 0);
                    test(opaqueEndpoint.rawEncoding.Equals(new Ice.EncodingVersion(1, 8)));
                }
                output.WriteLine("ok");

                Ice.ObjectAdapter adapter;
                output.Write("test object adapter endpoint information... ");
                output.Flush();
                {
                    string host = communicator.GetPropertyAsInt("Ice.IPv6") != 0 ? "::1" : "127.0.0.1";
                    communicator.SetProperty("TestAdapter.Endpoints", "tcp -h \"" + host +
                                             "\" -t 15000:udp -h \"" + host + "\"");
                    adapter = communicator.createObjectAdapter("TestAdapter");

                    Ice.Endpoint[] endpoints = adapter.GetEndpoints();
                    test(endpoints.Length == 2);
                    Ice.Endpoint[] publishedEndpoints = adapter.GetPublishedEndpoints();
                    test(Collections.Equals(endpoints, publishedEndpoints));

                    Ice.TCPEndpointInfo tcpEndpoint = getTCPEndpointInfo(endpoints[0].getInfo());
                    test(tcpEndpoint.type() == Ice.TCPEndpointType.value ||
                         tcpEndpoint.type() == Ice.SSLEndpointType.value ||
                         tcpEndpoint.type() == Ice.WSEndpointType.value ||
                         tcpEndpoint.type() == Ice.WSSEndpointType.value);

                    test(tcpEndpoint.host.Equals(host));
                    test(tcpEndpoint.port > 0);
                    test(tcpEndpoint.timeout == 15000);

                    Ice.UDPEndpointInfo udpEndpoint = (Ice.UDPEndpointInfo)endpoints[1].getInfo();
                    test(udpEndpoint.host.Equals(host));
                    test(udpEndpoint.datagram());
                    test(udpEndpoint.port > 0);

                    endpoints = new Ice.Endpoint[] { endpoints[0] };
                    test(endpoints.Length == 1);
                    adapter.SetPublishedEndpoints(endpoints);
                    publishedEndpoints = adapter.GetPublishedEndpoints();
                    test(Collections.Equals(endpoints, publishedEndpoints));

                    adapter.Destroy();

                    int port = helper.getTestPort(1);
                    communicator.SetProperty("TestAdapter.Endpoints", $"default -h * -p {port}");
                    communicator.SetProperty("TestAdapter.PublishedEndpoints", helper.getTestEndpoint(1));
                    adapter = communicator.createObjectAdapter("TestAdapter");

                    endpoints = adapter.GetEndpoints();
                    test(endpoints.Length >= 1);
                    publishedEndpoints = adapter.GetPublishedEndpoints();
                    test(publishedEndpoints.Length == 1);

                    foreach (Endpoint endpoint in endpoints)
                    {
                        tcpEndpoint = getTCPEndpointInfo(endpoint.getInfo());
                        test(tcpEndpoint.port == port);
                    }

                    tcpEndpoint = getTCPEndpointInfo(publishedEndpoints[0].getInfo());
                    test(tcpEndpoint.host == "127.0.0.1");
                    test(tcpEndpoint.port == port);

                    adapter.Destroy();
                }
                output.WriteLine("ok");

                int endpointPort = helper.getTestPort(0);

                var @base = IObjectPrx.Parse("test:" +
                                             helper.getTestEndpoint(0) + ":" +
                                             helper.getTestEndpoint(0, "udp"), communicator);
                var testIntf = Test.TestIntfPrx.CheckedCast(@base);

                string defaultHost = communicator.GetProperty("Ice.Default.Host") ?? "";

                output.Write("test connection endpoint information... ");
                output.Flush();
                {
                    Ice.EndpointInfo    info    = @base.GetConnection().getEndpoint().getInfo();
                    Ice.TCPEndpointInfo tcpinfo = getTCPEndpointInfo(info);
                    test(tcpinfo.port == endpointPort);
                    test(!tcpinfo.compress);
                    test(tcpinfo.host.Equals(defaultHost));

                    Dictionary <string, string> ctx = testIntf.getEndpointInfoAsContext();
                    test(ctx["host"].Equals(tcpinfo.host));
                    test(ctx["compress"].Equals("false"));
                    int port = int.Parse(ctx["port"]);
                    test(port > 0);

                    info = @base.Clone(invocationMode: InvocationMode.Datagram).GetConnection().getEndpoint().getInfo();
                    Ice.UDPEndpointInfo udp = (Ice.UDPEndpointInfo)info;
                    test(udp.port == endpointPort);
                    test(udp.host.Equals(defaultHost));
                }
                output.WriteLine("ok");

                output.Write("testing connection information... ");
                output.Flush();
                {
                    Ice.Connection connection = @base.GetConnection();
                    connection.setBufferSize(1024, 2048);

                    Ice.ConnectionInfo    info   = connection.getInfo();
                    Ice.TCPConnectionInfo ipInfo = getTCPConnectionInfo(info);
                    test(!info.incoming);
                    test(info.adapterName.Length == 0);
                    test(ipInfo.remotePort == endpointPort);
                    test(ipInfo.localPort > 0);
                    if (defaultHost.Equals("127.0.0.1"))
                    {
                        test(ipInfo.localAddress.Equals(defaultHost));
                        test(ipInfo.remoteAddress.Equals(defaultHost));
                    }
                    test(ipInfo.rcvSize >= 1024);
                    test(ipInfo.sndSize >= 2048);

                    Dictionary <string, string> ctx = testIntf.getConnectionInfoAsContext();
                    test(ctx["incoming"].Equals("true"));
                    test(ctx["adapterName"].Equals("TestAdapter"));
                    test(ctx["remoteAddress"].Equals(ipInfo.localAddress));
                    test(ctx["localAddress"].Equals(ipInfo.remoteAddress));
                    test(ctx["remotePort"].Equals(ipInfo.localPort.ToString()));
                    test(ctx["localPort"].Equals(ipInfo.remotePort.ToString()));

                    if (@base.GetConnection().type().Equals("ws") || @base.GetConnection().type().Equals("wss"))
                    {
                        Dictionary <string, string> headers = ((Ice.WSConnectionInfo)info).headers;
                        test(headers["Upgrade"].Equals("websocket"));
                        test(headers["Connection"].Equals("Upgrade"));
                        test(headers["Sec-WebSocket-Protocol"].Equals("ice.zeroc.com"));
                        test(headers["Sec-WebSocket-Accept"] != null);

                        test(ctx["ws.Upgrade"].Equals("websocket"));
                        test(ctx["ws.Connection"].Equals("Upgrade"));
                        test(ctx["ws.Sec-WebSocket-Protocol"].Equals("ice.zeroc.com"));
                        test(ctx["ws.Sec-WebSocket-Version"].Equals("13"));
                        test(ctx["ws.Sec-WebSocket-Key"] != null);
                    }

                    connection = @base.Clone(invocationMode: InvocationMode.Datagram).GetConnection();
                    connection.setBufferSize(2048, 1024);

                    Ice.UDPConnectionInfo udpInfo = (Ice.UDPConnectionInfo)connection.getInfo();
                    test(!udpInfo.incoming);
                    test(udpInfo.adapterName.Length == 0);
                    test(udpInfo.localPort > 0);
                    test(udpInfo.remotePort == endpointPort);

                    if (defaultHost.Equals("127.0.0.1"))
                    {
                        test(udpInfo.remoteAddress.Equals(defaultHost));
                        test(udpInfo.localAddress.Equals(defaultHost));
                    }
                    test(udpInfo.rcvSize >= 2048);
                    test(udpInfo.sndSize >= 1024);
                }
                output.WriteLine("ok");

                testIntf.shutdown();

                communicator.shutdown();
                communicator.waitForShutdown();
            }
예제 #8
0
파일: SSLEngine.cs 프로젝트: nail-lian/ice
        internal void Initialize()
        {
            if (_initialized)
            {
                return;
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                byte[] cert = new byte[size];
                                Buffer.BlockCopy(data, startpos, cert, 0, size);
                                _caCerts !.Import(cert);
                                first = false;
                            }
                        }
                        else
                        {
                            _caCerts !.Import(data);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidConfigurationException(
                                  $"IceSSL: error while attempting to load CA certificate from {certAuthFile}", ex);
                    }
                }
            }
            _initialized = true;
        }
예제 #9
0
        public ThreadPool(Ice.Communicator communicator, string prefix, int timeout)
        {
            _communicator   = communicator;
            _dispatcher     = communicator.Dispatcher;
            _destroyed      = false;
            _prefix         = prefix;
            _threadIndex    = 0;
            _inUse          = 0;
            _serialize      = _communicator.GetPropertyAsInt($"{_prefix}.Serialize") > 0;
            _serverIdleTime = timeout;

            string?programName = _communicator.GetProperty("Ice.ProgramName");

            if (programName != null)
            {
                _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 = _communicator.GetPropertyAsInt($"{_prefix}.Size") ?? 1;

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

            int sizeMax = _communicator.GetPropertyAsInt($"{_prefix}.SizeMax") ?? size;

            if (sizeMax < size)
            {
                _communicator.Logger.warning($"{_prefix}.SizeMax < {_prefix}.Size; SizeMax adjusted to Size ({size})");
                sizeMax = size;
            }

            int sizeWarn = _communicator.GetPropertyAsInt($"{_prefix}.SizeWarn") ?? 0;

            if (sizeWarn != 0 && sizeWarn < size)
            {
                _communicator.Logger.warning(
                    $"{_prefix}.SizeWarn < {_prefix}.Size; adjusted SizeWarn to Size ({size})");
                sizeWarn = size;
            }
            else if (sizeWarn > sizeMax)
            {
                _communicator.Logger.warning(
                    "${_prefix}.SizeWarn > {_prefix}.SizeMax; adjusted SizeWarn to SizeMax ({sizeMax})");
                sizeWarn = sizeMax;
            }

            int threadIdleTime = _communicator.GetPropertyAsInt($"{_prefix}.ThreadIdleTime") ?? 60;

            if (threadIdleTime < 0)
            {
                _communicator.Logger.warning($"{_prefix}.ThreadIdleTime < 0; ThreadIdleTime adjusted to 0");
                threadIdleTime = 0;
            }

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

            int stackSize = communicator.GetPropertyAsInt($"{_prefix }.StackSize") ?? 0;

            if (stackSize < 0)
            {
                _communicator.Logger.warning($"{_prefix}.StackSize < 0; Size adjusted to OS default");
                stackSize = 0;
            }
            _stackSize = stackSize;

            _priority = Util.stringToThreadPriority(_communicator.GetProperty($"{_prefix}.ThreadPriority") ??
                                                    _communicator.GetProperty("Ice.ThreadPriority"));

            if (_communicator.traceLevels().threadPool >= 1)
            {
                _communicator.Logger.trace(_communicator.traceLevels().threadPoolCat,
                                           $"creating {_prefix}: Size = {_size}, SizeMax = {_sizeMax}, SizeWarn = {_sizeWarn}");
            }

            _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;
                _communicator.Logger.error(s);

                destroy();
                joinWithAllThreads();
                throw;
            }
        }
예제 #10
0
            public static Test.TestIntfPrx allTests(global::Test.TestHelper helper)
            {
                Ice.Communicator communicator = helper.communicator();
                string           sref         = "test:" + helper.getTestEndpoint(0);
                var obj = IObjectPrx.Parse(sref, communicator);

                test(obj != null);
                var proxy = Test.TestIntfPrx.UncheckedCast(obj);

                test(proxy != null);

                var output = helper.getWriter();

                output.Write("testing enum values... ");
                output.Flush();

                test((int)Test.ByteEnum.benum1 == 0);
                test((int)Test.ByteEnum.benum2 == 1);
                test((int)Test.ByteEnum.benum3 == Test.ByteConst1.value);
                test((int)Test.ByteEnum.benum4 == Test.ByteConst1.value + 1);
                test((int)Test.ByteEnum.benum5 == Test.ShortConst1.value);
                test((int)Test.ByteEnum.benum6 == Test.ShortConst1.value + 1);
                test((int)Test.ByteEnum.benum7 == Test.IntConst1.value);
                test((int)Test.ByteEnum.benum8 == Test.IntConst1.value + 1);
                test((int)Test.ByteEnum.benum9 == Test.LongConst1.value);
                test((int)Test.ByteEnum.benum10 == Test.LongConst1.value + 1);
                test((int)Test.ByteEnum.benum11 == Test.ByteConst2.value);

                test((int)Test.ShortEnum.senum1 == 3);
                test((int)Test.ShortEnum.senum2 == 4);
                test((int)Test.ShortEnum.senum3 == Test.ByteConst1.value);
                test((int)Test.ShortEnum.senum4 == Test.ByteConst1.value + 1);
                test((int)Test.ShortEnum.senum5 == Test.ShortConst1.value);
                test((int)Test.ShortEnum.senum6 == Test.ShortConst1.value + 1);
                test((int)Test.ShortEnum.senum7 == Test.IntConst1.value);
                test((int)Test.ShortEnum.senum8 == Test.IntConst1.value + 1);
                test((int)Test.ShortEnum.senum9 == Test.LongConst1.value);
                test((int)Test.ShortEnum.senum10 == Test.LongConst1.value + 1);
                test((int)Test.ShortEnum.senum11 == Test.ShortConst2.value);

                test((int)Test.IntEnum.ienum1 == 0);
                test((int)Test.IntEnum.ienum2 == 1);
                test((int)Test.IntEnum.ienum3 == Test.ByteConst1.value);
                test((int)Test.IntEnum.ienum4 == Test.ByteConst1.value + 1);
                test((int)Test.IntEnum.ienum5 == Test.ShortConst1.value);
                test((int)Test.IntEnum.ienum6 == Test.ShortConst1.value + 1);
                test((int)Test.IntEnum.ienum7 == Test.IntConst1.value);
                test((int)Test.IntEnum.ienum8 == Test.IntConst1.value + 1);
                test((int)Test.IntEnum.ienum9 == Test.LongConst1.value);
                test((int)Test.IntEnum.ienum10 == Test.LongConst1.value + 1);
                test((int)Test.IntEnum.ienum11 == Test.IntConst2.value);
                test((int)Test.IntEnum.ienum12 == Test.LongConst2.value);

                test((int)Test.SimpleEnum.red == 0);
                test((int)Test.SimpleEnum.green == 1);
                test((int)Test.SimpleEnum.blue == 2);

                output.WriteLine("ok");

                output.Write("testing enum streaming... ");
                output.Flush();

                Ice.OutputStream ostr;
                byte[]           bytes;

                bool encoding_1_0 = communicator.GetProperty("Ice.Default.EncodingVersion") == "1.0";

                ostr = new OutputStream(communicator);
                ostr.WriteEnum((int)Test.ByteEnum.benum11, (int)Test.ByteEnum.benum11);
                bytes = ostr.Finished();
                test(bytes.Length == 1); // ByteEnum should require one byte

                ostr = new OutputStream(communicator);
                ostr.WriteEnum((int)Test.ShortEnum.senum11, (int)Test.ShortEnum.senum11);
                bytes = ostr.Finished();
                test(bytes.Length == (encoding_1_0 ? 2 : 5));

                ostr = new OutputStream(communicator);
                ostr.WriteEnum((int)Test.IntEnum.ienum11, (int)Test.IntEnum.ienum12);
                bytes = ostr.Finished();
                test(bytes.Length == (encoding_1_0 ? 4 : 5));

                ostr = new OutputStream(communicator);
                ostr.WriteEnum((int)Test.SimpleEnum.blue, (int)Test.SimpleEnum.blue);
                bytes = ostr.Finished();
                test(bytes.Length == 1); // SimpleEnum should require one byte

                output.WriteLine("ok");

                output.Write("testing enum operations... ");
                output.Flush();

                Test.ByteEnum byteEnum;
                test(proxy.opByte(Test.ByteEnum.benum1, out byteEnum) == Test.ByteEnum.benum1);
                test(byteEnum == Test.ByteEnum.benum1);
                test(proxy.opByte(Test.ByteEnum.benum11, out byteEnum) == Test.ByteEnum.benum11);
                test(byteEnum == Test.ByteEnum.benum11);

                Test.ShortEnum shortEnum;
                test(proxy.opShort(Test.ShortEnum.senum1, out shortEnum) == Test.ShortEnum.senum1);
                test(shortEnum == Test.ShortEnum.senum1);
                test(proxy.opShort(Test.ShortEnum.senum11, out shortEnum) == Test.ShortEnum.senum11);
                test(shortEnum == Test.ShortEnum.senum11);

                Test.IntEnum intEnum;
                test(proxy.opInt(Test.IntEnum.ienum1, out intEnum) == Test.IntEnum.ienum1);
                test(intEnum == Test.IntEnum.ienum1);
                test(proxy.opInt(Test.IntEnum.ienum11, out intEnum) == Test.IntEnum.ienum11);
                test(intEnum == Test.IntEnum.ienum11);
                test(proxy.opInt(Test.IntEnum.ienum12, out intEnum) == Test.IntEnum.ienum12);
                test(intEnum == Test.IntEnum.ienum12);

                Test.SimpleEnum s;
                test(proxy.opSimple(Test.SimpleEnum.green, out s) == Test.SimpleEnum.green);
                test(s == Test.SimpleEnum.green);

                output.WriteLine("ok");

                output.Write("testing enum sequences operations... ");
                output.Flush();

                {
                    var b1 = new Test.ByteEnum[11]
                    {
                        Test.ByteEnum.benum1,
                        Test.ByteEnum.benum2,
                        Test.ByteEnum.benum3,
                        Test.ByteEnum.benum4,
                        Test.ByteEnum.benum5,
                        Test.ByteEnum.benum6,
                        Test.ByteEnum.benum7,
                        Test.ByteEnum.benum8,
                        Test.ByteEnum.benum9,
                        Test.ByteEnum.benum10,
                        Test.ByteEnum.benum11
                    };

                    Test.ByteEnum[] b2;
                    Test.ByteEnum[] b3 = proxy.opByteSeq(b1, out b2);

                    for (int i = 0; i < b1.Length; ++i)
                    {
                        test(b1[i] == b2[i]);
                        test(b1[i] == b3[i]);
                    }
                }

                {
                    var s1 = new Test.ShortEnum[11]
                    {
                        Test.ShortEnum.senum1,
                        Test.ShortEnum.senum2,
                        Test.ShortEnum.senum3,
                        Test.ShortEnum.senum4,
                        Test.ShortEnum.senum5,
                        Test.ShortEnum.senum6,
                        Test.ShortEnum.senum7,
                        Test.ShortEnum.senum8,
                        Test.ShortEnum.senum9,
                        Test.ShortEnum.senum10,
                        Test.ShortEnum.senum11
                    };

                    Test.ShortEnum[] s2;
                    Test.ShortEnum[] s3 = proxy.opShortSeq(s1, out s2);

                    for (int i = 0; i < s1.Length; ++i)
                    {
                        test(s1[i] == s2[i]);
                        test(s1[i] == s3[i]);
                    }
                }

                {
                    Test.IntEnum[] i1 = new Test.IntEnum[11]
                    {
                        Test.IntEnum.ienum1,
                        Test.IntEnum.ienum2,
                        Test.IntEnum.ienum3,
                        Test.IntEnum.ienum4,
                        Test.IntEnum.ienum5,
                        Test.IntEnum.ienum6,
                        Test.IntEnum.ienum7,
                        Test.IntEnum.ienum8,
                        Test.IntEnum.ienum9,
                        Test.IntEnum.ienum10,
                        Test.IntEnum.ienum11
                    };

                    Test.IntEnum[] i2;
                    Test.IntEnum[] i3 = proxy.opIntSeq(i1, out i2);

                    for (int i = 0; i < i1.Length; ++i)
                    {
                        test(i1[i] == i2[i]);
                        test(i1[i] == i3[i]);
                    }
                }

                {
                    var s1 = new Test.SimpleEnum[3]
                    {
                        Test.SimpleEnum.red,
                        Test.SimpleEnum.green,
                        Test.SimpleEnum.blue
                    };

                    Test.SimpleEnum[] s2;
                    Test.SimpleEnum[] s3 = proxy.opSimpleSeq(s1, out s2);

                    for (int i = 0; i < s1.Length; ++i)
                    {
                        test(s1[i] == s2[i]);
                        test(s1[i] == s3[i]);
                    }
                }

                output.WriteLine("ok");
                return(proxy);
            }
예제 #11
0
        internal MetricsMap(string mapPrefix, Ice.Communicator communicator, Dictionary <string, ISubMapFactory>?subMaps)
        {
            MetricsAdminI.validateProperties(mapPrefix, communicator);
            _properties = communicator.GetProperties(forPrefix: mapPrefix);

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

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

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

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

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

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

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

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