Search in sources :

Example 1 with DataChunk

use of org.glassfish.grizzly.http.util.DataChunk in project Payara by payara.

the class Request method removeParameterFromRequestURI.

// START SJSWS 6376484
/**
 * Removes the session version from the request URI.
 * @param parameter   of the form ";" + parameterName + "="
 */
private void removeParameterFromRequestURI(String parameter) {
    int semicolon, semicolon2;
    final DataChunk uriBC = coyoteRequest.getRequest().getRequestURIRef().getRequestURIBC();
    semicolon = uriBC.indexOf(parameter, 0);
    if (semicolon > 0) {
        semicolon2 = uriBC.indexOf(';', semicolon + parameter.length());
        final int end;
        if (semicolon2 >= 0) {
            end = semicolon2;
            uriBC.notifyDirectUpdate();
        } else {
            end = uriBC.getLength();
        }
        uriBC.delete(semicolon, end);
    }
}
Also used : DataChunk(org.glassfish.grizzly.http.util.DataChunk)

Example 2 with DataChunk

use of org.glassfish.grizzly.http.util.DataChunk in project Payara by payara.

the class StandardWrapperValve method invoke.

// --------------------------------------------------------- Public Methods
/**
 * Invoke the servlet we are managing, respecting the rules regarding
 * servlet lifecycle and SingleThreadModel support.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 */
@Override
public int invoke(Request request, Response response) throws IOException, ServletException {
    boolean unavailable = false;
    Throwable throwable = null;
    Servlet servlet = null;
    StandardWrapper wrapper = (StandardWrapper) getContainer();
    Context context = (Context) wrapper.getParent();
    HttpRequest hrequest = (HttpRequest) request;
    /*
         * Create a request facade such that if the request was received
         * at the root context, and the root context is mapped to a
         * default-web-module, the default-web-module mapping is masked from
         * the application code to which the request facade is being passed.
         * For example, the request.facade's getContextPath() method will 
         * return "/", rather than the context root of the default-web-module,
         * in this case.
         */
    RequestFacade hreq = (RequestFacade) request.getRequest(true);
    HttpServletResponse hres = (HttpServletResponse) response.getResponse();
    // Check for the application being marked unavailable
    if (!context.getAvailable()) {
        // BEGIN S1AS 4878272
        hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        response.setDetailMessage(rb.getString(LogFacade.APP_UNAVAILABLE));
        // END S1AS 4878272
        unavailable = true;
    }
    // Check for the servlet being marked unavailable
    if (!unavailable && wrapper.isUnavailable()) {
        String msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_UNAVAILABLE), wrapper.getName());
        log(msg);
        if (hres == null) {
            // NOTE - Not much we can do generically
            ;
        } else {
            long available = wrapper.getAvailable();
            if ((available > 0L) && (available < Long.MAX_VALUE)) {
                hres.setDateHeader("Retry-After", available);
                // BEGIN S1AS 4878272
                hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                response.setDetailMessage(msg);
            // END S1AS 4878272
            } else if (available == Long.MAX_VALUE) {
                // BEGIN S1AS 4878272
                hres.sendError(HttpServletResponse.SC_NOT_FOUND);
                msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_NOT_FOUND), wrapper.getName());
                response.setDetailMessage(msg);
            // END S1AS 4878272
            }
        }
        unavailable = true;
    }
    // Allocate a servlet instance to process this request
    try {
        if (!unavailable) {
            servlet = wrapper.allocate();
        }
    } catch (UnavailableException e) {
        if (e.isPermanent()) {
            // BEGIN S1AS 4878272
            hres.sendError(HttpServletResponse.SC_NOT_FOUND);
            String msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_NOT_FOUND), wrapper.getName());
            response.setDetailMessage(msg);
        // END S1AS 4878272
        } else {
            hres.setDateHeader("Retry-After", e.getUnavailableSeconds());
            // BEGIN S1AS 4878272
            hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            String msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_UNAVAILABLE), wrapper.getName());
            response.setDetailMessage(msg);
        // END S1AS 4878272
        }
    } catch (ServletException e) {
        String msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_ALLOCATE_EXCEPTION), wrapper.getName());
        log(msg, StandardWrapper.getRootCause(e));
        throwable = e;
        exception(request, response, e);
        servlet = null;
    } catch (Throwable e) {
        String msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_ALLOCATE_EXCEPTION), wrapper.getName());
        log(msg, e);
        throwable = e;
        exception(request, response, e);
        servlet = null;
    }
    // Acknowlege the request
    try {
        response.sendAcknowledgement();
    } catch (IOException e) {
        String msg = MessageFormat.format(rb.getString(LogFacade.SEND_ACKNOWLEDGEMENT_EXCEPTION), wrapper.getName());
        log(msg, e);
        throwable = e;
        exception(request, response, e);
    } catch (Throwable e) {
        String msg = MessageFormat.format(rb.getString(LogFacade.SEND_ACKNOWLEDGEMENT_EXCEPTION), wrapper.getName());
        log(msg, e);
        throwable = e;
        exception(request, response, e);
        servlet = null;
    }
    DataChunk requestPathMB = hrequest.getRequestPathMB();
    hreq.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB);
    // Create the filter chain for this request
    ApplicationFilterFactory factory = ApplicationFilterFactory.getInstance();
    ApplicationFilterChain filterChain = factory.createFilterChain((ServletRequest) request, wrapper, servlet);
    // NOTE: This also calls the servlet's service() method
    try {
        String jspFile = wrapper.getJspFile();
        if (jspFile != null) {
            hreq.setAttribute(Globals.JSP_FILE_ATTR, jspFile);
        }
        // START IASRI 4665318
        if (servlet != null) {
            if (filterChain != null) {
                filterChain.setWrapper(wrapper);
                filterChain.doFilter(hreq, hres);
            } else {
                wrapper.service(hreq, hres, servlet);
            }
        }
    // END IASRI 4665318
    } catch (ClientAbortException e) {
        throwable = e;
        exception(request, response, e);
    } catch (IOException e) {
        String msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_SERVICE_EXCEPTION), wrapper.getName());
        log(msg, e);
        throwable = e;
        exception(request, response, e);
    } catch (UnavailableException e) {
        String msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_SERVICE_EXCEPTION), wrapper.getName());
        log(msg, e);
        // throwable = e;
        // exception(request, response, e);
        wrapper.unavailable(e);
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            hres.setDateHeader("Retry-After", available);
            // BEGIN S1AS 4878272
            hres.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            String msgServletUnavailable = MessageFormat.format(rb.getString(LogFacade.SERVLET_UNAVAILABLE), wrapper.getName());
            response.setDetailMessage(msgServletUnavailable);
        // END S1AS 4878272
        } else if (available == Long.MAX_VALUE) {
            // BEGIN S1AS 4878272
            hres.sendError(HttpServletResponse.SC_NOT_FOUND);
            String msgServletNotFound = MessageFormat.format(rb.getString(LogFacade.SERVLET_NOT_FOUND), wrapper.getName());
            response.setDetailMessage(msgServletNotFound);
        // END S1AS 4878272
        }
    // Do not save exception in 'throwable', because we
    // do not want to do exception(request, response, e) processing
    } catch (ServletException e) {
        Throwable rootCause = StandardWrapper.getRootCause(e);
        if (!(rootCause instanceof ClientAbortException)) {
            String msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_SERVICE_EXCEPTION), wrapper.getName());
            log(msg, rootCause);
        }
        throwable = e;
        exception(request, response, e);
    } catch (Throwable e) {
        String msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_SERVICE_EXCEPTION), wrapper.getName());
        log(msg, e);
        throwable = e;
        exception(request, response, e);
    }
    // Release the filter chain (if any) for this request
    try {
        if (filterChain != null)
            filterChain.release();
    } catch (Throwable e) {
        String msg = MessageFormat.format(rb.getString(LogFacade.RELEASE_FILTERS_EXCEPTION), wrapper.getName());
        log(msg, e);
        if (throwable == null) {
            throwable = e;
            exception(request, response, e);
        }
    }
    // Deallocate the allocated servlet instance
    try {
        if (servlet != null) {
            wrapper.deallocate(servlet);
        }
    } catch (Throwable e) {
        String msg = MessageFormat.format(rb.getString(LogFacade.DEALLOCATE_EXCEPTION), wrapper.getName());
        log(msg, e);
        if (throwable == null) {
            throwable = e;
            exception(request, response, e);
        }
    }
    // unload it and release this instance
    try {
        if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) {
            wrapper.unload();
        }
    } catch (Throwable e) {
        String msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_UNLOAD_EXCEPTION), wrapper.getName());
        log(msg, e);
        if (throwable == null) {
            exception(request, response, e);
        }
    }
    return END_PIPELINE;
}
Also used : Context(org.apache.catalina.Context) HttpRequest(org.apache.catalina.HttpRequest) UnavailableException(javax.servlet.UnavailableException) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) RequestFacade(org.apache.catalina.connector.RequestFacade) ServletException(javax.servlet.ServletException) Servlet(javax.servlet.Servlet) DataChunk(org.glassfish.grizzly.http.util.DataChunk) ClientAbortException(org.apache.catalina.connector.ClientAbortException)

Example 3 with DataChunk

use of org.glassfish.grizzly.http.util.DataChunk in project Payara by payara.

the class ContainerMapper method mapUriWithSemicolon.

/**
 * Maps the decodedURI to the corresponding Adapter, considering that URI
 * may have a semicolon with extra data followed, which shouldn't be a part
 * of mapping process.
 *
 * @param req HTTP request
 * @param decodedURI URI
 * @param semicolonPos semicolon position. Might be <tt>0</tt> if position wasn't resolved yet (so it will be resolved in the method), or <tt>-1</tt> if there is no semicolon in the URI.
 * @param mappingData
 * @return
 * @throws Exception
 */
final HttpHandler mapUriWithSemicolon(final Request req, final DataChunk decodedURI, int semicolonPos, final MappingData mappingData) throws Exception {
    mapperLock.readLock().lock();
    try {
        final CharChunk charChunk = decodedURI.getCharChunk();
        final int oldStart = charChunk.getStart();
        final int oldEnd = charChunk.getEnd();
        if (semicolonPos == 0) {
            semicolonPos = decodedURI.indexOf(';', 0);
        }
        DataChunk localDecodedURI = decodedURI;
        if (semicolonPos >= 0) {
            charChunk.setEnd(semicolonPos);
            // duplicate the URI path, because Mapper may corrupt the attributes,
            // which follow the path
            localDecodedURI = req.getNote(DATA_CHUNK);
            if (localDecodedURI == null) {
                localDecodedURI = DataChunk.newInstance();
                req.setNote(DATA_CHUNK, localDecodedURI);
            }
            localDecodedURI.duplicate(decodedURI);
        }
        try {
            return map(req, localDecodedURI, mappingData);
        } finally {
            charChunk.setStart(oldStart);
            charChunk.setEnd(oldEnd);
        }
    } finally {
        mapperLock.readLock().unlock();
    }
}
Also used : DataChunk(org.glassfish.grizzly.http.util.DataChunk) CharChunk(org.glassfish.grizzly.http.util.CharChunk)

Example 4 with DataChunk

use of org.glassfish.grizzly.http.util.DataChunk in project Payara by payara.

the class ContainerMapper method lookupHandler.

private Callable lookupHandler(final Request request, final Response response) throws CharConversionException, Exception {
    MappingData mappingData;
    mapperLock.readLock().lock();
    try {
        // If we have only one Adapter deployed, invoke that Adapter directly.
        if (!mapMultipleAdapter) {
            // Remove the MappingData as we might delegate the request
            // to be serviced directly by the WebContainer
            final HttpHandler httpHandler = mapper.getHttpHandler();
            if (httpHandler != null) {
                request.setNote(MAPPING_DATA, null);
                // return;
                return new HttpHandlerCallable(httpHandler, request, response);
            }
        }
        final DataChunk decodedURI = request.getRequest().getRequestURIRef().getDecodedRequestURIBC(isAllowEncodedSlash());
        mappingData = request.getNote(MAPPING_DATA);
        if (mappingData == null) {
            mappingData = new MappingData();
            request.setNote(MAPPING_DATA, mappingData);
        } else {
            mappingData.recycle();
        }
        HttpHandler httpHandler;
        final CharChunk decodedURICC = decodedURI.getCharChunk();
        final int semicolon = decodedURICC.indexOf(';', 0);
        // Map the request without any trailling.
        httpHandler = mapUriWithSemicolon(request, decodedURI, semicolon, mappingData);
        if (httpHandler == null || httpHandler instanceof ContainerMapper) {
            String ext = decodedURI.toString();
            String type = "";
            if (ext.lastIndexOf(".") > 0) {
                ext = "*" + ext.substring(ext.lastIndexOf("."));
                type = ext.substring(ext.lastIndexOf(".") + 1);
            }
            if (!MimeType.contains(type) && !"/".equals(ext)) {
                initializeFileURLPattern(ext);
                mappingData.recycle();
                httpHandler = mapUriWithSemicolon(request, decodedURI, semicolon, mappingData);
            } else {
                // return;
                return new SuperCallable(request, response);
            }
        }
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "Request: {0} was mapped to Adapter: {1}", new Object[] { decodedURI.toString(), httpHandler });
        }
        // request by default, hence do not pass the undecoded request.
        if (httpHandler == null || httpHandler instanceof ContainerMapper) {
            // super.service(request, response);
            return new SuperCallable(request, response);
        } else {
            // httpHandler.service(request, response);
            return new HttpHandlerCallable(httpHandler, request, response);
        }
    } finally {
        mapperLock.readLock().unlock();
    }
}
Also used : MappingData(org.glassfish.grizzly.http.server.util.MappingData) DataChunk(org.glassfish.grizzly.http.util.DataChunk) CharChunk(org.glassfish.grizzly.http.util.CharChunk)

Example 5 with DataChunk

use of org.glassfish.grizzly.http.util.DataChunk in project Payara by payara.

the class CoyoteAdapter method postParseRequest.

// ------------------------------------------------------ Protected Methods
/**
 * Parse additional request parameters.
 */
protected boolean postParseRequest(final org.glassfish.grizzly.http.server.Request req, final Request request, final org.glassfish.grizzly.http.server.Response res, final Response response, final boolean v3Enabled) throws Exception {
    // XXX the processor may have set a correct scheme and port prior to this point,
    // in ajp13 protocols dont make sense to get the port from the connector...
    // otherwise, use connector configuration
    request.setSecure(req.isSecure());
    // URI decoding
    DataChunk decodedURI;
    try {
        decodedURI = req.getRequest().getRequestURIRef().getDecodedRequestURIBC();
    } catch (CharConversionException cce) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid URI");
        return false;
    }
    if (compatWithTomcat || !v3Enabled) {
        // decodedURI.duplicate(req.requestURI());
        // try {
        // req.getURLDecoder().convert(decodedURI, false);
        // } catch (IOException ioe) {
        // res.setStatus(400);
        // res.setMessage("Invalid URI: " + ioe.getMessage());
        // return false;
        // }
        /* GlassFish Issue 2339
            // Normalize decoded URI
            if (!normalize(req.decodedURI())) {
                res.setStatus(400);
                res.setMessage("Invalid URI");
                return false;
            }
            */
        // Set the remote principal
        String principal = req.getRemoteUser();
        if (principal != null) {
            request.setUserPrincipal(new CoyotePrincipal(principal));
        }
        // Set the authorization type
        String authtype = req.getAuthType();
        if (authtype != null) {
            request.setAuthType(authtype);
        }
    /* CR 6309511
            // URI character decoding
            convertURI(decodedURI, request);

            // Parse session Id
            parseSessionId(req, request);
             */
    // START CR 6309511
    // URI character decoding
    // request.convertURI(decodedURI);
    // START GlassFish Issue 2339
    // Normalize decoded URI
    // if (!normalize(decodedURI)) {
    // res.setStatus(400);
    // res.setMessage("Invalid URI");
    // return false;
    // }
    // END GlassFish Issue 2339
    }
    // END CR 6309511
    /*
         * Remove any parameters from the URI, so they won't be considered
         * by the mapping algorithm, and save them in a temporary CharChunk,
         * so that any session id param may be parsed once the target
         * context, which may use a custom session parameter name, has been
         * identified
         */
    final CharChunk uriParamsCC = request.getURIParams();
    final CharChunk uriCC = decodedURI.getCharChunk();
    final int semicolon = uriCC.indexOf(';');
    if (semicolon > 0) {
        final int absSemicolon = uriCC.getStart() + semicolon;
        uriParamsCC.setChars(uriCC.getBuffer(), absSemicolon, uriCC.getEnd() - absSemicolon);
        decodedURI.setChars(uriCC.getBuffer(), uriCC.getStart(), absSemicolon - uriCC.getStart());
    }
    if (compatWithTomcat || !v3Enabled) {
        /*mod_jk*/
        DataChunk localDecodedURI = decodedURI;
        if (semicolon > 0) {
            localDecodedURI = req.getNote(DATA_CHUNK);
            if (localDecodedURI == null) {
                localDecodedURI = DataChunk.newInstance();
                req.setNote(DATA_CHUNK, localDecodedURI);
            }
            localDecodedURI.duplicate(decodedURI);
        }
        connector.getMapper().map(req.getRequest().serverName(), localDecodedURI, request.getMappingData());
        MappingData md = request.getMappingData();
        req.setNote(MAPPING_DATA, md);
        request.updatePaths(md);
    }
    // FIXME: the code below doesnt belongs to here,
    // this is only have sense
    // in Http11, not in ajp13..
    // At this point the Host header has been processed.
    // Override if the proxyPort/proxyHost are set
    String proxyName = connector.getProxyName();
    int proxyPort = connector.getProxyPort();
    if (proxyPort != 0) {
        req.setServerPort(proxyPort);
    }
    if (proxyName != null) {
        req.setServerName(proxyName);
    }
    Context ctx = (Context) request.getMappingData().context;
    // Parse session id
    if (ctx != null) {
        if (req.isRequestedSessionIdFromURL() && Globals.SESSION_PARAMETER_NAME.equals(ctx.getSessionParameterName())) {
            request.obtainSessionId();
        } else if (!uriParamsCC.isNull()) {
            // String sessionParam = ";" + ctx.getSessionParameterName() + "=";
            request.parseSessionId(ctx.getSessionParameterName(), uriParamsCC);
        }
    }
    // START GlassFish 1024
    request.setDefaultContext(request.getMappingData().isDefaultContext);
    // END GlassFish 1024
    // START SJSAS 6253524
    // request.setContext((Context) request.getMappingData().context);
    // END SJSAS 6253524
    // START SJSAS 6253524
    request.setContext(ctx);
    if (ctx != null && !uriParamsCC.isNull()) {
        request.parseSessionVersion(uriParamsCC);
    }
    if (!uriParamsCC.isNull()) {
        request.parseJReplica(uriParamsCC);
    }
    request.setWrapper((Wrapper) request.getMappingData().wrapper);
    // Filter trace method
    if (!connector.getAllowTrace() && Method.TRACE.equals(req.getMethod())) {
        Wrapper wrapper = request.getWrapper();
        String header = null;
        if (wrapper != null) {
            String[] methods = wrapper.getServletMethods();
            if (methods != null) {
                for (String method : methods) {
                    // Exclude TRACE from methods returned in Allow header
                    if ("TRACE".equals(method)) {
                        continue;
                    }
                    if (header == null) {
                        header = method;
                    } else {
                        header += ", " + method;
                    }
                }
            }
        }
        res.setStatus(405, "TRACE method is not allowed");
        res.addHeader("Allow", header);
        return false;
    }
    // Possible redirect
    DataChunk redirectPathMB = request.getMappingData().redirectPath;
    // START SJSAS 6253524
    if (!redirectPathMB.isNull() && (!ctx.hasAdHocPaths() || (ctx.getAdHocServletName(((HttpServletRequest) request.getRequest()).getServletPath()) == null))) {
        // END SJSAS 6253524
        String redirectPath = redirectPathMB.toString();
        String query = request.getQueryString();
        if (request.isRequestedSessionIdFromURL()) {
            // This is not optimal, but as this is not very common, it
            // shouldn't matter
            redirectPath = redirectPath + ";" + ctx.getSessionParameterName() + "=" + request.getRequestedSessionId();
        }
        // START GlassFish 936
        redirectPath = response.encode(redirectPath);
        // END GlassFish 936
        if (query != null) {
            // This is not optimal, but as this is not very common, it
            // shouldn't matter
            redirectPath = redirectPath + "?" + query;
        }
        // START CR 6590921
        boolean authPassthroughEnabled = connector.getAuthPassthroughEnabled();
        ProxyHandler proxyHandler = connector.getProxyHandler();
        if (authPassthroughEnabled && proxyHandler != null) {
            if (proxyHandler.getSSLKeysize((HttpServletRequest) request.getRequest()) > 0) {
                request.setSecure(true);
            }
        }
        // END CR 6590921
        // Issue a permanent redirect
        response.sendRedirect(redirectPath, false);
        return false;
    }
    // Parse session Id
    /* CR 6309511
        parseSessionCookiesId(req, request);
         */
    // START CR 6309511
    request.parseSessionCookiesId();
    // END CR 6309511
    // START SJSAS 6346226
    request.parseJrouteCookie();
    return true;
}
Also used : Context(org.apache.catalina.Context) Wrapper(org.apache.catalina.Wrapper) ProxyHandler(com.sun.appserv.ProxyHandler) CharConversionException(java.io.CharConversionException) HttpServletRequest(javax.servlet.http.HttpServletRequest) MappingData(org.glassfish.grizzly.http.server.util.MappingData) DataChunk(org.glassfish.grizzly.http.util.DataChunk) CharChunk(org.glassfish.grizzly.http.util.CharChunk)

Aggregations

DataChunk (org.glassfish.grizzly.http.util.DataChunk)8 MappingData (org.glassfish.grizzly.http.server.util.MappingData)5 CharChunk (org.glassfish.grizzly.http.util.CharChunk)3 Context (org.apache.catalina.Context)2 ProxyHandler (com.sun.appserv.ProxyHandler)1 ContainerMapper (com.sun.enterprise.v3.services.impl.ContainerMapper)1 CharConversionException (java.io.CharConversionException)1 IOException (java.io.IOException)1 String (java.lang.String)1 BindException (java.net.BindException)1 MalformedURLException (java.net.MalformedURLException)1 NamingException (javax.naming.NamingException)1 Servlet (javax.servlet.Servlet)1 ServletException (javax.servlet.ServletException)1 UnavailableException (javax.servlet.UnavailableException)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 HttpRequest (org.apache.catalina.HttpRequest)1 LifecycleException (org.apache.catalina.LifecycleException)1 Wrapper (org.apache.catalina.Wrapper)1