internal InternalConnectionFactory(PoolingHttpClientConnectionManager.ConfigData configData, HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection> connFactory ) : base() { this.configData = configData != null ? configData : new PoolingHttpClientConnectionManager.ConfigData (); this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory .Instance; }
public async Task ClientUsingNewCallWithNewProtocol(HttpTransportType transportType) { await using (var server = await StartServer <VersionStartup>()) { var httpConnectionFactory = new HttpConnectionFactory( Options.Create(new HttpConnectionOptions { Transports = transportType, DefaultTransferFormat = TransferFormat.Text }), LoggerFactory); var tcs = new TaskCompletionSource(); var proxyConnectionFactory = new ProxyConnectionFactory(httpConnectionFactory); var connectionBuilder = new HubConnectionBuilder() .WithUrl(new Uri(server.Url + "/version")) .WithLoggerFactory(LoggerFactory); connectionBuilder.Services.AddSingleton <IHubProtocol>(new VersionedJsonHubProtocol(1000)); connectionBuilder.Services.AddSingleton <IConnectionFactory>(proxyConnectionFactory); var connection = connectionBuilder.Build(); connection.On("NewProtocolMethodClient", () => { tcs.SetResult(); }); try { await connection.StartAsync().DefaultTimeout(); // Task should already have been awaited in StartAsync var connectionContext = await proxyConnectionFactory.ConnectTask.DefaultTimeout(); // Simulate a new call from the client var messageToken = new JObject { ["type"] = int.MaxValue }; connectionContext.Transport.Output.Write(Encoding.UTF8.GetBytes(messageToken.ToString())); connectionContext.Transport.Output.Write(new[] { (byte)0x1e }); await connectionContext.Transport.Output.FlushAsync().DefaultTimeout(); await tcs.Task.DefaultTimeout(); } catch (Exception ex) { LoggerFactory.CreateLogger <HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally { await connection.DisposeAsync().DefaultTimeout(); } } }
/// <since>4.3</since> public BasicConnFactory(SocketFactory plainfactory, SSLSocketFactory sslfactory, int connectTimeout, SocketConfig sconfig, ConnectionConfig cconfig) : base() { this.plainfactory = plainfactory; this.sslfactory = sslfactory; this.connectTimeout = connectTimeout; this.sconfig = sconfig != null ? sconfig : SocketConfig.Default; this.connFactory = new DefaultBHttpClientConnectionFactory(cconfig != null ? cconfig : ConnectionConfig.Default); }
public PoolingHttpClientConnectionManager(Registry <ConnectionSocketFactory> socketFactoryRegistry , HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection> connFactory, SchemePortResolver schemePortResolver, DnsResolver dnsResolver, long timeToLive, TimeUnit tunit) : base() { this.configData = new PoolingHttpClientConnectionManager.ConfigData(); this.pool = new CPool(new PoolingHttpClientConnectionManager.InternalConnectionFactory (this.configData, connFactory), 2, 20, timeToLive, tunit); this.connectionOperator = new HttpClientConnectionOperator(socketFactoryRegistry, schemePortResolver, dnsResolver); }
public BasicConnFactory(SSLSocketFactory sslfactory, HttpParams @params) : base() { Args.NotNull(@params, "HTTP params"); this.plainfactory = null; this.sslfactory = sslfactory; this.connectTimeout = @params.GetIntParameter(CoreConnectionPNames.ConnectionTimeout , 0); this.sconfig = HttpParamConfig.GetSocketConfig(@params); this.connFactory = new DefaultBHttpClientConnectionFactory(HttpParamConfig.GetConnectionConfig (@params)); }
public BasicHttpClientConnectionManager(Lookup <ConnectionSocketFactory> socketFactoryRegistry , HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection> connFactory, SchemePortResolver schemePortResolver, DnsResolver dnsResolver) : base() { this.connectionOperator = new HttpClientConnectionOperator(socketFactoryRegistry, schemePortResolver, dnsResolver); this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory .Instance; this.expiry = long.MaxValue; this.socketConfig = SocketConfig.Default; this.connConfig = ConnectionConfig.Default; }
public async Task DoesNotSupportNonUriEndPoints() { var factory = new HttpConnectionFactory( Options.Create(new HttpConnectionOptions { DefaultTransferFormat = TransferFormat.Text }), NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync <NotSupportedException>(async() => await factory.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 0))); Assert.Equal("The provided EndPoint must be of type UriEndPoint.", ex.Message); }
public void ShallowCopyHttpConnectionOptionsCopiesAllPublicProperties() { Func <HttpMessageHandler, HttpMessageHandler> handlerFactory = handler => handler; Func <Task <string> > tokenProvider = () => Task.FromResult(""); Func <WebSocketConnectionContext, CancellationToken, ValueTask <WebSocket> > webSocketFactory = (context, token) => ValueTask.FromResult <WebSocket>(null); Action <ClientWebSocketOptions> webSocketConfig = options => { }; var testValues = new Dictionary <string, object> { { $"{nameof(HttpConnectionOptions.HttpMessageHandlerFactory)}", handlerFactory }, { $"{nameof(HttpConnectionOptions.Headers)}", new Dictionary <string, string>() }, { $"{nameof(HttpConnectionOptions.ClientCertificates)}", new X509CertificateCollection() }, { $"{nameof(HttpConnectionOptions.Cookies)}", new CookieContainer() }, { $"{nameof(HttpConnectionOptions.Url)}", new Uri("https://example.com") }, { $"{nameof(HttpConnectionOptions.Transports)}", HttpTransportType.ServerSentEvents }, { $"{nameof(HttpConnectionOptions.SkipNegotiation)}", true }, { $"{nameof(HttpConnectionOptions.AccessTokenProvider)}", tokenProvider }, { $"{nameof(HttpConnectionOptions.CloseTimeout)}", TimeSpan.FromDays(1) }, { $"{nameof(HttpConnectionOptions.Credentials)}", Mock.Of <ICredentials>() }, { $"{nameof(HttpConnectionOptions.Proxy)}", Mock.Of <IWebProxy>() }, { $"{nameof(HttpConnectionOptions.UseDefaultCredentials)}", true }, { $"{nameof(HttpConnectionOptions.DefaultTransferFormat)}", TransferFormat.Text }, { $"{nameof(HttpConnectionOptions.WebSocketConfiguration)}", webSocketConfig }, { $"{nameof(HttpConnectionOptions.WebSocketFactory)}", webSocketFactory }, { $"{nameof(HttpConnectionOptions.ApplicationMaxBufferSize)}", 1L * 1024 * 1024 }, { $"{nameof(HttpConnectionOptions.TransportMaxBufferSize)}", 1L * 1024 * 1024 }, }; var options = new HttpConnectionOptions(); var properties = typeof(HttpConnectionOptions) .GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { property.SetValue(options, testValues[property.Name]); } var shallowCopiedOptions = HttpConnectionFactory.ShallowCopyHttpConnectionOptions(options); foreach (var property in properties) { Assert.Equal(testValues[property.Name], property.GetValue(shallowCopiedOptions)); testValues.Remove(property.Name); } Assert.Empty(testValues); }
public async Task OptionsUrlMustMatchEndPointIfSet() { var url1 = new Uri("http://example.com/1"); var url2 = new Uri("http://example.com/2"); var factory = new HttpConnectionFactory( Options.Create(new HttpConnectionOptions { Url = url1, DefaultTransferFormat = TransferFormat.Text }), NullLoggerFactory.Instance); var ex = await Assert.ThrowsAsync <InvalidOperationException>(async() => await factory.ConnectAsync(new UriEndPoint(url2))); Assert.Equal("If HttpConnectionOptions.Url was set, it must match the UriEndPoint.Uri passed to ConnectAsync.", ex.Message); }
public async Task ConnectionIsDisposedIfItFailsToStartAsync() { var testHandler = new TestHttpMessageHandler(autoNegotiate: false, handleFirstPoll: false); testHandler.OnRequest((req, next, ct) => Task.FromException <HttpResponseMessage>(new Exception("BOOM"))); var factory = new HttpConnectionFactory(Options.Create(new HttpConnectionOptions() { Url = new Uri("http://example.com"), HttpMessageHandlerFactory = _ => testHandler }), NullLoggerFactory.Instance); // We don't care about the specific exception await Assert.ThrowsAnyAsync <Exception>(() => factory.ConnectAsync(TransferFormat.Text)); // We care that the handler (and by extension the client) was disposed Assert.True(testHandler.Disposed); }
public async void ConfigureSignalR() { // Client keys pair var client_x25519key = _dataEncryptor.CreateX25519EncryptorKey().Key; // Client public key bytes array var clientPublicKeyBytes = _dataEncryptor.GetX25519EncryptorPublicKeyBytes(client_x25519key); var token = GetToken(url); // SignalR hub url var stringUri = $"{url}/userNotification"; var options = new HttpConnectionOptions() { AccessTokenProvider = () => Task.FromResult(token), Url = new System.Uri(stringUri), }; var factory = new HttpConnectionFactory(Options.Create(options), new LoggerFactory()); hubConnection = new HubConnection(factory, new JsonHubProtocol(), null); hubConnection.On <string>("PublicKeyExchange", keyDTOstring => { // Server public key and nonce bytes var keyDto = JsonConvert.DeserializeObject <ServerPublicKeyDto>(keyDTOstring); ReadOnlySpan <byte> nonce = System.Convert.FromBase64String(keyDto.Nonce); // Create nonce from server nonce bytes clientEncryptorKey.Nonce = new NSec.Cryptography.Nonce(nonce.Slice(0, 4), nonce.Slice(4)); clientEncryptorKey.Key = _dataEncryptor.CreateAes256GcmSymmetricKey(System.Convert.FromBase64String(keyDto.PublicKey), client_x25519key); }); await hubConnection.StartAsync(); await hubConnection.InvokeAsync("PublicKeyExchange", System.Convert.ToBase64String(clientPublicKeyBytes)); }
public async void ConfigureSignalR() { // Client keys pair var client_x25519key = _dataEncryptor.CreateX25519EncryptorKey().Key; // Client public key bytes array var clientPublicKeyBytes = _dataEncryptor.GetX25519EncryptorPublicKeyBytes(client_x25519key); // SignalR hub url var stringUri = $"{url}/userRegistration"; var options = new HttpConnectionOptions() { Url = new System.Uri(stringUri), }; var factory = new HttpConnectionFactory(Options.Create(options), new LoggerFactory()); hubConnection = new HubConnection(factory, new JsonHubProtocol(), null); await hubConnection.StartAsync(); }
/// <since>4.3</since> public ProxyClient(HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection> connFactory, ConnectionConfig connectionConfig, RequestConfig requestConfig) : base () { this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory .Instance; this.connectionConfig = connectionConfig != null ? connectionConfig : ConnectionConfig .Default; this.requestConfig = requestConfig != null ? requestConfig : RequestConfig.Default; this.httpProcessor = new ImmutableHttpProcessor(new RequestTargetHost(), new RequestClientConnControl (), new RequestUserAgent()); this.requestExec = new HttpRequestExecutor(); this.proxyAuthStrategy = new ProxyAuthenticationStrategy(); this.authenticator = new HttpAuthenticator(); this.proxyAuthState = new AuthState(); this.authSchemeRegistry = new AuthSchemeRegistry(); this.authSchemeRegistry.Register(AuthSchemes.Basic, new BasicSchemeFactory()); this.authSchemeRegistry.Register(AuthSchemes.Digest, new DigestSchemeFactory()); this.authSchemeRegistry.Register(AuthSchemes.Ntlm, new NTLMSchemeFactory()); this.authSchemeRegistry.Register(AuthSchemes.Spnego, new SPNegoSchemeFactory()); this.authSchemeRegistry.Register(AuthSchemes.Kerberos, new KerberosSchemeFactory( )); this.reuseStrategy = new DefaultConnectionReuseStrategy(); }
public PoolingHttpClientConnectionManager(Registry <ConnectionSocketFactory> socketFactoryRegistry , HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection> connFactory) : this (socketFactoryRegistry, connFactory, null) { }
private HttpResponse Navigate(HttpRequest request, HttpBehavior httpBehavior) { bool ContinueRedirect = true; HttpResponse response = null; HttpConnectionFactory connFactory = new HttpConnectionFactory(); HttpConnection connection = connFactory.GetConnnection(request.Uri, this.m_proxy); connection.Timeout = Timeout; HttpBehavior.RedirectStep rs = null; string redirectUri = null; int responseCode = 0; int redirectCounter = 0; try { while (ContinueRedirect) { try { response = SendRequestAndGetResponse(connection, request); redirectUri = response.Location; responseCode = response.ResponseCode; // response code 100 means that we need to wait for another response // and receive the response from the socket again on the same connection if (responseCode == 100) { response = GetResponse(connection); redirectUri = response.Location; responseCode = response.ResponseCode; } if (httpBehavior != null) { rs = httpBehavior.GetNextStep(); rs.Compare(responseCode, redirectUri); ContinueRedirect = !httpBehavior.IsEmpty(); } else { ContinueRedirect = (redirectCounter < this.m_maxRedirects && (responseCode == 301 || responseCode == 302)); redirectCounter++; } if (ContinueRedirect) { request = new HttpGet(new Uri(redirectUri)); // make sure the connection is still open and redirect url is from the same host connection = connFactory.GetConnnection(request.Uri, this.m_proxy, connection); connection.Timeout = Timeout; } } catch (Exception ex) { int i = 0; throw ex; } } } finally { connection.Close(); } return(response); }
public PoolingHttpClientConnectionManager(Registry <ConnectionSocketFactory> socketFactoryRegistry , HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection> connFactory, DnsResolver dnsResolver) : this(socketFactoryRegistry, connFactory, null, dnsResolver, -1, TimeUnit.Milliseconds) { }
public PoolingHttpClientConnectionManager(HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection > connFactory) : this(GetDefaultRegistry(), connFactory, null) { }
public BasicHttpClientConnectionManager(Lookup <ConnectionSocketFactory> socketFactoryRegistry , HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection> connFactory) : this (socketFactoryRegistry, connFactory, null, null) { }