public TTlsSocketTransport(TcpClient client, TConfiguration config, X509Certificate2 certificate, bool isServer = false, RemoteCertificateValidationCallback certValidator = null, LocalCertificateSelectionCallback localCertificateSelectionCallback = null, SslProtocols sslProtocols = SslProtocols.Tls12) : base(config) { _client = client; _certificate = certificate; _certValidator = certValidator; _localCertificateSelectionCallback = localCertificateSelectionCallback; _sslProtocols = sslProtocols; _isServer = isServer; if (isServer && certificate == null) { throw new ArgumentException("TTlsSocketTransport needs certificate to be used for server", nameof(certificate)); } if (IsOpen) { InputStream = client.GetStream(); OutputStream = client.GetStream(); } }
private TTransport MakeTransport(URL url, TConfiguration configuration) { var ipaddress = IPAddress.Loopback; if (!NetUtil.IsAnyHost(url.Host) && !NetUtil.IsLocalHost(url.Host)) { ipaddress = IPAddress.Parse(url.Host); } // construct endpoint transport TTransport transport = null; Transport selectedTransport = GetTransport(url); { switch (selectedTransport) { case Transport.Tcp: transport = new TSocketTransport(ipaddress, url.Port, configuration); break; case Transport.NamedPipe: transport = new TNamedPipeTransport(".test", configuration); break; case Transport.Http: transport = new THttpTransport(new Uri($"http://{url.Host}:{url.Port}"), configuration); break; case Transport.TcpTls: transport = new TTlsSocketTransport(ipaddress, url.Port, configuration, GetCertificate(), CertValidator, LocalCertificateSelectionCallback); break; default: Console.WriteLine("unhandled case"); break; } } // optionally add layered transport(s) Buffering selectedBuffering = GetBuffering(url); switch (selectedBuffering) { case Buffering.Buffered: transport = new TBufferedTransport(transport); break; case Buffering.Framed: transport = new TFramedTransport(transport); break; default: // layered transport(s) are optional if (selectedBuffering != Buffering.None) { Console.WriteLine("unhandled case"); } break; } return(transport); }
/// <summary> /// Get the specify setting. The first level will get from memory cache, if the cache not exist, then get from physical path by intenal directory. /// </summary> /// <typeparam name="TConfiguration">The type of setting.</typeparam> /// <returns>The setting from cache or physical path.</returns> public virtual TConfiguration Get <TConfiguration>() where TConfiguration : class, ISetting, new() { var setting = new TConfiguration(); if (_cache.TryGetValue(setting.Name, out TConfiguration cacheConfiguration)) { return(cacheConfiguration); } var path = GetPath(setting); try { using var reader = new StreamReader(path, Encoding.UTF8); var content = reader.ReadToEnd(); setting = JsonConvert.DeserializeObject <TConfiguration>(content); _cache.Set(setting.Name, setting); //refresh } catch (FileNotFoundException) { setting = (TConfiguration)setting.Initialize(); Set(setting); } return(setting); }
public TTlsSocketTransport(string host, int port, TConfiguration config, int timeout, X509Certificate2 certificate, RemoteCertificateValidationCallback certValidator = null, LocalCertificateSelectionCallback localCertificateSelectionCallback = null, SslProtocols sslProtocols = SslProtocols.Tls12) : base(config) { try { var entry = Dns.GetHostEntry(host); if (entry.AddressList.Length == 0) { throw new TTransportException(TTransportException.ExceptionType.Unknown, "unable to resolve host name"); } var addr = entry.AddressList[0]; _host = new IPAddress(addr.GetAddressBytes(), addr.ScopeId); _port = port; _timeout = timeout; _certificate = certificate; _certValidator = certValidator; _localCertificateSelectionCallback = localCertificateSelectionCallback; _sslProtocols = sslProtocols; InitSocket(); } catch (SocketException e) { throw new TTransportException(TTransportException.ExceptionType.Unknown, e.Message, e); } }
public TSocketTransport(string host, int port, TConfiguration config, int timeout = 0) : base(config) { try { var entry = Dns.GetHostEntry(host); if (entry.AddressList.Length == 0) { throw new TTransportException(TTransportException.ExceptionType.Unknown, "unable to resolve host name"); } var addr = entry.AddressList[0]; Host = new IPAddress(addr.GetAddressBytes(), addr.ScopeId); Port = port; TcpClient = new TcpClient(host, port); TcpClient.ReceiveTimeout = TcpClient.SendTimeout = timeout; TcpClient.Client.NoDelay = true; SetInputOutputStream(); } catch (SocketException e) { throw new TTransportException(TTransportException.ExceptionType.Unknown, e.Message, e); } }
public THttpServerTransport( ITAsyncProcessor processor, TConfiguration config, TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory, TTransportFactory inputTransFactory = null, TTransportFactory outputTransFactory = null, RequestDelegate next = null, ILoggerFactory loggerFactory = null) { // loggerFactory == null is not illegal anymore Processor = processor ?? throw new ArgumentNullException(nameof(processor)); Configuration = config; // may be null InputProtocolFactory = inputProtocolFactory ?? throw new ArgumentNullException(nameof(inputProtocolFactory)); OutputProtocolFactory = outputProtocolFactory ?? throw new ArgumentNullException(nameof(outputProtocolFactory)); InputTransportFactory = inputTransFactory; OutputTransportFactory = outputTransFactory; /* never used * _next = next; * _logger = (loggerFactory != null) ? loggerFactory.CreateLogger<THttpServerTransport>() : new NullLogger<THttpServerTransport>(); */ }
public TSocketTransport(string host, int port, TConfiguration config, int timeout = 0) : base(config) { try { var entry = Dns.GetHostEntryAsync(host).ConfigureAwait(false).GetAwaiter().GetResult(); if (entry.AddressList.Length == 0) { throw new TTransportException(TTransportException.ExceptionType.Unknown, "unable to resolve host name"); } Host = entry.AddressList[0]; Port = port; #if WINDOWS_UWP || NETSTANDARD1_3 TcpClient = new TcpClient(); #else TcpClient = new TcpClient(host, port); #endif TcpClient.ReceiveTimeout = TcpClient.SendTimeout = timeout; TcpClient.Client.NoDelay = true; SetInputOutputStream(); } catch (SocketException e) { throw new TTransportException(TTransportException.ExceptionType.Unknown, e.Message, e); } }
public TMemoryBufferTransport(byte[] buf, TConfiguration config) : base(config) { Bytes = (byte[])buf.Clone(); _bytesUsed = Bytes.Length; UpdateKnownMessageSize(_bytesUsed); }
public THttpServerTransport( ITAsyncProcessor processor, TConfiguration config, RequestDelegate next = null, ILoggerFactory loggerFactory = null) : this(processor, config, new TBinaryProtocol.Factory(), null, next, loggerFactory) { }
public TNamedPipeTransport(string server, string pipe, TConfiguration config, int timeout = Timeout.Infinite) : base(config) { var serverName = string.IsNullOrWhiteSpace(server) ? server : "."; ConnectTimeout = (timeout > 0) ? timeout : Timeout.Infinite; PipeStream = new NamedPipeClientStream(serverName, pipe, PipeDirection.InOut, PipeOptions.None); }
public TNamedPipeTransport(string server, string pipe, TConfiguration config, int timeout = DEFAULT_CONNECT_TIMEOUT) : base(config) { var serverName = string.IsNullOrWhiteSpace(server) ? server : "."; ConnectTimeout = (timeout > 0) ? timeout : DEFAULT_CONNECT_TIMEOUT; PipeStream = new NamedPipeClientStream(serverName, pipe, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Anonymous); }
public THttpServerTransport( ITAsyncProcessor processor, TConfiguration config, TProtocolFactory protocolFactory, TTransportFactory transFactory = null, RequestDelegate next = null, ILoggerFactory loggerFactory = null) : this(processor, config, protocolFactory, protocolFactory, transFactory, transFactory, next, loggerFactory) { }
/// <summary> /// Возвращает объект типа <typeparamref name="TConfiguration"/>, содержащий настройки модуля <typeparamref name="TModule"/>. /// Изменение значений настроек в возвращенном объекте не влияет на непосредственно используемые в работе приложения значения. Для применения измененных значений см. <see cref="ApplyConfiguration{TConfiguration}(TConfiguration)"/>. /// </summary> /// <exception cref="InvalidOperationException">Возникает, если модуль <typeparamref name="TModule"/> не найден.</exception> public TConfiguration GetEditable <TConfiguration>() where TConfiguration : ModuleConfiguration <TModule>, new() { var valuesProviderUsable = AppCore.GetModulesManager().CreateValuesProviderForModule(_module); var configuration = new TConfiguration() { _isReadonly = false, _valuesProvider = valuesProviderUsable }; return(configuration); }
public TSocketTransport(IPAddress host, int port, TConfiguration config, int timeout = 0) : base(config) { Host = host; Port = port; TcpClient = new TcpClient(); TcpClient.ReceiveTimeout = TcpClient.SendTimeout = timeout; TcpClient.Client.NoDelay = true; SetInputOutputStream(); }
public TTlsSocketTransport(IPAddress host, int port, TConfiguration config, X509Certificate2 certificate = null, RemoteCertificateValidationCallback certValidator = null, LocalCertificateSelectionCallback localCertificateSelectionCallback = null, SslProtocols sslProtocols = SslProtocols.Tls12) : this(host, port, config, 0, certificate, certValidator, localCertificateSelectionCallback, sslProtocols) { }
public TConfiguration Get <TConfiguration>() where TConfiguration : struct, IConfiguration <T> { IConfiguration <T> configuration; if (_configurations.TryGetValue(typeof(TConfiguration), out configuration)) { return((TConfiguration)configuration); } var defaultConf = new TConfiguration(); defaultConf.ToDefault(); return(defaultConf); }
/// <summary> /// Возвращает объект типа <typeparamref name="TConfiguration"/>, содержащий параметры модуля <typeparamref name="TModule"/>. /// Возвращенный объект находится в режиме "только для чтения" - изменение параметров невозможно, попытка выполнить set вызовет <see cref="InvalidOperationException"/>. /// Все объекты конфигурации, созданные путем вызова этого метода, манипулируют одним набором значений. /// То есть после изменения конфигурации путем вызова <see cref="ApplyConfiguration{TConfiguration}(TConfiguration)"/> новые значения автоматически доступны во всех ранее созданных в данном методе экземплярах конфигурации. /// </summary> /// <exception cref="InvalidOperationException">Возникает, если модуль <typeparamref name="TModule"/> не найден.</exception> public TConfiguration GetUsable <TConfiguration>() where TConfiguration : ModuleConfiguration <TModule>, new() { if (_valuesProviderUsable == null) { _valuesProviderUsable = AppCore.GetModulesManager().CreateValuesProviderForModule(_module); } var configuration = new TConfiguration() { _isReadonly = true, _valuesProvider = _valuesProviderUsable }; return(configuration); }
public TServerSocketTransport(int port, TConfiguration config, int clientTimeout = 0) : this(null, config, clientTimeout) { try { // Make server socket _server = new TcpListener(IPAddress.Any, port); _server.Server.NoDelay = true; } catch (Exception) { _server = null; throw new TTransportException("Could not create ServerSocket on port " + port + "."); } }
public THttpTransport(Uri uri, TConfiguration config, IEnumerable <X509Certificate> certificates, IDictionary <string, string> customRequestHeaders, string userAgent = null) : base(config) { _uri = uri; _certificates = (certificates ?? Enumerable.Empty <X509Certificate>()).ToArray(); if (!string.IsNullOrEmpty(userAgent)) { UserAgent = userAgent; } // due to current bug with performance of Dispose in netcore https://github.com/dotnet/corefx/issues/8809 // this can be switched to default way (create client->use->dispose per flush) later _httpClient = CreateClient(customRequestHeaders); }
/// <summary> /// Constructor that takes a <c>HttpClient</c> instance to support using <c>IHttpClientFactory</c>. /// </summary> /// <remarks>As the <c>HttpMessageHandler</c> of the client must be configured at the time of creation, it /// is assumed that the consumer has already added any certificates and configured decompression methods. The /// consumer can use the <c>CreateHttpClientHandler</c> method to get a handler with these set.</remarks> /// <param name="httpClient">Client configured with the desired message handler, user agent, and URI if not /// specified in the <c>uri</c> parameter. A default user agent will be used if not set.</param> /// <param name="config">Thrift configuration object</param> /// <param name="uri">Optional URI to use for requests, if not specified the base address of <c>httpClient</c> /// is used.</param> public THttpTransport(HttpClient httpClient, TConfiguration config, Uri uri = null) : base(config) { _httpClient = httpClient; _uri = uri ?? httpClient.BaseAddress; httpClient.BaseAddress = _uri; var userAgent = _httpClient.DefaultRequestHeaders.UserAgent.ToString(); if (!string.IsNullOrEmpty(userAgent)) { UserAgent = userAgent; } ConfigureClient(_httpClient); }
public TConfiguration Get <TConfiguration>() where TConfiguration : class, new() { if (typeof(TConfiguration) == typeof(Vertica.Integration.Infrastructure.Configuration.Configuration)) { throw new ArgumentException("Getting a Configuration of type Configuration is not allowed."); } Vertica.Integration.Infrastructure.Configuration.Configuration configuration = this._repository.Get(this.GetId <TConfiguration>(false)); if (configuration != null) { return(JsonConvert.DeserializeObject <TConfiguration>(configuration.JsonData, this._serializerSettings)); } TConfiguration tConfiguration = Activator.CreateInstance <TConfiguration>(); this.Save <TConfiguration>(tConfiguration, "IntegrationService", false); return(tConfiguration); }
public TTlsSocketTransport(IPAddress host, int port, TConfiguration config, int timeout, X509Certificate2 certificate, RemoteCertificateValidationCallback certValidator = null, LocalCertificateSelectionCallback localCertificateSelectionCallback = null, SslProtocols sslProtocols = SslProtocols.Tls12) : base(config) { _host = host; _port = port; _timeout = timeout; _certificate = certificate; _certValidator = certValidator; _localCertificateSelectionCallback = localCertificateSelectionCallback; _sslProtocols = sslProtocols; InitSocket(); }
public void StartServer() { try { var configuration = GetConfiguration(); Log.Logger = CreateSerilogLogger(configuration); IHost host = CreateHostBuilder(configuration, Log.Logger); int serverPort = configuration.GetValue <int>(STR_ThriftServerDefaultPort); Log.Information("Starting {0} at port {1}", STR_AppName, serverPort); //Prepare the thrift server processor ThriftGatewayServerImpl serverHandler = new ThriftGatewayServerImpl(); var processor = new ThriftAPIGatewayService.AsyncProcessor(serverHandler); var protocolFactory = new TBinaryProtocol.Factory(); var thriftConfiguration = new TConfiguration(); var serverTransport = new TServerSocketTransport(serverPort, thriftConfiguration); var transportFactory = new TBufferedTransport.Factory(); var threadConfiguration = new TThreadPoolAsyncServer.Configuration(); var loggerFactory = new SerilogLoggerFactory(Log.Logger); var server = new TThreadPoolAsyncServer( processorFactory: new TSingletonProcessorFactory(processor), serverTransport: serverTransport, inputTransportFactory: transportFactory, outputTransportFactory: transportFactory, inputProtocolFactory: protocolFactory, outputProtocolFactory: protocolFactory, threadConfig: threadConfiguration, loggerFactory.CreateLogger <Startup>()); Log.Information("Starting {0} at port {1}", STR_AppName, serverPort); Log.Information(STR_QuitText); var source = new CancellationTokenSource(); server.ServeAsync(CancellationToken.None).GetAwaiter().GetResult(); Console.ReadLine(); source.Cancel(); } catch (Exception ex) { Log.Fatal(ex, "Startup terminated unexpectedly ({ApplicationContext})!", STR_AppName); } }
protected override async Task <IClient> CreateClient(URL url) { //实例化TheTransport //获得transport参数,用于反射实例化 var timeout = url.GetParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); var config = new TConfiguration(); config.MaxFrameSize = url.GetParameter(MAXFRAMESIZE_KEY, config.MaxFrameSize); config.MaxMessageSize = url.GetParameter(MAXMESSAGESIZE_KEY, config.MaxMessageSize); config.RecursionLimit = url.GetParameter(RECURSIONLIMIT_KEY, config.RecursionLimit); var transport = GetTransport(url); Logger().LogInformation($"Selected client transport: {transport}"); var protocol = MakeProtocol(url, MakeTransport(url, config)); Logger().LogInformation($"Selected client protocol: {GetProtocol(url)}"); var mplex = GetMultiplex(url); Logger().LogInformation("Multiplex " + (mplex ? "yes" : "no")); var proxyKey = url.GetParameter(PROXY_KEY); if (string.IsNullOrEmpty(proxyKey) || !_clientTypes.ContainsKey(proxyKey)) { throw new RpcException($"not find the proxy thrift client {url.ToFullString()}"); } if (mplex) { protocol = new TMultiplexedProtocol(protocol, proxyKey); } //instance ThriftClient var client = (TBaseClient)Activator.CreateInstance(_clientTypes[proxyKey], protocol); await Task.CompletedTask; return(new ThriftClient(client, timeout, url)); }
public TConfiguration Get <TConfiguration>() where TConfiguration : class, new() { if (typeof(TConfiguration) == typeof(Configuration)) { throw new ArgumentException("Getting a Configuration of type Configuration is not allowed."); } Configuration existing = _repository.Get(GetId <TConfiguration>()); if (existing != null) { return(JsonConvert.DeserializeObject <TConfiguration>(existing.JsonData, _serializerSettings)); } var configuration = new TConfiguration(); Save(configuration, "IntegrationService"); return(configuration); }
public TTlsServerSocketTransport( TcpListener listener, TConfiguration config, X509Certificate2 certificate, RemoteCertificateValidationCallback clientCertValidator = null, LocalCertificateSelectionCallback localCertificateSelectionCallback = null, SslProtocols sslProtocols = SslProtocols.Tls12) : base(config) { if (!certificate.HasPrivateKey) { throw new TTransportException(TTransportException.ExceptionType.Unknown, "Your server-certificate needs to have a private key"); } _serverCertificate = certificate; _clientCertValidator = clientCertValidator; _localCertificateSelectionCallback = localCertificateSelectionCallback; _sslProtocols = sslProtocols; _server = listener; }
public TTlsServerSocketTransport( int port, TConfiguration config, X509Certificate2 certificate, RemoteCertificateValidationCallback clientCertValidator = null, LocalCertificateSelectionCallback localCertificateSelectionCallback = null, SslProtocols sslProtocols = SslProtocols.Tls12) : this(null, config, certificate, clientCertValidator, localCertificateSelectionCallback, sslProtocols) { try { // Create server socket _server = new TcpListener(IPAddress.Any, port); _server.Server.NoDelay = true; } catch (Exception) { _server = null; throw new TTransportException($"Could not create ServerSocket on port {port}."); } }
/// <summary> /// 获取 <typeparamref name="TConfiguration"/> 类型的配置项组。 /// </summary> /// <typeparam name="TConfiguration">配置项组的类型。</typeparam> /// <returns>配置项组。</returns> public TConfiguration Of <TConfiguration>() where TConfiguration : Configuration, new() { if (_configurationDictionary.TryGetValue(typeof(TConfiguration), out var configuration)) { return((TConfiguration)configuration); } lock (_locker) { if (_configurationDictionary.TryGetValue(typeof(TConfiguration), out var lockedConfiguration)) { return((TConfiguration)lockedConfiguration); } configuration = new TConfiguration { Repo = _repo }; _configurationDictionary[typeof(TConfiguration)] = configuration; return((TConfiguration)configuration); } }
public TConfiguration Parse <TConfiguration>() where TConfiguration : new() { var errors = new List <ConfigurationParserError>(); var config = new TConfiguration(); foreach (var property in typeof(TConfiguration).GetProperties()) { var rawValue = Environment.GetEnvironmentVariable(property.Name); if (_configurationBinders[property.Name].TryParse(property.Name, rawValue, errors, out var parsed)) { property.SetValue(config, parsed); } } if (errors.Any()) { throw new ConfigurationBindException(errors); } return(config); }
public Program() { _haltables = new List <IHaltable>(); _receivers = new SortedList <int, IReceiver>(); _hotkeyActions = new Dictionary <Keys, Action>(); GameData = new HGameData(); Connection = new HConnection(); Connection.Connected += Connected; Connection.DataOutgoing += HandleData; Connection.DataIncoming += HandleData; Connection.Disconnected += Disconnected; Hook = new KeyboardHook(); Hook.HotkeyPressed += HotkeyPressed; Config = new TConfiguration(); Eavesdropper.Terminate(); Eavesdropper.Certifier = new CertificateManager("Tanji", "Tanji Certificate Authority"); Eavesdropper.Overrides.AddRange(Config.ProxyOverrides); }