コード例 #1
0
 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;
 }
コード例 #2
0
        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();
                }
            }
        }
コード例 #3
0
 /// <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);
 }
コード例 #4
0
 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);
 }
コード例 #5
0
 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));
 }
コード例 #6
0
 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;
 }
コード例 #7
0
        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);
        }
コード例 #8
0
    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);
    }
コード例 #9
0
        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);
        }
コード例 #10
0
        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);
        }
コード例 #11
0
        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));
        }
コード例 #12
0
        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();
        }
コード例 #13
0
 /// <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();
 }
コード例 #14
0
 public PoolingHttpClientConnectionManager(Registry <ConnectionSocketFactory> socketFactoryRegistry
                                           , HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection> connFactory) : this
     (socketFactoryRegistry, connFactory, null)
 {
 }
コード例 #15
0
        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);
        }
コード例 #16
0
 public PoolingHttpClientConnectionManager(Registry <ConnectionSocketFactory> socketFactoryRegistry
                                           , HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection> connFactory, DnsResolver
                                           dnsResolver) : this(socketFactoryRegistry, connFactory, null, dnsResolver, -1,
                                                               TimeUnit.Milliseconds)
 {
 }
コード例 #17
0
 public PoolingHttpClientConnectionManager(HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection
                                                                  > connFactory) : this(GetDefaultRegistry(), connFactory, null)
 {
 }
コード例 #18
0
 public BasicHttpClientConnectionManager(Lookup <ConnectionSocketFactory> socketFactoryRegistry
                                         , HttpConnectionFactory <HttpRoute, ManagedHttpClientConnection> connFactory) : this
     (socketFactoryRegistry, connFactory, null, null)
 {
 }