Search in sources :

Example 1 with HttpResponse

use of org.openecard.apache.http.HttpResponse in project open-ecard by ecsec.

the class StreamHttpClientConnection method receiveResponseHeader.

@Override
public HttpResponse receiveResponseHeader() throws HttpException, IOException {
    assertOpen();
    final HttpResponse response = this.responseParser.parse();
    if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK) {
        incrementResponseCount();
    }
    return response;
}
Also used : HttpResponse(org.openecard.apache.http.HttpResponse)

Example 2 with HttpResponse

use of org.openecard.apache.http.HttpResponse in project open-ecard by ecsec.

the class HttpGetTask method getRequest.

private void getRequest() throws IOException, ConnectionError, URISyntaxException, HttpException {
    TlsConnectionHandler tlsHandler = new TlsConnectionHandler(dispatcher, tokenRequest, connectionHandle);
    tlsHandler.setUpClient();
    // connect the tls endpoint and make a get request
    TlsClientProtocol handler = tlsHandler.createTlsConnection();
    // set up connection to endpoint
    InputStream in = handler.getInputStream();
    OutputStream out = handler.getOutputStream();
    StreamHttpClientConnection conn = new StreamHttpClientConnection(in, out);
    // prepare HTTP connection
    HttpContext ctx = new BasicHttpContext();
    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    DefaultConnectionReuseStrategy reuse = new DefaultConnectionReuseStrategy();
    // prepare request
    String resource = tlsHandler.getResource();
    BasicHttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("GET", resource);
    HttpRequestHelper.setDefaultHeader(req, tlsHandler.getServerAddress());
    req.setHeader("Accept", "text/html, */*;q=0.8");
    req.setHeader("Accept-Charset", "utf-8, *;q=0.8");
    HttpUtils.dumpHttpRequest(LOG, req);
    // send request and receive response
    HttpResponse response = httpexecutor.execute(req, conn, ctx);
    int statusCode = response.getStatusLine().getStatusCode();
    conn.receiveResponseEntity(response);
    HttpEntity entity = response.getEntity();
    byte[] entityData = FileUtils.toByteArray(entity.getContent());
    HttpUtils.dumpHttpResponse(LOG, response, entityData);
    conn.close();
    if (statusCode < 200 || statusCode > 299) {
        throw new ConnectionError(WRONG_SERVER_RESULT, statusCode);
    }
}
Also used : HttpRequestExecutor(org.openecard.apache.http.protocol.HttpRequestExecutor) HttpEntity(org.openecard.apache.http.HttpEntity) InputStream(java.io.InputStream) BasicHttpContext(org.openecard.apache.http.protocol.BasicHttpContext) OutputStream(java.io.OutputStream) TlsClientProtocol(org.openecard.bouncycastle.tls.TlsClientProtocol) BasicHttpContext(org.openecard.apache.http.protocol.BasicHttpContext) HttpContext(org.openecard.apache.http.protocol.HttpContext) DefaultConnectionReuseStrategy(org.openecard.apache.http.impl.DefaultConnectionReuseStrategy) HttpResponse(org.openecard.apache.http.HttpResponse) StreamHttpClientConnection(org.openecard.transport.httpcore.StreamHttpClientConnection) BasicHttpEntityEnclosingRequest(org.openecard.apache.http.message.BasicHttpEntityEnclosingRequest)

Example 3 with HttpResponse

use of org.openecard.apache.http.HttpResponse in project open-ecard by ecsec.

the class ResourceContext method getStreamInt.

private static ResourceContext getStreamInt(URL url, CertificateValidator v, List<Pair<URL, TlsServerCertificate>> serverCerts, int maxRedirects) throws IOException, ResourceException, ValidationError, InvalidAddressException {
    try {
        DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY);
        CookieManager cManager = (CookieManager) dynCtx.get(TR03112Keys.COOKIE_MANAGER);
        LOG.info("Trying to load resource from: {}", url);
        if (maxRedirects == 0) {
            throw new ResourceException(MAX_REDIRECTS);
        }
        maxRedirects--;
        String protocol = url.getProtocol();
        String hostname = url.getHost();
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
        }
        String resource = url.getFile();
        resource = resource.isEmpty() ? "/" : resource;
        if (!"https".equals(protocol)) {
            throw new InvalidAddressException(INVALID_ADDRESS);
        }
        // open a TLS connection, retrieve the server certificate and save it
        TlsClientProtocol h;
        DynamicAuthentication tlsAuth = new DynamicAuthentication(hostname);
        // add PKIX validator if not doin nPA auth
        if (isPKIXVerify()) {
            tlsAuth.addCertificateVerifier(new JavaSecVerifier());
        }
        // FIXME: validate certificate chain as soon as a usable solution exists for the trust problem
        // tlsAuth.setCertificateVerifier(new JavaSecVerifier());
        TlsCrypto crypto = new BcTlsCrypto(ReusableSecureRandom.getInstance());
        ClientCertTlsClient tlsClient = new ClientCertDefaultTlsClient(crypto, hostname, true);
        tlsClient.setAuthentication(tlsAuth);
        // connect tls client
        tlsClient.setClientVersion(ProtocolVersion.TLSv12);
        Socket socket = ProxySettings.getDefault().getSocket(protocol, hostname, port);
        h = new TlsClientProtocol(socket.getInputStream(), socket.getOutputStream());
        LOG.debug("Performing TLS handshake.");
        h.connect(tlsClient);
        LOG.debug("TLS handshake performed.");
        serverCerts.add(new Pair<>(url, tlsAuth.getServerCertificate()));
        // check result
        CertificateValidator.VerifierResult verifyResult = v.validate(url, tlsAuth.getServerCertificate());
        if (verifyResult == CertificateValidator.VerifierResult.FINISH) {
            List<Pair<URL, TlsServerCertificate>> pairs = Collections.unmodifiableList(serverCerts);
            return new ResourceContext(tlsClient, h, pairs);
        }
        StreamHttpClientConnection conn = new StreamHttpClientConnection(h.getInputStream(), h.getOutputStream());
        HttpContext ctx = new BasicHttpContext();
        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        BasicHttpEntityEnclosingRequest req = new BasicHttpEntityEnclosingRequest("GET", resource);
        HttpRequestHelper.setDefaultHeader(req, url);
        req.setHeader("Accept", "text/xml, */*;q=0.8");
        req.setHeader("Accept-Charset", "utf-8, *;q=0.8");
        setCookieHeader(req, cManager, url);
        HttpUtils.dumpHttpRequest(LOG, req);
        LOG.debug("Sending HTTP request.");
        HttpResponse response = httpexecutor.execute(req, conn, ctx);
        storeCookies(response, cManager, url);
        LOG.debug("HTTP response received.");
        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();
        String reason = status.getReasonPhrase();
        HttpUtils.dumpHttpResponse(LOG, response, null);
        HttpEntity entity = null;
        boolean finished = false;
        if (TR03112Utils.isRedirectStatusCode(statusCode)) {
            Header[] headers = response.getHeaders("Location");
            if (headers.length > 0) {
                String uri = headers[0].getValue();
                url = new URL(uri);
            } else {
                // FIXME: refactor exception handling
                throw new ResourceException(MISSING_LOCATION_HEADER);
            }
        } else if (statusCode >= 400) {
            // according to the HTTP RFC, codes greater than 400 signal errors
            LOG.debug("Received a result code {} '{}' from server.", statusCode, reason);
            throw new InvalidResultStatus(LANG.translationForKey(INVALID_RESULT_STATUS, statusCode, reason));
        } else {
            if (verifyResult == CertificateValidator.VerifierResult.CONTINUE) {
                throw new InvalidAddressException(INVALID_REFRESH_ADDRESS_NOSOP);
            } else {
                conn.receiveResponseEntity(response);
                entity = response.getEntity();
                finished = true;
            }
        }
        // follow next redirect or finish?
        if (finished) {
            assert (entity != null);
            ResourceContext result = new ResourceContext(tlsClient, h, serverCerts);
            LimitedInputStream is = new LimitedInputStream(entity.getContent());
            result.setStream(is);
            return result;
        } else {
            h.close();
            return getStreamInt(url, v, serverCerts, maxRedirects);
        }
    } catch (URISyntaxException ex) {
        throw new IOException(LANG.translationForKey(FAILED_PROXY), ex);
    } catch (HttpException ex) {
        // don't translate this, it is handled in the ActivationAction
        throw new IOException("Invalid HTTP message received.", ex);
    }
}
Also used : HttpRequestExecutor(org.openecard.apache.http.protocol.HttpRequestExecutor) HttpEntity(org.openecard.apache.http.HttpEntity) BasicHttpContext(org.openecard.apache.http.protocol.BasicHttpContext) LimitedInputStream(org.openecard.common.io.LimitedInputStream) TlsClientProtocol(org.openecard.bouncycastle.tls.TlsClientProtocol) URISyntaxException(java.net.URISyntaxException) ClientCertTlsClient(org.openecard.crypto.tls.ClientCertTlsClient) StreamHttpClientConnection(org.openecard.transport.httpcore.StreamHttpClientConnection) URL(java.net.URL) TlsCrypto(org.openecard.bouncycastle.tls.crypto.TlsCrypto) BcTlsCrypto(org.openecard.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto) HttpException(org.openecard.apache.http.HttpException) CookieManager(org.openecard.transport.httpcore.cookies.CookieManager) JavaSecVerifier(org.openecard.crypto.tls.verify.JavaSecVerifier) InvalidResultStatus(org.openecard.transport.httpcore.InvalidResultStatus) Pair(org.openecard.common.util.Pair) BasicHttpEntityEnclosingRequest(org.openecard.apache.http.message.BasicHttpEntityEnclosingRequest) BasicHttpContext(org.openecard.apache.http.protocol.BasicHttpContext) HttpContext(org.openecard.apache.http.protocol.HttpContext) ClientCertDefaultTlsClient(org.openecard.crypto.tls.ClientCertDefaultTlsClient) HttpResponse(org.openecard.apache.http.HttpResponse) BcTlsCrypto(org.openecard.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto) IOException(java.io.IOException) StatusLine(org.openecard.apache.http.StatusLine) Header(org.openecard.apache.http.Header) DynamicAuthentication(org.openecard.crypto.tls.auth.DynamicAuthentication) InvalidAddressException(org.openecard.binding.tctoken.ex.InvalidAddressException) Socket(java.net.Socket) DynamicContext(org.openecard.common.DynamicContext)

Example 4 with HttpResponse

use of org.openecard.apache.http.HttpResponse in project open-ecard by ecsec.

the class HttpAppPluginActionHandler method createHTTPResponseFromBindingResult.

private HttpResponse createHTTPResponseFromBindingResult(BindingResult bindingResult) {
    BindingResultCode resultCode = bindingResult.getResultCode();
    LOG.debug("Recieved BindingResult with ResultCode {}", resultCode);
    HttpResponse response;
    switch(resultCode) {
        case OK:
            response = new Http11Response(HttpStatus.SC_OK);
            break;
        case REDIRECT:
            response = new Http11Response(HttpStatus.SC_SEE_OTHER);
            String location = bindingResult.getAuxResultData().get(AuxDataKeys.REDIRECT_LOCATION);
            if (location != null && !location.isEmpty()) {
                response.addHeader(HeaderTypes.LOCATION.fieldName(), location);
            } else {
                // redirect requires a location field
                LOG.error("No redirect address available in given BindingResult instance.");
                response = new Http11Response(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            }
            break;
        case WRONG_PARAMETER:
        case MISSING_PARAMETER:
            response = new Http11Response(HttpStatus.SC_BAD_REQUEST);
            break;
        case INTERNAL_ERROR:
            response = new Http11Response(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            break;
        case RESOURCE_UNAVAILABLE:
        case DEPENDING_HOST_UNREACHABLE:
            response = new Http11Response(HttpStatus.SC_NOT_FOUND);
            break;
        case RESOURCE_LOCKED:
            response = new Http11Response(HttpStatus.SC_LOCKED);
            break;
        case TIMEOUT:
            response = new Http11Response(HttpStatus.SC_GATEWAY_TIMEOUT);
            break;
        case TOO_MANY_REQUESTS:
            // Code for TOO MANY REQUESTS is 429 according to RFC 6585
            response = new Http11Response(429);
            break;
        default:
            LOG.error("Untreated result code: " + resultCode);
            response = new Http11Response(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }
    addHTTPEntity(response, bindingResult);
    return response;
}
Also used : HttpResponse(org.openecard.apache.http.HttpResponse) BindingResultCode(org.openecard.addon.bind.BindingResultCode) Http11Response(org.openecard.control.binding.http.common.Http11Response)

Example 5 with HttpResponse

use of org.openecard.apache.http.HttpResponse in project open-ecard by ecsec.

the class HttpAppPluginActionHandler method handle.

@Override
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext context) throws HttpException, IOException {
    LOG.debug("HTTP request: {}", httpRequest.toString());
    CORSFilter corsFilter = new CORSFilter();
    HttpResponse corsResp = corsFilter.preProcess(httpRequest, context);
    if (corsResp != null) {
        // CORS Response created, return it to the caller
        // This is either a preflight response, or a block, because the Origin mismatched
        LOG.debug("HTTP response: {}", corsResp);
        Http11Response.copyHttpResponse(corsResp, httpResponse);
        return;
    }
    // deconstruct request uri
    String uri = httpRequest.getRequestLine().getUri();
    URI requestURI = URI.create(uri);
    String path = requestURI.getPath();
    // remove leading '/'
    String resourceName = path.substring(1, path.length());
    // find suitable addon
    try {
        AppPluginAction action = selector.getAppPluginAction(resourceName);
        String rawQuery = requestURI.getRawQuery();
        Map<String, String> queries = new HashMap<>(0);
        if (rawQuery != null) {
            queries = HttpRequestLineUtils.transform(rawQuery);
        }
        RequestBody body = null;
        if (httpRequest instanceof HttpEntityEnclosingRequest) {
            LOG.debug("Request contains an entity.");
            body = getRequestBody(httpRequest, resourceName);
        }
        Headers headers = readReqHeaders(httpRequest);
        // and add some special values to the header section
        headers.setHeader(METHOD_HDR, httpRequest.getRequestLine().getMethod());
        BindingResult bindingResult = action.execute(body, queries, headers, null);
        HttpResponse response = createHTTPResponseFromBindingResult(bindingResult);
        response.setParams(httpRequest.getParams());
        LOG.debug("HTTP response: {}", response);
        Http11Response.copyHttpResponse(response, httpResponse);
        // CORS post processing
        corsFilter.postProcess(httpRequest, httpResponse, context);
    } catch (AddonNotFoundException ex) {
        if (path.equals("/")) {
            new IndexHandler().handle(httpRequest, httpResponse, context);
        } else if (path.startsWith("/")) {
            new FileHandler(new DocumentRoot("/www", "/www-files")).handle(httpRequest, httpResponse, context);
        } else {
            new DefaultHandler().handle(httpRequest, httpResponse, context);
        }
    }
}
Also used : BindingResult(org.openecard.addon.bind.BindingResult) HashMap(java.util.HashMap) AddonNotFoundException(org.openecard.addon.AddonNotFoundException) Headers(org.openecard.addon.bind.Headers) DocumentRoot(org.openecard.control.binding.http.common.DocumentRoot) HttpResponse(org.openecard.apache.http.HttpResponse) AppPluginAction(org.openecard.addon.bind.AppPluginAction) URI(java.net.URI) HttpEntityEnclosingRequest(org.openecard.apache.http.HttpEntityEnclosingRequest) RequestBody(org.openecard.addon.bind.RequestBody)

Aggregations

HttpResponse (org.openecard.apache.http.HttpResponse)10 HttpEntity (org.openecard.apache.http.HttpEntity)5 IOException (java.io.IOException)4 HttpException (org.openecard.apache.http.HttpException)4 BasicHttpEntityEnclosingRequest (org.openecard.apache.http.message.BasicHttpEntityEnclosingRequest)4 BasicHttpContext (org.openecard.apache.http.protocol.BasicHttpContext)4 HttpContext (org.openecard.apache.http.protocol.HttpContext)4 HttpRequestExecutor (org.openecard.apache.http.protocol.HttpRequestExecutor)4 StringEntity (org.openecard.apache.http.entity.StringEntity)3 DefaultConnectionReuseStrategy (org.openecard.apache.http.impl.DefaultConnectionReuseStrategy)3 Http11Response (org.openecard.control.binding.http.common.Http11Response)3 StreamHttpClientConnection (org.openecard.transport.httpcore.StreamHttpClientConnection)3 Header (org.openecard.apache.http.Header)2 ContentType (org.openecard.apache.http.entity.ContentType)2 TlsClientProtocol (org.openecard.bouncycastle.tls.TlsClientProtocol)2 StartPAOSResponse (iso.std.iso_iec._24727.tech.schema.StartPAOSResponse)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1