Search in sources :

Example 1 with MappingData

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

the class CoyoteAdapter method service.

// -------------------------------------------------------- Adapter Methods
/**
 * Service method.
 */
@Override
public void service(org.glassfish.grizzly.http.server.Request req, org.glassfish.grizzly.http.server.Response res) throws Exception {
    res.getResponse().setAllowCustomReasonPhrase(Constants.USE_CUSTOM_STATUS_MSG_IN_HEADER);
    Request request = req.getNote(CATALINA_REQUEST_NOTE);
    Response response = req.getNote(CATALINA_RESPONSE_NOTE);
    // Grizzly already parsed, decoded, and mapped the request.
    // Let's re-use this info here, before firing the
    // requestStartEvent probe, so that the mapping data will be
    // available to any probe event listener via standard
    // ServletRequest APIs (such as getContextPath())
    MappingData md = req.getNote(MAPPING_DATA);
    final boolean v3Enabled = md != null;
    if (request == null) {
        // Create objects
        request = (Request) connector.createRequest();
        response = (Response) connector.createResponse();
        // Link objects
        request.setResponse(response);
        response.setRequest(request);
        // Set as notes
        req.setNote(CATALINA_REQUEST_NOTE, request);
        req.setNote(CATALINA_RESPONSE_NOTE, response);
        // res.setNote(ADAPTER_NOTES, response);
        // Set query string encoding
        req.getRequest().getRequestURIRef().setDefaultURIEncoding(Charset.forName(connector.getURIEncoding()));
    }
    request.setCoyoteRequest(req);
    response.setCoyoteResponse(res);
    if (v3Enabled && !compatWithTomcat) {
        request.setMappingData(md);
        request.updatePaths(md);
    }
    req.addAfterServiceListener(catalinaAfterServiceListener);
    try {
        doService(req, request, res, response, v3Enabled);
        // Request may want to initialize async processing
        request.onExitService();
    } catch (Throwable t) {
        log.log(Level.SEVERE, LogFacade.REQUEST_PROCESSING_EXCEPTION, t);
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) MappingData(org.glassfish.grizzly.http.server.util.MappingData)

Example 2 with MappingData

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

the class StandardContext method getRequestDispatcher.

/**
 * Return a <code>RequestDispatcher</code> instance that acts as a
 * wrapper for the resource at the given path.  The path must begin
 * with a "/" and is interpreted as relative to the current context root.
 */
@Override
public RequestDispatcher getRequestDispatcher(String path) {
    // Validate the path argument
    if (path == null) {
        return null;
    }
    if (!path.startsWith("/") && !path.isEmpty()) {
        String msg = MessageFormat.format(rb.getString(LogFacade.INCORRECT_OR_NOT_EMPTY_PATH), path);
        throw new IllegalArgumentException(msg);
    }
    // Get query string
    String queryString = null;
    int pos = path.indexOf('?');
    if (pos >= 0) {
        queryString = path.substring(pos + 1);
        path = path.substring(0, pos);
    }
    path = RequestUtil.normalize(path);
    if (path == null)
        return (null);
    pos = path.length();
    // Use the thread local URI and mapping data
    DispatchData dd = dispatchData.get();
    if (dd == null) {
        dd = new DispatchData();
        dispatchData.set(dd);
    }
    MessageBytes uriMB = dd.uriMB;
    uriMB.recycle();
    // Retrieve the thread local mapping data
    MappingData mappingData = dd.mappingData;
    // Map the URI
    CharChunk uriCC = uriMB.getCharChunk();
    try {
        uriCC.append(getPath(), 0, getPath().length());
        /*
             * Ignore any trailing path params (separated by ';') for mapping
             * purposes
             */
        int semicolon = path.indexOf(';');
        if (pos >= 0 && semicolon > pos) {
            semicolon = -1;
        }
        uriCC.append(path, 0, semicolon > 0 ? semicolon : pos);
        getMapper().map(uriMB, mappingData);
        if (mappingData.wrapper == null) {
            return (null);
        }
        /*
             * Append any trailing path params (separated by ';') that were
             * ignored for mapping purposes, so that they're reflected in the
             * RequestDispatcher's requestURI
             */
        if (semicolon > 0) {
            uriCC.append(path, semicolon, pos - semicolon);
        }
    } catch (Exception e) {
        // Should never happen
        log.log(Level.WARNING, LogFacade.MAPPING_ERROR_EXCEPTION, e);
        return (null);
    }
    Wrapper wrapper = (Wrapper) mappingData.wrapper;
    String wrapperPath = mappingData.wrapperPath.toString();
    String pathInfo = mappingData.pathInfo.toString();
    HttpServletMapping mappingForDispatch = new MappingImpl(mappingData);
    mappingData.recycle();
    // Construct a RequestDispatcher to process this request
    return new ApplicationDispatcher(wrapper, mappingForDispatch, uriCC.toString(), wrapperPath, pathInfo, queryString, null);
}
Also used : Wrapper(org.apache.catalina.Wrapper) MessageBytes(org.glassfish.grizzly.http.util.MessageBytes) MappingData(org.glassfish.grizzly.http.server.util.MappingData) MappingImpl(org.apache.catalina.connector.MappingImpl) SecurityConstraint(org.apache.catalina.deploy.SecurityConstraint) CharChunk(org.glassfish.grizzly.http.util.CharChunk) LifecycleException(org.apache.catalina.LifecycleException) MalformedObjectNameException(javax.management.MalformedObjectNameException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) NamingException(javax.naming.NamingException) MBeanRegistrationException(javax.management.MBeanRegistrationException) MalformedURLException(java.net.MalformedURLException) HttpServletMapping(javax.servlet.http.HttpServletMapping)

Example 3 with MappingData

use of org.glassfish.grizzly.http.server.util.MappingData 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 4 with MappingData

use of org.glassfish.grizzly.http.server.util.MappingData 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)

Example 5 with MappingData

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

the class WebContainer method createHttpListener.

protected WebConnector createHttpListener(NetworkListener listener, HttpService httpService, Mapper mapper) {
    if (!Boolean.valueOf(listener.getEnabled())) {
        return null;
    }
    int port = 8080;
    WebConnector connector;
    checkHostnameUniqueness(listener.getName(), httpService);
    try {
        port = Integer.parseInt(listener.getPort());
    } catch (NumberFormatException nfe) {
        String msg = rb.getString(LogFacade.HTTP_LISTENER_INVALID_PORT);
        msg = MessageFormat.format(msg, listener.getPort(), listener.getName());
        throw new IllegalArgumentException(msg);
    }
    if (mapper == null) {
        for (Mapper m : habitat.<Mapper>getAllServices(Mapper.class)) {
            if (m.getPort() == port && m instanceof ContextMapper) {
                ContextMapper cm = (ContextMapper) m;
                if (listener.getName().equals(cm.getId())) {
                    mapper = m;
                    break;
                }
            }
        }
    }
    String defaultVS = listener.findHttpProtocol().getHttp().getDefaultVirtualServer();
    if (!defaultVS.equals(org.glassfish.api.web.Constants.ADMIN_VS)) {
        // Before we start a WebConnector, let's makes sure there is
        // not another Container already listening on that port
        DataChunk host = DataChunk.newInstance();
        char[] c = defaultVS.toCharArray();
        host.setChars(c, 0, c.length);
        DataChunk mb = DataChunk.newInstance();
        mb.setChars(new char[] { '/' }, 0, 1);
        MappingData md = new MappingData();
        try {
            mapper.map(host, mb, md);
        } catch (Exception e) {
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "", e);
            }
        }
        if (md.context != null && md.context instanceof ContextRootInfo) {
            ContextRootInfo r = (ContextRootInfo) md.context;
            if (!(r.getHttpHandler() instanceof ContainerMapper)) {
                new BindException("Port " + port + " is already used by Container: " + r.getHttpHandler() + " and will not get started.").printStackTrace();
                return null;
            }
        }
    }
    /*
         * Create Connector. Connector is SSL-enabled if
         * 'security-enabled' attribute in <http-listener>
         * element is set to TRUE.
         */
    boolean isSecure = Boolean.valueOf(listener.findHttpProtocol().getSecurityEnabled());
    if (isSecure && defaultRedirectPort == -1) {
        defaultRedirectPort = port;
    }
    String address = listener.getAddress();
    if ("any".equals(address) || "ANY".equals(address) || "INADDR_ANY".equals(address)) {
        address = null;
    /*
             * Setting 'address' to NULL will cause Tomcat to pass a
             * NULL InetAddress argument to the java.net.ServerSocket
             * constructor, meaning that the server socket will accept
             * connections on any/all local addresses.
             */
    }
    connector = (WebConnector) _embedded.createConnector(address, port, isSecure);
    connector.setMapper(mapper);
    connector.setJvmRoute(engine.getJvmRoute());
    if (logger.isLoggable(Level.INFO)) {
        logger.log(Level.INFO, LogFacade.HTTP_LISTENER_CREATED, new Object[] { listener.getName(), listener.getAddress(), listener.getPort() });
    }
    connector.setDefaultHost(listener.findHttpProtocol().getHttp().getDefaultVirtualServer());
    connector.setName(listener.getName());
    connector.setInstanceName(instanceName);
    connector.configure(listener, isSecure, httpService);
    _embedded.addConnector(connector);
    connectorMap.put(listener.getName(), connector);
    // If we already know the redirect port, then set it now
    // This situation will occurs when dynamic reconfiguration occurs
    String redirectPort = listener.findHttpProtocol().getHttp().getRedirectPort();
    if (redirectPort != null) {
        connector.setRedirectPort(Integer.parseInt(redirectPort));
    } else if (defaultRedirectPort != -1) {
        connector.setRedirectPort(defaultRedirectPort);
    }
    ObservableBean httpListenerBean = (ObservableBean) ConfigSupport.getImpl(listener);
    httpListenerBean.addListener(configListener);
    return connector;
}
Also used : BindException(java.net.BindException) LifecycleException(org.apache.catalina.LifecycleException) NamingException(javax.naming.NamingException) BindException(java.net.BindException) MalformedURLException(java.net.MalformedURLException) ContextRootInfo(org.glassfish.grizzly.config.ContextRootInfo) Mapper(org.glassfish.grizzly.http.server.util.Mapper) ContextMapper(org.glassfish.internal.grizzly.ContextMapper) ContainerMapper(com.sun.enterprise.v3.services.impl.ContainerMapper) MappingData(org.glassfish.grizzly.http.server.util.MappingData) DataChunk(org.glassfish.grizzly.http.util.DataChunk) ObservableBean(org.jvnet.hk2.config.ObservableBean) ContextMapper(org.glassfish.internal.grizzly.ContextMapper) ContainerMapper(com.sun.enterprise.v3.services.impl.ContainerMapper)

Aggregations

MappingData (org.glassfish.grizzly.http.server.util.MappingData)7 DataChunk (org.glassfish.grizzly.http.util.DataChunk)5 CharChunk (org.glassfish.grizzly.http.util.CharChunk)3 MalformedURLException (java.net.MalformedURLException)2 NamingException (javax.naming.NamingException)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 LifecycleException (org.apache.catalina.LifecycleException)2 Wrapper (org.apache.catalina.Wrapper)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 MBeanRegistrationException (javax.management.MBeanRegistrationException)1 MalformedObjectNameException (javax.management.MalformedObjectNameException)1 ServletException (javax.servlet.ServletException)1 HttpServletMapping (javax.servlet.http.HttpServletMapping)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 Context (org.apache.catalina.Context)1