Search in sources :

Example 86 with ProtocolVersion

use of org.graylog.shaded.elasticsearch7.org.apache.http.ProtocolVersion in project android_frameworks_base by ParanoidAndroid.

the class SSLConnectionClosedByUserException method openConnection.

/**
     * Opens the connection to a http server or proxy.
     *
     * @return the opened low level connection
     * @throws IOException if the connection fails for any reason.
     */
@Override
AndroidHttpClientConnection openConnection(Request req) throws IOException {
    SSLSocket sslSock = null;
    if (mProxyHost != null) {
        // If we have a proxy set, we first send a CONNECT request
        // to the proxy; if the proxy returns 200 OK, we negotiate
        // a secure connection to the target server via the proxy.
        // If the request fails, we drop it, but provide the event
        // handler with the response status and headers. The event
        // handler is then responsible for cancelling the load or
        // issueing a new request.
        AndroidHttpClientConnection proxyConnection = null;
        Socket proxySock = null;
        try {
            proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort());
            proxySock.setSoTimeout(60 * 1000);
            proxyConnection = new AndroidHttpClientConnection();
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSocketBufferSize(params, 8192);
            proxyConnection.bind(proxySock, params);
        } catch (IOException e) {
            if (proxyConnection != null) {
                proxyConnection.close();
            }
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to establish a connection to the proxy";
            }
            throw new IOException(errorMessage);
        }
        StatusLine statusLine = null;
        int statusCode = 0;
        Headers headers = new Headers();
        try {
            BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString());
            // 400 Bad Request
            for (Header h : req.mHttpRequest.getAllHeaders()) {
                String headerName = h.getName().toLowerCase();
                if (headerName.startsWith("proxy") || headerName.equals("keep-alive") || headerName.equals("host")) {
                    proxyReq.addHeader(h);
                }
            }
            proxyConnection.sendRequestHeader(proxyReq);
            proxyConnection.flush();
            // a loop is a standard way of dealing with them
            do {
                statusLine = proxyConnection.parseResponseHeader(headers);
                statusCode = statusLine.getStatusCode();
            } while (statusCode < HttpStatus.SC_OK);
        } catch (ParseException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }
            throw new IOException(errorMessage);
        } catch (HttpException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }
            throw new IOException(errorMessage);
        } catch (IOException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to send a CONNECT request";
            }
            throw new IOException(errorMessage);
        }
        if (statusCode == HttpStatus.SC_OK) {
            try {
                sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true);
            } catch (IOException e) {
                if (sslSock != null) {
                    sslSock.close();
                }
                String errorMessage = e.getMessage();
                if (errorMessage == null) {
                    errorMessage = "failed to create an SSL socket";
                }
                throw new IOException(errorMessage);
            }
        } else {
            // if the code is not OK, inform the event handler
            ProtocolVersion version = statusLine.getProtocolVersion();
            req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase());
            req.mEventHandler.headers(headers);
            req.mEventHandler.endData();
            proxyConnection.close();
            // request needs to be dropped
            return null;
        }
    } else {
        // if we do not have a proxy, we simply connect to the host
        try {
            sslSock = (SSLSocket) getSocketFactory().createSocket(mHost.getHostName(), mHost.getPort());
            sslSock.setSoTimeout(SOCKET_TIMEOUT);
        } catch (IOException e) {
            if (sslSock != null) {
                sslSock.close();
            }
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to create an SSL socket";
            }
            throw new IOException(errorMessage);
        }
    }
    // do handshake and validate server certificates
    SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName());
    // Inform the user if there is a problem
    if (error != null) {
        // need to.
        synchronized (mSuspendLock) {
            mSuspended = true;
        }
        // don't hold the lock while calling out to the event handler
        boolean canHandle = req.getEventHandler().handleSslErrorRequest(error);
        if (!canHandle) {
            throw new IOException("failed to handle " + error);
        }
        synchronized (mSuspendLock) {
            if (mSuspended) {
                try {
                    // Put a limit on how long we are waiting; if the timeout
                    // expires (which should never happen unless you choose
                    // to ignore the SSL error dialog for a very long time),
                    // we wake up the thread and abort the request. This is
                    // to prevent us from stalling the network if things go
                    // very bad.
                    mSuspendLock.wait(10 * 60 * 1000);
                    if (mSuspended) {
                        // mSuspended is true if we have not had a chance to
                        // restart the connection yet (ie, the wait timeout
                        // has expired)
                        mSuspended = false;
                        mAborted = true;
                        if (HttpLog.LOGV) {
                            HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!");
                        }
                    }
                } catch (InterruptedException e) {
                // ignore
                }
            }
            if (mAborted) {
                // The user decided not to use this unverified connection
                // so close it immediately.
                sslSock.close();
                throw new SSLConnectionClosedByUserException("connection closed by the user");
            }
        }
    }
    // All went well, we have an open, verified connection.
    AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
    BasicHttpParams params = new BasicHttpParams();
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);
    conn.bind(sslSock, params);
    return conn;
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) IOException(java.io.IOException) ProtocolVersion(org.apache.http.ProtocolVersion) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) StatusLine(org.apache.http.StatusLine) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Header(org.apache.http.Header) HttpException(org.apache.http.HttpException) ParseException(org.apache.http.ParseException) BasicHttpParams(org.apache.http.params.BasicHttpParams) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket)

Example 87 with ProtocolVersion

use of org.graylog.shaded.elasticsearch7.org.apache.http.ProtocolVersion in project android_frameworks_base by ParanoidAndroid.

the class Request method readResponse.

/**
     * Receive a single http response.
     *
     * @param httpClientConnection the request to receive the response for.
     */
void readResponse(AndroidHttpClientConnection httpClientConnection) throws IOException, ParseException {
    // don't send cancelled requests
    if (mCancelled)
        return;
    StatusLine statusLine = null;
    boolean hasBody = false;
    httpClientConnection.flush();
    int statusCode = 0;
    Headers header = new Headers();
    do {
        statusLine = httpClientConnection.parseResponseHeader(header);
        statusCode = statusLine.getStatusCode();
    } while (statusCode < HttpStatus.SC_OK);
    if (HttpLog.LOGV)
        HttpLog.v("Request.readResponseStatus() " + statusLine.toString().length() + " " + statusLine);
    ProtocolVersion v = statusLine.getProtocolVersion();
    mEventHandler.status(v.getMajor(), v.getMinor(), statusCode, statusLine.getReasonPhrase());
    mEventHandler.headers(header);
    HttpEntity entity = null;
    hasBody = canResponseHaveBody(mHttpRequest, statusCode);
    if (hasBody)
        entity = httpClientConnection.receiveResponseEntity(header);
    // restrict the range request to the servers claiming that they are
    // accepting ranges in bytes
    boolean supportPartialContent = "bytes".equalsIgnoreCase(header.getAcceptRanges());
    if (entity != null) {
        InputStream is = entity.getContent();
        // process gzip content encoding
        Header contentEncoding = entity.getContentEncoding();
        InputStream nis = null;
        byte[] buf = null;
        int count = 0;
        try {
            if (contentEncoding != null && contentEncoding.getValue().equals("gzip")) {
                nis = new GZIPInputStream(is);
            } else {
                nis = is;
            }
            /* accumulate enough data to make it worth pushing it
                 * up the stack */
            buf = mConnection.getBuf();
            int len = 0;
            int lowWater = buf.length / 2;
            while (len != -1) {
                synchronized (this) {
                    while (mLoadingPaused) {
                        // filled its internal buffers.
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            HttpLog.e("Interrupted exception whilst " + "network thread paused at WebCore's request." + " " + e.getMessage());
                        }
                    }
                }
                len = nis.read(buf, count, buf.length - count);
                if (len != -1) {
                    count += len;
                    if (supportPartialContent)
                        mReceivedBytes += len;
                }
                if (len == -1 || count >= lowWater) {
                    if (HttpLog.LOGV)
                        HttpLog.v("Request.readResponse() " + count);
                    mEventHandler.data(buf, count);
                    count = 0;
                }
            }
        } catch (EOFException e) {
            /* InflaterInputStream throws an EOFException when the
                   server truncates gzipped content.  Handle this case
                   as we do truncated non-gzipped content: no error */
            if (count > 0) {
                // if there is uncommited content, we should commit them
                mEventHandler.data(buf, count);
            }
            if (HttpLog.LOGV)
                HttpLog.v("readResponse() handling " + e);
        } catch (IOException e) {
            // don't throw if we have a non-OK status code
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_PARTIAL_CONTENT) {
                if (supportPartialContent && count > 0) {
                    // if there is uncommited content, we should commit them
                    // as we will continue the request
                    mEventHandler.data(buf, count);
                }
                throw e;
            }
        } finally {
            if (nis != null) {
                nis.close();
            }
        }
    }
    mConnection.setCanPersist(entity, statusLine.getProtocolVersion(), header.getConnectionType());
    mEventHandler.endData();
    complete();
    if (HttpLog.LOGV)
        HttpLog.v("Request.readResponse(): done " + mHost.getSchemeName() + "://" + getHostPort() + mPath);
}
Also used : HttpEntity(org.apache.http.HttpEntity) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ProtocolVersion(org.apache.http.ProtocolVersion) StatusLine(org.apache.http.StatusLine) GZIPInputStream(java.util.zip.GZIPInputStream) Header(org.apache.http.Header) EOFException(java.io.EOFException)

Example 88 with ProtocolVersion

use of org.graylog.shaded.elasticsearch7.org.apache.http.ProtocolVersion in project XobotOS by xamarin.

the class HttpService method handleRequest.

public void handleRequest(final HttpServerConnection conn, final HttpContext context) throws IOException, HttpException {
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    HttpResponse response = null;
    try {
        HttpRequest request = conn.receiveRequestHeader();
        request.setParams(new DefaultedHttpParams(request.getParams(), this.params));
        ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
        if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
            // Downgrade protocol version if greater than HTTP/1.1 
            ver = HttpVersion.HTTP_1_1;
        }
        if (request instanceof HttpEntityEnclosingRequest) {
            if (((HttpEntityEnclosingRequest) request).expectContinue()) {
                response = this.responseFactory.newHttpResponse(ver, HttpStatus.SC_CONTINUE, context);
                response.setParams(new DefaultedHttpParams(response.getParams(), this.params));
                if (this.expectationVerifier != null) {
                    try {
                        this.expectationVerifier.verify(request, response, context);
                    } catch (HttpException ex) {
                        response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
                        response.setParams(new DefaultedHttpParams(response.getParams(), this.params));
                        handleException(ex, response);
                    }
                }
                if (response.getStatusLine().getStatusCode() < 200) {
                    // Send 1xx response indicating the server expections
                    // have been met
                    conn.sendResponseHeader(response);
                    conn.flush();
                    response = null;
                    conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
                }
            } else {
                conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
            }
        }
        if (response == null) {
            response = this.responseFactory.newHttpResponse(ver, HttpStatus.SC_OK, context);
            response.setParams(new DefaultedHttpParams(response.getParams(), this.params));
            context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
            context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
            this.processor.process(request, context);
            doService(request, response, context);
        }
        // Make sure the request content is fully consumed
        if (request instanceof HttpEntityEnclosingRequest) {
            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            if (entity != null) {
                entity.consumeContent();
            }
        }
    } catch (HttpException ex) {
        response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
        response.setParams(new DefaultedHttpParams(response.getParams(), this.params));
        handleException(ex, response);
    }
    this.processor.process(response, context);
    conn.sendResponseHeader(response);
    conn.sendResponseEntity(response);
    conn.flush();
    if (!this.connStrategy.keepAlive(response, context)) {
        conn.close();
    }
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpEntity(org.apache.http.HttpEntity) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) HttpResponse(org.apache.http.HttpResponse) HttpException(org.apache.http.HttpException) ProtocolVersion(org.apache.http.ProtocolVersion) DefaultedHttpParams(org.apache.http.params.DefaultedHttpParams)

Example 89 with ProtocolVersion

use of org.graylog.shaded.elasticsearch7.org.apache.http.ProtocolVersion in project XobotOS by xamarin.

the class ResponseContent method process.

public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (response.containsHeader(HTTP.TRANSFER_ENCODING)) {
        throw new ProtocolException("Transfer-encoding header already present");
    }
    if (response.containsHeader(HTTP.CONTENT_LEN)) {
        throw new ProtocolException("Content-Length header already present");
    }
    ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        long len = entity.getContentLength();
        if (entity.isChunked() && !ver.lessEquals(HttpVersion.HTTP_1_0)) {
            response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);
        } else if (len >= 0) {
            response.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength()));
        }
        // Specify a content type if known
        if (entity.getContentType() != null && !response.containsHeader(HTTP.CONTENT_TYPE)) {
            response.addHeader(entity.getContentType());
        }
        // Specify a content encoding if known
        if (entity.getContentEncoding() != null && !response.containsHeader(HTTP.CONTENT_ENCODING)) {
            response.addHeader(entity.getContentEncoding());
        }
    } else {
        int status = response.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED && status != HttpStatus.SC_RESET_CONTENT) {
            response.addHeader(HTTP.CONTENT_LEN, "0");
        }
    }
}
Also used : ProtocolException(org.apache.http.ProtocolException) HttpEntity(org.apache.http.HttpEntity) ProtocolVersion(org.apache.http.ProtocolVersion)

Example 90 with ProtocolVersion

use of org.graylog.shaded.elasticsearch7.org.apache.http.ProtocolVersion in project XobotOS by xamarin.

the class BasicLineParser method parseRequestLine.

/**
     * Parses a request line.
     *
     * @param buffer    a buffer holding the line to parse
     *
     * @return  the parsed request line
     *
     * @throws ParseException        in case of a parse error
     */
public RequestLine parseRequestLine(final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException {
    if (buffer == null) {
        throw new IllegalArgumentException("Char array buffer may not be null");
    }
    if (cursor == null) {
        throw new IllegalArgumentException("Parser cursor may not be null");
    }
    int indexFrom = cursor.getPos();
    int indexTo = cursor.getUpperBound();
    try {
        skipWhitespace(buffer, cursor);
        int i = cursor.getPos();
        int blank = buffer.indexOf(' ', i, indexTo);
        if (blank < 0) {
            throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo));
        }
        String method = buffer.substringTrimmed(i, blank);
        cursor.updatePos(blank);
        skipWhitespace(buffer, cursor);
        i = cursor.getPos();
        blank = buffer.indexOf(' ', i, indexTo);
        if (blank < 0) {
            throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo));
        }
        String uri = buffer.substringTrimmed(i, blank);
        cursor.updatePos(blank);
        ProtocolVersion ver = parseProtocolVersion(buffer, cursor);
        skipWhitespace(buffer, cursor);
        if (!cursor.atEnd()) {
            throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo));
        }
        return createRequestLine(method, uri, ver);
    } catch (IndexOutOfBoundsException e) {
        throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo));
    }
}
Also used : ParseException(org.apache.http.ParseException) ProtocolVersion(org.apache.http.ProtocolVersion)

Aggregations

ProtocolVersion (org.apache.http.ProtocolVersion)143 BasicStatusLine (org.apache.http.message.BasicStatusLine)67 Test (org.junit.Test)53 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)50 StatusLine (org.apache.http.StatusLine)44 HttpResponse (org.apache.http.HttpResponse)32 HttpEntity (org.apache.http.HttpEntity)31 Header (org.apache.http.Header)25 StringEntity (org.apache.http.entity.StringEntity)25 IOException (java.io.IOException)18 BasicHeader (org.apache.http.message.BasicHeader)15 URL (java.net.URL)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 HttpURLConnection (java.net.HttpURLConnection)13 HashMap (java.util.HashMap)13 List (java.util.List)13 ParseException (org.apache.http.ParseException)13 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)13 HttpHost (org.apache.http.HttpHost)12 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)11