Search in sources :

Example 11 with HttpVersion

use of io.netty.handler.codec.http.HttpVersion in project vert.x by eclipse.

the class ServerConnection method processMessage.

private void processMessage(Object msg) {
    if (msg instanceof HttpObject) {
        HttpObject obj = (HttpObject) msg;
        DecoderResult result = obj.decoderResult();
        if (result.isFailure()) {
            Throwable cause = result.cause();
            if (cause instanceof TooLongFrameException) {
                String causeMsg = cause.getMessage();
                HttpVersion version;
                if (msg instanceof HttpRequest) {
                    version = ((HttpRequest) msg).protocolVersion();
                } else if (currentRequest != null) {
                    version = currentRequest.version() == io.vertx.core.http.HttpVersion.HTTP_1_0 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;
                } else {
                    version = HttpVersion.HTTP_1_1;
                }
                HttpResponseStatus status = causeMsg.startsWith("An HTTP line is larger than") ? HttpResponseStatus.REQUEST_URI_TOO_LONG : HttpResponseStatus.BAD_REQUEST;
                DefaultFullHttpResponse resp = new DefaultFullHttpResponse(version, status);
                writeToChannel(resp);
            }
            // That will close the connection as it is considered as unusable
            channel.pipeline().fireExceptionCaught(result.cause());
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;
            if (server.options().isHandle100ContinueAutomatically()) {
                if (HttpHeaders.is100ContinueExpected(request)) {
                    write100Continue();
                }
            }
            HttpServerResponseImpl resp = new HttpServerResponseImpl(vertx, this, request);
            HttpServerRequestImpl req = new HttpServerRequestImpl(this, request, resp);
            handleRequest(req, resp);
        }
        if (msg instanceof HttpContent) {
            HttpContent chunk = (HttpContent) msg;
            if (chunk.content().isReadable()) {
                Buffer buff = Buffer.buffer(chunk.content());
                handleChunk(buff);
            }
            //TODO chunk trailers
            if (msg instanceof LastHttpContent) {
                if (!paused) {
                    handleEnd();
                } else {
                    // Requeue
                    pending.add(LastHttpContent.EMPTY_LAST_CONTENT);
                }
            }
        }
    } else if (msg instanceof WebSocketFrameInternal) {
        WebSocketFrameInternal frame = (WebSocketFrameInternal) msg;
        handleWsFrame(frame);
    }
    checkNextTick();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) WebSocketFrameInternal(io.vertx.core.http.impl.ws.WebSocketFrameInternal) DecoderResult(io.netty.handler.codec.DecoderResult) HttpVersion(io.netty.handler.codec.http.HttpVersion)

Example 12 with HttpVersion

use of io.netty.handler.codec.http.HttpVersion in project xipki by xipki.

the class HttpProxyServlet method service.

@Override
public FullHttpResponse service(FullHttpRequest request, ServletURI servletUri, SSLSession sslSession, SslReverseProxyMode sslReverseProxyMode) throws Exception {
    HttpVersion version = request.protocolVersion();
    HttpMethod method = request.method();
    if (method != HttpMethod.POST) {
        return createErrorResponse(version, METHOD_NOT_ALLOWED);
    }
    try {
        if (!REQUEST_MIMETYPE.equalsIgnoreCase(request.headers().get("Content-Type"))) {
            return createErrorResponse(version, HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
        }
        if (localP11CryptServicePool == null) {
            LOG.error("localP11CryptService in servlet not configured");
            return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
        byte[] requestBytes = readContent(request);
        byte[] responseBytes = responder.processRequest(localP11CryptServicePool, requestBytes);
        return createOKResponse(version, RESPONSE_MIMETYPE, responseBytes);
    } catch (Throwable th) {
        if (th instanceof EOFException) {
            LogUtil.warn(LOG, th, "connection reset by peer");
        } else {
            LOG.error("Throwable thrown, this should not happen.", th);
        }
        return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : EOFException(java.io.EOFException) HttpVersion(io.netty.handler.codec.http.HttpVersion) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 13 with HttpVersion

use of io.netty.handler.codec.http.HttpVersion in project xipki by xipki.

the class HttpCmpServlet method service.

@Override
public FullHttpResponse service(FullHttpRequest request, ServletURI servletUri, SSLSession sslSession, SslReverseProxyMode sslReverseProxyMode) throws Exception {
    HttpVersion httpVersion = request.protocolVersion();
    HttpMethod method = request.method();
    if (method != HttpMethod.POST) {
        return createErrorResponse(httpVersion, HttpResponseStatus.METHOD_NOT_ALLOWED);
    }
    X509Certificate clientCert = getClientCert(request, sslSession, sslReverseProxyMode);
    AuditService auditService = auditServiceRegister.getAuditService();
    AuditEvent event = new AuditEvent(new Date());
    event.setApplicationName(CaAuditConstants.APPNAME);
    event.setName(CaAuditConstants.NAME_PERF);
    event.addEventData(CaAuditConstants.NAME_reqType, RequestType.CMP.name());
    AuditLevel auditLevel = AuditLevel.INFO;
    AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
    String auditMessage = null;
    try {
        if (responderManager == null) {
            String message = "responderManager in servlet not configured";
            LOG.error(message);
            throw new HttpRespAuditException(HttpResponseStatus.INTERNAL_SERVER_ERROR, message, AuditLevel.ERROR, AuditStatus.FAILED);
        }
        String reqContentType = request.headers().get("Content-Type");
        if (!CT_REQUEST.equalsIgnoreCase(reqContentType)) {
            String message = "unsupported media type " + reqContentType;
            throw new HttpRespAuditException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE, message, AuditLevel.INFO, AuditStatus.FAILED);
        }
        String caName = null;
        X509CaCmpResponder responder = null;
        if (servletUri.getPath().length() > 1) {
            // skip the first char which is always '/'
            String caAlias = servletUri.getPath().substring(1);
            caName = responderManager.getCaNameForAlias(caAlias);
            if (caName == null) {
                caName = caAlias.toLowerCase();
            }
            responder = responderManager.getX509CaResponder(caName);
        }
        if (caName == null || responder == null || !responder.isOnService()) {
            String message;
            if (caName == null) {
                message = "no CA is specified";
            } else if (responder == null) {
                message = "unknown CA '" + caName + "'";
            } else {
                message = "CA '" + caName + "' is out of service";
            }
            LOG.warn(message);
            throw new HttpRespAuditException(HttpResponseStatus.NOT_FOUND, message, AuditLevel.INFO, AuditStatus.FAILED);
        }
        event.addEventData(CaAuditConstants.NAME_ca, responder.getCaName());
        byte[] reqContent = readContent(request);
        PKIMessage pkiReq;
        try {
            pkiReq = PKIMessage.getInstance(reqContent);
        } catch (Exception ex) {
            LogUtil.error(LOG, ex, "could not parse the request (PKIMessage)");
            throw new HttpRespAuditException(HttpResponseStatus.BAD_REQUEST, "bad request", AuditLevel.INFO, AuditStatus.FAILED);
        }
        PKIMessage pkiResp = responder.processPkiMessage(pkiReq, clientCert, event);
        byte[] encodedPkiResp = pkiResp.getEncoded();
        return createOKResponse(httpVersion, CT_RESPONSE, encodedPkiResp);
    } catch (HttpRespAuditException ex) {
        auditStatus = ex.getAuditStatus();
        auditLevel = ex.getAuditLevel();
        auditMessage = ex.getAuditMessage();
        return createErrorResponse(httpVersion, ex.getHttpStatus());
    } catch (Throwable th) {
        if (th instanceof EOFException) {
            LogUtil.warn(LOG, th, "connection reset by peer");
        } else {
            LOG.error("Throwable thrown, this should not happen!", th);
        }
        auditLevel = AuditLevel.ERROR;
        auditStatus = AuditStatus.FAILED;
        auditMessage = "internal error";
        return createErrorResponse(httpVersion, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } finally {
        audit(auditService, event, auditLevel, auditStatus, auditMessage);
    }
}
Also used : PKIMessage(org.bouncycastle.asn1.cmp.PKIMessage) AuditLevel(org.xipki.audit.AuditLevel) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) EOFException(java.io.EOFException) AuditStatus(org.xipki.audit.AuditStatus) X509CaCmpResponder(org.xipki.ca.server.api.X509CaCmpResponder) EOFException(java.io.EOFException) AuditEvent(org.xipki.audit.AuditEvent) HttpVersion(io.netty.handler.codec.http.HttpVersion) AuditService(org.xipki.audit.AuditService) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Example 14 with HttpVersion

use of io.netty.handler.codec.http.HttpVersion in project xipki by xipki.

the class HttpScepServlet method service.

@Override
public FullHttpResponse service(FullHttpRequest request, ServletURI servletUri, SSLSession sslSession, SslReverseProxyMode sslReverseProxyMode) throws Exception {
    HttpVersion version = request.protocolVersion();
    HttpMethod method = request.method();
    boolean viaPost;
    if (method == HttpMethod.POST) {
        viaPost = true;
    } else if (method == HttpMethod.GET) {
        viaPost = false;
    } else {
        return createErrorResponse(version, HttpResponseStatus.METHOD_NOT_ALLOWED);
    }
    String scepName = null;
    String certProfileName = null;
    if (servletUri.getPath().length() > 1) {
        String scepPath = servletUri.getPath();
        if (scepPath.endsWith(CGI_PROGRAM)) {
            // skip also the first char (which is always '/')
            String path = scepPath.substring(1, scepPath.length() - CGI_PROGRAM_LEN);
            String[] tokens = path.split("/");
            if (tokens.length == 2) {
                scepName = tokens[0];
                certProfileName = tokens[1].toLowerCase();
            }
        }
    // end if
    }
    if (scepName == null || certProfileName == null) {
        return createErrorResponse(version, HttpResponseStatus.NOT_FOUND);
    }
    AuditService auditService = auditServiceRegister.getAuditService();
    AuditEvent event = new AuditEvent(new Date());
    event.setApplicationName("SCEP");
    event.setName(CaAuditConstants.NAME_PERF);
    event.addEventData(CaAuditConstants.NAME_SCEP_name, scepName + "/" + certProfileName);
    event.addEventData(CaAuditConstants.NAME_reqType, RequestType.SCEP.name());
    String msgId = RandomUtil.nextHexLong();
    event.addEventData(CaAuditConstants.NAME_mid, msgId);
    AuditLevel auditLevel = AuditLevel.INFO;
    AuditStatus auditStatus = AuditStatus.SUCCESSFUL;
    String auditMessage = null;
    try {
        if (responderManager == null) {
            auditMessage = "responderManager in servlet not configured";
            LOG.error(auditMessage);
            auditLevel = AuditLevel.ERROR;
            auditStatus = AuditStatus.FAILED;
            return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
        Scep responder = responderManager.getScep(scepName);
        if (responder == null || !responder.isOnService() || !responder.supportsCertProfile(certProfileName)) {
            auditMessage = "unknown SCEP '" + scepName + "/" + certProfileName + "'";
            LOG.warn(auditMessage);
            auditStatus = AuditStatus.FAILED;
            return createErrorResponse(version, HttpResponseStatus.NOT_FOUND);
        }
        String operation = servletUri.getParameter("operation");
        event.addEventData(CaAuditConstants.NAME_SCEP_operation, operation);
        if ("PKIOperation".equalsIgnoreCase(operation)) {
            CMSSignedData reqMessage;
            // parse the request
            try {
                byte[] content;
                if (viaPost) {
                    content = readContent(request);
                } else {
                    String b64 = servletUri.getParameter("message");
                    content = Base64.decode(b64);
                }
                reqMessage = new CMSSignedData(content);
            } catch (Exception ex) {
                final String msg = "invalid request";
                LogUtil.error(LOG, ex, msg);
                auditMessage = msg;
                auditStatus = AuditStatus.FAILED;
                return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
            }
            ContentInfo ci;
            try {
                ci = responder.servicePkiOperation(reqMessage, certProfileName, msgId, event);
            } catch (MessageDecodingException ex) {
                final String msg = "could not decrypt and/or verify the request";
                LogUtil.error(LOG, ex, msg);
                auditMessage = msg;
                auditStatus = AuditStatus.FAILED;
                return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
            } catch (OperationException ex) {
                ErrorCode code = ex.getErrorCode();
                HttpResponseStatus httpCode;
                switch(code) {
                    case ALREADY_ISSUED:
                    case CERT_REVOKED:
                    case CERT_UNREVOKED:
                        httpCode = HttpResponseStatus.FORBIDDEN;
                        break;
                    case BAD_CERT_TEMPLATE:
                    case BAD_REQUEST:
                    case BAD_POP:
                    case INVALID_EXTENSION:
                    case UNKNOWN_CERT:
                    case UNKNOWN_CERT_PROFILE:
                        httpCode = HttpResponseStatus.BAD_REQUEST;
                        break;
                    case NOT_PERMITTED:
                        httpCode = HttpResponseStatus.UNAUTHORIZED;
                        break;
                    case SYSTEM_UNAVAILABLE:
                        httpCode = HttpResponseStatus.SERVICE_UNAVAILABLE;
                        break;
                    case CRL_FAILURE:
                    case DATABASE_FAILURE:
                    case SYSTEM_FAILURE:
                        httpCode = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                        break;
                    default:
                        httpCode = HttpResponseStatus.INTERNAL_SERVER_ERROR;
                        break;
                }
                auditMessage = ex.getMessage();
                LogUtil.error(LOG, ex, auditMessage);
                auditStatus = AuditStatus.FAILED;
                return createErrorResponse(version, httpCode);
            }
            byte[] bodyBytes = ci.getEncoded();
            return createOKResponse(version, CT_RESPONSE, bodyBytes);
        } else if (Operation.GetCACaps.getCode().equalsIgnoreCase(operation)) {
            // CA-Ident is ignored
            byte[] caCapsBytes = responder.getCaCaps().getBytes();
            return createOKResponse(version, ScepConstants.CT_TEXT_PLAIN, caCapsBytes);
        } else if (Operation.GetCACert.getCode().equalsIgnoreCase(operation)) {
            // CA-Ident is ignored
            byte[] respBytes = responder.getCaCertResp().getBytes();
            return createOKResponse(version, ScepConstants.CT_X509_CA_RA_CERT, respBytes);
        } else if (Operation.GetNextCACert.getCode().equalsIgnoreCase(operation)) {
            auditMessage = "SCEP operation '" + operation + "' is not permitted";
            auditStatus = AuditStatus.FAILED;
            return createErrorResponse(version, HttpResponseStatus.FORBIDDEN);
        } else {
            auditMessage = "unknown SCEP operation '" + operation + "'";
            auditStatus = AuditStatus.FAILED;
            return createErrorResponse(version, HttpResponseStatus.BAD_REQUEST);
        }
    } catch (Throwable th) {
        if (th instanceof EOFException) {
            final String msg = "connection reset by peer";
            if (LOG.isWarnEnabled()) {
                LogUtil.warn(LOG, th, msg);
            }
            LOG.debug(msg, th);
        } else {
            LOG.error("Throwable thrown, this should not happen!", th);
        }
        auditLevel = AuditLevel.ERROR;
        auditStatus = AuditStatus.FAILED;
        auditMessage = "internal error";
        return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    } finally {
        audit(auditService, event, auditLevel, auditStatus, auditMessage);
    }
}
Also used : HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) AuditLevel(org.xipki.audit.AuditLevel) CMSSignedData(org.bouncycastle.cms.CMSSignedData) Date(java.util.Date) MessageDecodingException(org.xipki.scep.exception.MessageDecodingException) IOException(java.io.IOException) EOFException(java.io.EOFException) OperationException(org.xipki.ca.api.OperationException) AuditStatus(org.xipki.audit.AuditStatus) MessageDecodingException(org.xipki.scep.exception.MessageDecodingException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) EOFException(java.io.EOFException) AuditEvent(org.xipki.audit.AuditEvent) ErrorCode(org.xipki.ca.api.OperationException.ErrorCode) Scep(org.xipki.ca.server.api.Scep) HttpVersion(io.netty.handler.codec.http.HttpVersion) AuditService(org.xipki.audit.AuditService) HttpMethod(io.netty.handler.codec.http.HttpMethod) OperationException(org.xipki.ca.api.OperationException)

Example 15 with HttpVersion

use of io.netty.handler.codec.http.HttpVersion in project xipki by xipki.

the class HealthCheckServlet method service0.

private FullHttpResponse service0(FullHttpRequest request, ServletURI servletUri, SSLSession sslSession) {
    HttpVersion version = request.protocolVersion();
    HttpMethod method = request.method();
    if (method != HttpMethod.GET) {
        return createErrorResponse(version, HttpResponseStatus.METHOD_NOT_ALLOWED);
    }
    try {
        if (responderManager == null) {
            LOG.error("responderManager in servlet is not configured");
            return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
        String caName = null;
        X509CaCmpResponder responder = null;
        if (servletUri.getPath().length() > 1) {
            // skip the first char which is always '/'
            String caAlias = servletUri.getPath().substring(1);
            caName = responderManager.getCaNameForAlias(caAlias);
            if (caName == null) {
                caName = caAlias.toLowerCase();
            }
            responder = responderManager.getX509CaResponder(caName);
        }
        if (caName == null || responder == null || !responder.isOnService()) {
            String auditMessage;
            if (caName == null) {
                auditMessage = "no CA is specified";
            } else if (responder == null) {
                auditMessage = "unknown CA '" + caName + "'";
            } else {
                auditMessage = "CA '" + caName + "' is out of service";
            }
            LOG.warn(auditMessage);
            return createErrorResponse(version, HttpResponseStatus.NOT_FOUND);
        }
        HealthCheckResult healthResult = responder.healthCheck();
        HttpResponseStatus status = healthResult.isHealthy() ? HttpResponseStatus.OK : HttpResponseStatus.INTERNAL_SERVER_ERROR;
        byte[] respBytes = healthResult.toJsonMessage(true).getBytes();
        return createResponse(version, status, HealthCheckServlet.CT_RESPONSE, respBytes);
    } catch (Throwable th) {
        if (th instanceof EOFException) {
            LogUtil.warn(LOG, th, "connection reset by peer");
        } else {
            LOG.error("Throwable thrown, this should not happen!", th);
        }
        return createErrorResponse(version, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : X509CaCmpResponder(org.xipki.ca.server.api.X509CaCmpResponder) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) EOFException(java.io.EOFException) HealthCheckResult(org.xipki.common.HealthCheckResult) HttpVersion(io.netty.handler.codec.http.HttpVersion) HttpMethod(io.netty.handler.codec.http.HttpMethod)

Aggregations

HttpVersion (io.netty.handler.codec.http.HttpVersion)22 HttpMethod (io.netty.handler.codec.http.HttpMethod)11 ByteBuf (io.netty.buffer.ByteBuf)8 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)8 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)7 EOFException (java.io.EOFException)7 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)6 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)6 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)5 Map (java.util.Map)4 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)3 HttpRequest (io.netty.handler.codec.http.HttpRequest)3 Date (java.util.Date)3 HashMap (java.util.HashMap)3 Test (org.junit.Test)3 AuditEvent (org.xipki.audit.AuditEvent)3 ResponderAndPath (org.xipki.ocsp.api.ResponderAndPath)3 DataProvider (com.tngtech.java.junit.dataprovider.DataProvider)2 Unpooled (io.netty.buffer.Unpooled)2 Channel (io.netty.channel.Channel)2