public override async Task RunAsync(string[] args) { await using ZeroC.Ice.Communicator communicator = Initialize(ref args); var endpoint = Protocol == ZeroC.Ice.Protocol.Ice1 ? $"{Transport} -h {Host}" : $"ice+{Transport}://{Host}:0"; communicator.SetProperty("TestAdapter.Endpoints", endpoint); ZeroC.Ice.ObjectAdapter adapter = communicator.CreateObjectAdapter("TestAdapter"); adapter.Add("test", new Decimal()); adapter.Add("test1", new Test1I()); adapter.Add("test2", new Test2I()); await adapter.ActivateAsync(); Console.Out.Write("testing operation name... "); Console.Out.Flush(); IdecimalPrx p = adapter.CreateProxy("test", IdecimalPrx.Factory); p.@default(); Console.Out.WriteLine("ok"); Console.Out.Write("testing System as module name... "); Console.Out.Flush(); [email protected] t1 = adapter.CreateProxy("test1", [email protected]); t1.op(); ZeroC.Slice.Test.Escape.System.ITestPrx t2 = adapter.CreateProxy("test2", ZeroC.Slice.Test.Escape.System.ITestPrx.Factory); t2.op(); Console.Out.WriteLine("ok"); Console.Out.Write("testing types... "); Console.Out.Flush(); Testtypes(); Console.Out.WriteLine("ok"); }
internal SslEngine( Communicator communicator, X509Certificate2Collection?certificates, X509Certificate2Collection?caCertificates, RemoteCertificateValidationCallback?certificateValidationCallback, IPasswordCallback?passwordCallback) { _logger = communicator.Logger; SecurityTraceLevel = communicator.GetPropertyAsInt("IceSSL.Trace.Security") ?? 0; _trustManager = new SslTrustManager(communicator); RemoteCertificateValidationCallback = certificateValidationCallback; PasswordCallback = passwordCallback; Certs = certificates; CaCerts = caCertificates; // Check for a default directory. We look in this directory for files mentioned in the configuration. _defaultDir = communicator.GetProperty("IceSSL.DefaultDir") ?? ""; string certStoreLocation = communicator.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 SslProtocols = ParseProtocols(communicator.GetPropertyAsList("IceSSL.Protocols")); // CheckCertName determines whether we compare the name in a peer's certificate against its hostname. bool?checkCertName = communicator.GetPropertyAsBool("IceSSL.CheckCertName"); if (checkCertName != null && RemoteCertificateValidationCallback != null) { throw new InvalidConfigurationException( "the property `IceSSL.CheckCertName' check is incompatible with the custom remote certificate validation callback"); } CheckCertName = 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. int?verifyDepthMax = communicator.GetPropertyAsInt("IceSSL.VerifyDepthMax"); if (verifyDepthMax != null && RemoteCertificateValidationCallback != null) { throw new InvalidConfigurationException( "the property `IceSSL.VerifyDepthMax' check is incompatible with the custom remote certificate validation callback"); } _verifyDepthMax = verifyDepthMax ?? 3; // CheckCRL determines whether the certificate revocation list is checked, and how strictly. CheckCRL = communicator.GetPropertyAsInt("IceSSL.CheckCRL") ?? 0; // 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 = communicator.GetProperty("IceSSL.CertFile"); string? passwordStr = communicator.GetProperty("IceSSL.Password"); string? findCert = communicator.GetProperty("IceSSL.FindCert"); const string findPrefix = "IceSSL.FindCert."; Dictionary <string, string> findCertProps = communicator.GetProperties(forPrefix: findPrefix); if (certFile != null) { if (!CheckPath(ref certFile)) { throw new FileNotFoundException($"certificate file not found: `{certFile}'", certFile); } SecureString?password = null; if (passwordStr != null) { password = CreateSecureString(passwordStr); } else if (PasswordCallback != null) { password = PasswordCallback(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( $"error while attempting to load certificate from `{certFile}'", ex); } } else if (findCert != null) { string certStore = communicator.GetProperty("IceSSL.CertStore") ?? "My"; Certs.AddRange(FindCertificates("IceSSL.FindCert", storeLocation, certStore, findCert)); if (Certs.Count == 0) { throw new InvalidConfigurationException("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("no certificates found"); } } } if (CaCerts == null) { string?certAuthFile = communicator.GetProperty("IceSSL.CAs"); if (certAuthFile != null && RemoteCertificateValidationCallback != null) { throw new InvalidConfigurationException( "the property `IceSSL.CAs' is incompatible with the custom remote certificate validation callback"); } bool?usePlatformCAs = communicator.GetPropertyAsBool("IceSSL.UsePlatformCAs"); if (usePlatformCAs != null && RemoteCertificateValidationCallback != null) { throw new InvalidConfigurationException( "the property `IceSSL.UsePlatformCAs' is incompatible with the custom remote certificate validation callback"); } if (RemoteCertificateValidationCallback == null) { if (certAuthFile != null || !(usePlatformCAs ?? false)) { CaCerts = new X509Certificate2Collection(); } if (certAuthFile != null) { if (!CheckPath(ref certAuthFile)) { throw new FileNotFoundException("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( $"error while attempting to load CA certificate from {certAuthFile}", ex); } } } } }
// Constructor for ice2 unmarshaling. internal WSEndpoint(EndpointData data, Communicator communicator) : base(data, communicator) { }
// TODO avoid copy payload (ToArray) creates a copy, that should be possible when // the frame has a single segment. public IncomingResponseFrame(Communicator communicator, OutgoingResponseFrame frame) : this(communicator, frame.Payload.ToArray()) { }
internal SslEngine( Communicator communicator, TlsClientOptions?tlsClientOptions, TlsServerOptions?tlsServerOptions) { _logger = communicator.Logger; SecurityTraceLevel = communicator.GetPropertyAsInt("IceSSL.Trace.Security") ?? 0; SslTrustManager = new SslTrustManager(communicator); TlsClientOptions = new TlsClientOptions(); TlsServerOptions = new TlsServerOptions(); TlsClientOptions.EnabledSslProtocols = tlsClientOptions?.EnabledSslProtocols ?? ParseProtocols(communicator.GetPropertyAsList("IceSSL.Protocols")); TlsServerOptions.EnabledSslProtocols = tlsServerOptions?.EnabledSslProtocols ?? ParseProtocols(communicator.GetPropertyAsList("IceSSL.Protocols")); TlsServerOptions.RequireClientCertificate = tlsServerOptions?.RequireClientCertificate ?? true; // Check for a default directory. We look in this directory for files mentioned in the configuration. string defaultDir = communicator.GetProperty("IceSSL.DefaultDir") ?? ""; X509Certificate2Collection?certificates = null; // If IceSSL.CertFile is defined, load a certificate from a file and add it to the collection. if (communicator.GetProperty("IceSSL.CertFile") is string certificateFile) { if (!CheckPath(defaultDir, ref certificateFile)) { throw new FileNotFoundException( $"certificate file not found: `{certificateFile}'", certificateFile); } certificates = new X509Certificate2Collection(); try { X509KeyStorageFlags importFlags; if (AssemblyUtil.IsLinux) { importFlags = X509KeyStorageFlags.EphemeralKeySet; } else { importFlags = tlsClientOptions?.UseMachineContex ?? tlsServerOptions?.UseMachineContex ?? false ? X509KeyStorageFlags.MachineKeySet : X509KeyStorageFlags.UserKeySet; } certificates.Add(communicator.GetProperty("IceSSL.Password") is string password ? new X509Certificate2(certificateFile, password, importFlags) : new X509Certificate2(certificateFile, "", importFlags)); } catch (CryptographicException ex) { throw new InvalidConfigurationException( $"error while attempting to load certificate from `{certificateFile}'", ex); } } TlsClientOptions.ClientCertificates = tlsClientOptions?.ClientCertificates ?? certificates; TlsServerOptions.ServerCertificate = tlsServerOptions?.ServerCertificate ?? certificates?[0]; TlsClientOptions.ClientCertificateSelectionCallback = tlsClientOptions?.ClientCertificateSelectionCallback; X509Certificate2Collection?caCertificates = null; if (communicator.GetProperty("IceSSL.CAs") is string certAuthFile) { if (!CheckPath(defaultDir, ref certAuthFile)) { throw new FileNotFoundException("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 } string beginCertificateMark = "-----BEGIN CERTIFICATE-----"; string endCertificateMark = "-----END CERTIFICATE-----"; caCertificates = new X509Certificate2Collection(); if (strbuf.Length == data.Length) { int size, startpos, endpos = 0; bool first = true; while (true) { startpos = strbuf.IndexOf(beginCertificateMark, endpos); if (startpos != -1) { endpos = strbuf.IndexOf(endCertificateMark, startpos); if (endpos == -1) { throw new FormatException( $"end certificate mark `{endCertificateMark}' not found"); } size = endpos - startpos + endCertificateMark.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); caCertificates.Import(cert); first = false; } } else { caCertificates.Import(data); } } catch (Exception ex) { throw new InvalidConfigurationException( $"error while attempting to load CA certificate from `{certAuthFile}'", ex); } } if (tlsClientOptions?.ServerCertificateValidationCallback == null) { TlsClientOptions.ServerCertificateCertificateAuthorities = tlsClientOptions?.ServerCertificateCertificateAuthorities ?? caCertificates; } else { TlsClientOptions.ServerCertificateValidationCallback = tlsClientOptions.ServerCertificateValidationCallback; } if (tlsServerOptions?.ClientCertificateValidationCallback == null) { TlsServerOptions.ClientCertificateCertificateAuthorities = tlsServerOptions?.ClientCertificateCertificateAuthorities ?? caCertificates; } else { TlsServerOptions.ClientCertificateValidationCallback = tlsServerOptions.ClientCertificateValidationCallback; } }
// Constructor for ice1 unmarshaling private WSEndpoint(EndpointData data, TimeSpan timeout, bool compress, Communicator communicator) : base(data, timeout, compress, communicator) { }
internal MetricsAdmin(Communicator communicator, ILogger logger) { Logger = logger; _communicator = communicator; UpdateViews(); }
// TODO avoid copy payload (ToArray) creates a copy, that should be possible when // the frame has a single segment. internal IncomingRequestFrame(Communicator communicator, OutgoingRequestFrame frame) : this(communicator, VectoredBufferExtensions.ToArray(frame.Data)) { }
internal MetricsMap(string mapPrefix, Communicator communicator, Dictionary <string, ISubMapFactory>?subMaps) { MetricsAdmin.ValidateProperties(mapPrefix, communicator); _properties = communicator.GetProperties(forPrefix: mapPrefix); _retain = communicator.GetPropertyAsInt($"{mapPrefix}RetainDetached") ?? 10; _accept = ParseRule(communicator, $"{mapPrefix}Accept"); _reject = ParseRule(communicator, $"{mapPrefix}Reject"); var groupByAttributes = new List <string>(); var 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); } } _groupByAttributes = groupByAttributes.ToImmutableList(); _groupBySeparators = groupBySeparators.ToImmutableList(); if (subMaps != null && subMaps.Count > 0) { _subMapCloneFactories = new Dictionary <string, ISubMapCloneFactory>(); var subMapNames = new List <string>(); var subMapCloneFactories = new Dictionary <string, ISubMapCloneFactory>(); foreach ((string key, ISubMapFactory value) in subMaps) { subMapNames.Add(key); string subAllMapsPrefix = $"{mapPrefix}Map."; string subMapPrefix = $"{subAllMapsPrefix}{key}."; if (communicator.GetProperties(forPrefix: subMapPrefix).Count == 0) { if (communicator.GetProperties(forPrefix: subAllMapsPrefix).Count == 0) { subMapPrefix = mapPrefix; } else { continue; // This sub-map isn't configured. } } subMapCloneFactories.Add(key, value.CreateCloneFactory(subMapPrefix, communicator)); } _subMapCloneFactories = subMapCloneFactories.ToImmutableDictionary(); } else { _subMapCloneFactories = null; } }
// Change this proxy's communicator private static IRemoteLoggerPrx ChangeCommunicator(IRemoteLoggerPrx prx, Communicator communicator) => IRemoteLoggerPrx.Parse(prx.ToString() !, communicator);
/// <summary>Parses an ice+transport URI string that represents one or more object adapter endpoints.</summary> /// <param name="uriString">The URI string to parse.</param> /// <param name="communicator">The communicator.</param> /// <returns>The list of endpoints.</returns> internal static IReadOnlyList <Endpoint> ParseEndpoints(string uriString, Communicator communicator) => Parse(uriString, oaEndpoints: true, communicator).Endpoints;
internal OpaqueEndpoint( Communicator communicator, Protocol protocol, Dictionary <string, string?> options, string endpointString) : base(protocol) { Communicator = communicator; if (options.TryGetValue("-t", out string?argument)) { if (argument == null) { throw new FormatException($"no argument provided for -t option in endpoint `{endpointString}'"); } short t; try { t = short.Parse(argument, CultureInfo.InvariantCulture); } catch (FormatException ex) { throw new FormatException( $"invalid transport value `{argument}' in endpoint `{endpointString}'", ex); } if (t < 0) { throw new FormatException( $"transport value `{argument}' out of range in endpoint `{endpointString}'"); } Transport = (Transport)t; options.Remove("-t"); } else { throw new FormatException($"no -t option in endpoint `{endpointString}'"); } if (options.TryGetValue("-e", out argument)) { if (argument == null) { throw new FormatException($"no argument provided for -e option in endpoint `{endpointString}'"); } try { Encoding = Encoding.Parse(argument); } catch (FormatException ex) { throw new FormatException($"invalid encoding version `{argument}' in endpoint `{endpointString}'", ex); } options.Remove("-e"); } else { Encoding = Encoding.Latest; // TODO: should be the default encoding for this communicator } if (options.TryGetValue("-v", out argument)) { if (argument == null) { throw new FormatException($"no argument provided for -v option in endpoint `{endpointString}'"); } try { Bytes = Convert.FromBase64String(argument); } catch (FormatException ex) { throw new FormatException($"invalid Base64 input in endpoint `{endpointString}'", ex); } options.Remove("-v"); } else { throw new FormatException($"no -v option in endpoint `{endpointString}'"); } // the caller deals with remaining options, if any }
private protected IPEndpoint( Communicator communicator, Protocol protocol, Dictionary <string, string?> options, bool oaEndpoint, string endpointString) : base(communicator, protocol) { Debug.Assert(protocol == Protocol.Ice1 || protocol == Protocol.Ice2); // TODO: ice1-only if (options.TryGetValue("-h", out string?argument)) { Host = argument ?? throw new FormatException($"no argument provided for -h option in endpoint `{endpointString}'"); if (Host == "*") { Host = oaEndpoint ? "" : throw new FormatException($"`-h *' not valid for proxy endpoint `{endpointString}'"); } options.Remove("-h"); } else { Host = Communicator.DefaultHost ?? ""; } if (options.TryGetValue("-p", out argument)) { if (argument == null) { throw new FormatException($"no argument provided for -p option in endpoint `{endpointString}'"); } try { Port = ushort.Parse(argument, CultureInfo.InvariantCulture); } catch (FormatException ex) { throw new FormatException($"invalid port value `{argument}' in endpoint `{endpointString}'", ex); } options.Remove("-p"); } // else Port remains 0 if (options.TryGetValue("--sourceAddress", out argument)) { if (oaEndpoint) { throw new FormatException( $"`--sourceAddress' not valid for object adapter endpoint `{endpointString}'"); } if (argument == null) { throw new FormatException( $"no argument provided for --sourceAddress option in endpoint `{endpointString}'"); } try { SourceAddress = IPAddress.Parse(argument); } catch (Exception ex) { throw new FormatException( $"invalid IP address provided for --sourceAddress option in endpoint `{endpointString}'", ex); } options.Remove("--sourceAddress"); } // else SourceAddress remains null }