Ejemplo n.º 1
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void Upgrade(ManagedHttpClientConnection conn, HttpHost host, HttpContext
                                    context)
        {
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            Lookup <ConnectionSocketFactory> registry = GetSocketFactoryRegistry(clientContext
                                                                                 );
            ConnectionSocketFactory sf = registry.Lookup(host.GetSchemeName());

            if (sf == null)
            {
                throw new UnsupportedSchemeException(host.GetSchemeName() + " protocol is not supported"
                                                     );
            }
            if (!(sf is LayeredConnectionSocketFactory))
            {
                throw new UnsupportedSchemeException(host.GetSchemeName() + " protocol does not support connection upgrade"
                                                     );
            }
            LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory)sf;

            System.Net.Sockets.Socket sock = conn.GetSocket();
            int port = this.schemePortResolver.Resolve(host);

            sock = lsf.CreateLayeredSocket(sock, host.GetHostName(), port, context);
            conn.Bind(sock);
        }
 internal virtual HttpClientConnection GetConnection(HttpRoute route, object state
                                                     )
 {
     lock (this)
     {
         Asserts.Check(!this.shutdown, "Connection manager has been shut down");
         if (this.log.IsDebugEnabled())
         {
             this.log.Debug("Get connection for route " + route);
         }
         Asserts.Check(!this.leased, "Connection is still allocated");
         if (!LangUtils.Equals(this.route, route) || !LangUtils.Equals(this.state, state))
         {
             CloseConnection();
         }
         this.route = route;
         this.state = state;
         CheckExpiry();
         if (this.conn == null)
         {
             this.conn = this.connFactory.Create(route, this.connConfig);
         }
         this.leased = true;
         return(this.conn);
     }
 }
 public virtual void ReleaseConnection(HttpClientConnection conn, object state, long
                                       keepalive, TimeUnit tunit)
 {
     lock (this)
     {
         Args.NotNull(conn, "Connection");
         Asserts.Check(conn == this.conn, "Connection not obtained from this manager");
         if (this.log.IsDebugEnabled())
         {
             this.log.Debug("Releasing connection " + conn);
         }
         if (this.shutdown)
         {
             ShutdownConnection();
             return;
         }
         try
         {
             this.updated = Runtime.CurrentTimeMillis();
             if (!this.conn.IsOpen())
             {
                 this.conn   = null;
                 this.route  = null;
                 this.conn   = null;
                 this.expiry = long.MaxValue;
             }
             else
             {
                 this.state = state;
                 if (this.log.IsDebugEnabled())
                 {
                     string s;
                     if (keepalive > 0)
                     {
                         s = "for " + keepalive + " " + tunit;
                     }
                     else
                     {
                         s = "indefinitely";
                     }
                     this.log.Debug("Connection can be kept alive " + s);
                 }
                 if (keepalive > 0)
                 {
                     this.expiry = this.updated + tunit.ToMillis(keepalive);
                 }
                 else
                 {
                     this.expiry = long.MaxValue;
                 }
             }
         }
         finally
         {
             this.leased = false;
         }
     }
 }
Ejemplo n.º 4
0
 public virtual void ReleaseConnection(HttpClientConnection managedConn, object state
                                       , long keepalive, TimeUnit tunit)
 {
     Args.NotNull(managedConn, "Managed connection");
     lock (managedConn)
     {
         CPoolEntry entry = CPoolProxy.Detach(managedConn);
         if (entry == null)
         {
             return;
         }
         ManagedHttpClientConnection conn = entry.GetConnection();
         try
         {
             if (conn.IsOpen())
             {
                 entry.SetState(state);
                 entry.UpdateExpiry(keepalive, tunit != null ? tunit : TimeUnit.Milliseconds);
                 if (this.log.IsDebugEnabled())
                 {
                     string s;
                     if (keepalive > 0)
                     {
                         s = "for " + (double)keepalive / 1000 + " seconds";
                     }
                     else
                     {
                         s = "indefinitely";
                     }
                     this.log.Debug("Connection " + Format(entry) + " can be kept alive " + s);
                 }
             }
         }
         finally
         {
             this.pool.Release(entry, conn.IsOpen() && entry.IsRouteComplete());
             if (this.log.IsDebugEnabled())
             {
                 this.log.Debug("Connection released: " + Format(entry) + FormatStats(entry.GetRoute
                                                                                          ()));
             }
         }
     }
 }
 private void ShutdownConnection()
 {
     if (this.conn != null)
     {
         this.log.Debug("Shutting down connection");
         try
         {
             this.conn.Shutdown();
         }
         catch (IOException iox)
         {
             if (this.log.IsDebugEnabled())
             {
                 this.log.Debug("I/O exception shutting down connection", iox);
             }
         }
         this.conn = null;
     }
 }
 private void CloseConnection()
 {
     if (this.conn != null)
     {
         this.log.Debug("Closing connection");
         try
         {
             this.conn.Close();
         }
         catch (IOException iox)
         {
             if (this.log.IsDebugEnabled())
             {
                 this.log.Debug("I/O exception closing connection", iox);
             }
         }
         this.conn = null;
     }
 }
Ejemplo n.º 7
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void Connect(ManagedHttpClientConnection conn, HttpHost host, IPEndPoint
                                    localAddress, int connectTimeout, SocketConfig socketConfig, HttpContext context
                                    )
        {
            Lookup <ConnectionSocketFactory> registry = GetSocketFactoryRegistry(context);
            ConnectionSocketFactory          sf       = registry.Lookup(host.GetSchemeName());

            if (sf == null)
            {
                throw new UnsupportedSchemeException(host.GetSchemeName() + " protocol is not supported"
                                                     );
            }
            IPAddress[] addresses = this.dnsResolver.Resolve(host.GetHostName());
            int         port      = this.schemePortResolver.Resolve(host);

            for (int i = 0; i < addresses.Length; i++)
            {
                IPAddress address = addresses[i];
                bool      last    = i == addresses.Length - 1;
                System.Net.Sockets.Socket sock = sf.CreateSocket(context);
                sock.SetReuseAddress(socketConfig.IsSoReuseAddress());
                conn.Bind(sock);
                IPEndPoint remoteAddress = new IPEndPoint(address, port);
                if (this.log.IsDebugEnabled())
                {
                    this.log.Debug("Connecting to " + remoteAddress);
                }
                try
                {
                    sock.ReceiveTimeout = socketConfig.GetSoTimeout();
                    sock = sf.ConnectSocket(connectTimeout, sock, host, remoteAddress, localAddress,
                                            context);
                    sock.NoDelay = socketConfig.IsTcpNoDelay();
                    sock.SetKeepAlive(socketConfig.IsSoKeepAlive());
                    int linger = socketConfig.GetSoLinger();
                    if (linger >= 0)
                    {
                        sock.SetSoLinger(linger > 0, linger);
                    }
                    conn.Bind(sock);
                    return;
                }
                catch (SocketTimeoutException ex)
                {
                    if (last)
                    {
                        throw new ConnectTimeoutException(ex, host, addresses);
                    }
                }
                catch (ConnectException ex)
                {
                    if (last)
                    {
                        string msg = ex.Message;
                        if ("Connection timed out".Equals(msg))
                        {
                            throw new ConnectTimeoutException(ex, host, addresses);
                        }
                        else
                        {
                            throw new HttpHostConnectException(ex, host, addresses);
                        }
                    }
                }
                if (this.log.IsDebugEnabled())
                {
                    this.log.Debug("Connect to " + remoteAddress + " timed out. " + "Connection will be retried using another IP address"
                                   );
                }
            }
        }
Ejemplo n.º 8
0
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="Apache.Http.HttpException"></exception>
        public virtual Socket Tunnel(HttpHost proxy, HttpHost target, Credentials credentials
                                     )
        {
            Args.NotNull(proxy, "Proxy host");
            Args.NotNull(target, "Target host");
            Args.NotNull(credentials, "Credentials");
            HttpHost host = target;

            if (host.GetPort() <= 0)
            {
                host = new HttpHost(host.GetHostName(), 80, host.GetSchemeName());
            }
            HttpRoute route = new HttpRoute(host, this.requestConfig.GetLocalAddress(), proxy
                                            , false, RouteInfo.TunnelType.Tunnelled, RouteInfo.LayerType.Plain);
            ManagedHttpClientConnection conn = this.connFactory.Create(route, this.connectionConfig
                                                                       );
            HttpContext  context = new BasicHttpContext();
            HttpResponse response;
            IHttpRequest connect = new BasicHttpRequest("CONNECT", host.ToHostString(), HttpVersion
                                                        .Http11);
            BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();

            credsProvider.SetCredentials(new AuthScope(proxy), credentials);
            // Populate the execution context
            context.SetAttribute(HttpCoreContext.HttpTargetHost, target);
            context.SetAttribute(HttpCoreContext.HttpConnection, conn);
            context.SetAttribute(HttpCoreContext.HttpRequest, connect);
            context.SetAttribute(HttpClientContext.HttpRoute, route);
            context.SetAttribute(HttpClientContext.ProxyAuthState, this.proxyAuthState);
            context.SetAttribute(HttpClientContext.CredsProvider, credsProvider);
            context.SetAttribute(HttpClientContext.AuthschemeRegistry, this.authSchemeRegistry
                                 );
            context.SetAttribute(HttpClientContext.RequestConfig, this.requestConfig);
            this.requestExec.PreProcess(connect, this.httpProcessor, context);
            for (; ;)
            {
                if (!conn.IsOpen())
                {
                    Socket socket = Sharpen.Extensions.CreateSocket(proxy.GetHostName(), proxy.GetPort
                                                                        ());
                    conn.Bind(socket);
                }
                this.authenticator.GenerateAuthResponse(connect, this.proxyAuthState, context);
                response = this.requestExec.Execute(connect, conn, context);
                int status = response.GetStatusLine().GetStatusCode();
                if (status < 200)
                {
                    throw new HttpException("Unexpected response to CONNECT request: " + response.GetStatusLine
                                                ());
                }
                if (this.authenticator.IsAuthenticationRequested(proxy, response, this.proxyAuthStrategy
                                                                 , this.proxyAuthState, context))
                {
                    if (this.authenticator.HandleAuthChallenge(proxy, response, this.proxyAuthStrategy
                                                               , this.proxyAuthState, context))
                    {
                        // Retry request
                        if (this.reuseStrategy.KeepAlive(response, context))
                        {
                            // Consume response content
                            HttpEntity entity = response.GetEntity();
                            EntityUtils.Consume(entity);
                        }
                        else
                        {
                            conn.Close();
                        }
                        // discard previous auth header
                        connect.RemoveHeaders(AUTH.ProxyAuthResp);
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            int status_1 = response.GetStatusLine().GetStatusCode();

            if (status_1 > 299)
            {
                // Buffer response content
                HttpEntity entity = response.GetEntity();
                if (entity != null)
                {
                    response.SetEntity(new BufferedHttpEntity(entity));
                }
                conn.Close();
                throw new TunnelRefusedException("CONNECT refused by proxy: " + response.GetStatusLine
                                                     (), response);
            }
            return(conn.GetSocket());
        }