Search in sources :

Example 6 with CharChunk

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

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

the class FormAuthenticator method authenticate.

// ------------------------------------------------------- Public Methods
/**
 * Authenticate the user making this request, based on the specified
 * login configuration.  Return <code>true</code> if any specified
 * constraint has been satisfied, or <code>false</code> if we have
 * created a response challenge already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param config Login configuration describing how authentication
 * should be performed
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean authenticate(HttpRequest request, HttpResponse response, LoginConfig config) throws IOException {
    // References to objects we will need later
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    HttpServletResponse hres = (HttpServletResponse) response.getResponse();
    Session session = null;
    String contextPath = hreq.getContextPath();
    String requestURI = request.getDecodedRequestURI();
    // Is this the action request from the login page?
    boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION);
    // Have we already authenticated someone?
    Principal principal = hreq.getUserPrincipal();
    // processing section of this method.
    if (principal != null && !loginAction) {
        if (log.isLoggable(Level.FINE))
            log.log(Level.FINE, "Already authenticated '" + principal.getName() + "'");
        String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
        if (ssoId != null) {
            getSession(request, true);
        }
        return (true);
    }
    // processing section of this method.
    if (!cache && !loginAction) {
        session = getSession(request, true);
        if (log.isLoggable(Level.FINE))
            log.log(Level.FINE, "Checking for reauthenticate in session " + session);
        String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE);
        char[] password = (char[]) session.getNote(Constants.SESS_PASSWORD_NOTE);
        if ((username != null) && (password != null)) {
            if (log.isLoggable(Level.FINE))
                log.log(Level.FINE, "Reauthenticating username '" + username + "'");
            principal = context.getRealm().authenticate(username, password);
            if (principal != null) {
                session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
                if (!matchRequest(request)) {
                    register(request, response, principal, Constants.FORM_METHOD, username, password);
                    return (true);
                }
            }
            if (log.isLoggable(Level.FINE))
                log.log(Level.FINE, "Reauthentication failed, proceed normally");
        }
    }
    // authentication?  If so, forward the *original* request instead.
    if (matchRequest(request)) {
        session = getSession(request, true);
        if (log.isLoggable(Level.FINE)) {
            String msg = "Restore request from session '" + session.getIdInternal() + "'";
            log.log(Level.FINE, msg);
        }
        principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE);
        register(request, response, principal, Constants.FORM_METHOD, (String) session.getNote(Constants.SESS_USERNAME_NOTE), (char[]) session.getNote(Constants.SESS_PASSWORD_NOTE));
        String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
        if (ssoId != null) {
            associate(ssoId, getSsoVersion(request), session);
        }
        if (restoreRequest(request, session)) {
            if (log.isLoggable(Level.FINE))
                log.log(Level.FINE, "Proceed to restored request");
            return (true);
        } else {
            if (log.isLoggable(Level.FINE))
                log.log(Level.FINE, "Restore of original request failed");
            hres.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return (false);
        }
    }
    // Acquire references to objects we will need to evaluate
    MessageBytes uriMB = MessageBytes.newInstance();
    CharChunk uriCC = uriMB.getCharChunk();
    uriCC.setLimit(-1);
    response.setContext(request.getContext());
    // No -- Save this request and redirect to the form login page
    if (!loginAction) {
        session = getSession(request, true);
        if (log.isLoggable(Level.FINE)) {
            String msg = "Save request in session '" + session.getIdInternal() + "'";
            log.log(Level.FINE, msg);
        }
        saveRequest(request, session);
        // START Apache bug 36136: Refactor the login and error page forward
        /*
            RequestDispatcher disp =
                context.getServletContext().getRequestDispatcher
                (config.getLoginPage());
            try {
                disp.forward(hreq, hres);
                response.finishResponse();
            } catch (Throwable t) {
                log.warn("Unexpected error forwarding to login page", t);
            }
            */
        forwardToLoginPage(request, response, config);
        return (false);
    }
    // Yes -- Validate the specified credentials and redirect
    // to the error page if they are not correct
    Realm realm = context.getRealm();
    String username = hreq.getParameter(Constants.FORM_USERNAME);
    String pwd = hreq.getParameter(Constants.FORM_PASSWORD);
    char[] password = ((pwd != null) ? pwd.toCharArray() : null);
    if (log.isLoggable(Level.FINE))
        log.log(Level.FINE, "Authenticating username '" + username + "'");
    principal = realm.authenticate(username, password);
    if (principal == null) {
        // START Apache bug 36136: Refactor the login and error page forward
        /*
            RequestDispatcher disp =
                context.getServletContext().getRequestDispatcher
                (config.getErrorPage());
            try {
                disp.forward(hreq, hres);
            } catch (Throwable t) {
                log.warn("Unexpected error forwarding to error page", t);
            }
            */
        forwardToErrorPage(request, response, config);
        return (false);
    }
    // Save the authenticated Principal in our session
    if (log.isLoggable(Level.FINE))
        log.log(Level.FINE, "Authentication of '" + username + "' was successful");
    if (session == null)
        session = getSession(request, true);
    session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
    // If we are not caching, save the username and password as well
    if (!cache) {
        session.setNote(Constants.SESS_USERNAME_NOTE, username);
        session.setNote(Constants.SESS_PASSWORD_NOTE, password);
    }
    // Redirect the user to the original request URI (which will cause
    // the original request to be restored)
    requestURI = savedRequestURL(session);
    if (requestURI == null) {
        // requestURI will be null if the login form is submitted
        // directly, i.e., if there has not been any original request
        // that was stored away before the redirect to the login form was
        // issued. In this case, assume that the original request has been
        // for the context root, and have the welcome page mechanism take
        // care of it
        requestURI = hreq.getContextPath() + "/";
        register(request, response, principal, Constants.FORM_METHOD, (String) session.getNote(Constants.SESS_USERNAME_NOTE), (char[]) session.getNote(Constants.SESS_PASSWORD_NOTE));
        String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
        if (ssoId != null) {
            associate(ssoId, getSsoVersion(request), session);
        }
    }
    if (log.isLoggable(Level.FINE)) {
        log.log(Level.FINE, "Redirecting to original '" + requestURI + "'");
    }
    hres.sendRedirect(hres.encodeRedirectURL(requestURI));
    return (false);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) MessageBytes(org.glassfish.grizzly.http.util.MessageBytes) Realm(org.apache.catalina.Realm) Principal(java.security.Principal) CharChunk(org.glassfish.grizzly.http.util.CharChunk) Session(org.apache.catalina.Session)

Example 8 with CharChunk

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

CharChunk (org.glassfish.grizzly.http.util.CharChunk)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 MappingData (org.glassfish.grizzly.http.server.util.MappingData)3 DataChunk (org.glassfish.grizzly.http.util.DataChunk)3 IOException (java.io.IOException)2 MalformedURLException (java.net.MalformedURLException)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 Wrapper (org.apache.catalina.Wrapper)2 MessageBytes (org.glassfish.grizzly.http.util.MessageBytes)2 ProxyHandler (com.sun.appserv.ProxyHandler)1 CharConversionException (java.io.CharConversionException)1 String (java.lang.String)1 URL (java.net.URL)1 Principal (java.security.Principal)1 MBeanRegistrationException (javax.management.MBeanRegistrationException)1 MalformedObjectNameException (javax.management.MalformedObjectNameException)1 NamingException (javax.naming.NamingException)1 ServletException (javax.servlet.ServletException)1 HttpServletMapping (javax.servlet.http.HttpServletMapping)1 Context (org.apache.catalina.Context)1