Search in sources :

Example 11 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class HttpServletRequestImpl method loadParts.

private void loadParts() throws IOException, ServletException {
    final ServletRequestContext requestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (parts == null) {
        final List<Part> parts = new ArrayList<>();
        String mimeType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
        if (mimeType != null && mimeType.startsWith(MultiPartParserDefinition.MULTIPART_FORM_DATA)) {
            FormData formData = parseFormData();
            if (formData != null) {
                for (final String namedPart : formData) {
                    for (FormData.FormValue part : formData.get(namedPart)) {
                        parts.add(new PartImpl(namedPart, part, requestContext.getOriginalServletPathMatch().getServletChain().getManagedServlet().getMultipartConfig(), servletContext, this));
                    }
                }
            }
        } else {
            throw UndertowServletMessages.MESSAGES.notAMultiPartRequest();
        }
        this.parts = parts;
    }
}
Also used : FormData(io.undertow.server.handlers.form.FormData) Part(javax.servlet.http.Part) ArrayList(java.util.ArrayList) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) HttpString(io.undertow.util.HttpString)

Example 12 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class HttpServletRequestImpl method isUserInRole.

@Override
public boolean isUserInRole(final String role) {
    if (role == null) {
        return false;
    }
    //according to the servlet spec this aways returns false
    if (role.equals("*")) {
        return false;
    }
    SecurityContext sc = exchange.getSecurityContext();
    Account account = sc.getAuthenticatedAccount();
    if (account == null) {
        return false;
    }
    ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (role.equals("**")) {
        Set<String> roles = servletRequestContext.getDeployment().getDeploymentInfo().getSecurityRoles();
        if (!roles.contains("**")) {
            return true;
        }
    }
    final ServletChain servlet = servletRequestContext.getCurrentServlet();
    final Deployment deployment = servletContext.getDeployment();
    final AuthorizationManager authorizationManager = deployment.getDeploymentInfo().getAuthorizationManager();
    return authorizationManager.isUserInRole(role, account, servlet.getManagedServlet().getServletInfo(), this, deployment);
}
Also used : Account(io.undertow.security.idm.Account) ServletChain(io.undertow.servlet.handlers.ServletChain) SecurityContext(io.undertow.security.api.SecurityContext) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) Deployment(io.undertow.servlet.api.Deployment) HttpString(io.undertow.util.HttpString) AuthorizationManager(io.undertow.servlet.api.AuthorizationManager)

Example 13 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class RewriteHandler method handleRequest.

public void handleRequest(HttpServerExchange exchange) throws Exception {
    RewriteRule[] rules = config.getRules();
    if (rules == null || rules.length == 0) {
        next.handleRequest(exchange);
        return;
    }
    if (Boolean.TRUE.equals(invoked.get())) {
        next.handleRequest(exchange);
        invoked.set(null);
        return;
    }
    ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    HttpServletRequestImpl request = src.getOriginalRequest();
    HttpServletResponseImpl response = src.getOriginalResponse();
    UndertowResolver resolver = new UndertowResolver(src, src.getOriginalRequest());
    invoked.set(Boolean.TRUE);
    // As long as MB isn't a char sequence or affiliated, this has to be
    // converted to a string
    CharSequence url = exchange.getRelativePath();
    CharSequence host = request.getServerName();
    boolean rewritten = false;
    boolean done = false;
    for (int i = 0; i < rules.length; i++) {
        CharSequence test = (rules[i].isHost()) ? host : url;
        CharSequence newtest = rules[i].evaluate(test, resolver);
        if (newtest != null && !test.equals(newtest.toString())) {
            if (UndertowServletLogger.REQUEST_LOGGER.isDebugEnabled()) {
                UndertowServletLogger.REQUEST_LOGGER.debug("Rewrote " + test + " as " + newtest + " with rule pattern " + rules[i].getPatternString());
            }
            if (rules[i].isHost()) {
                host = newtest;
            } else {
                url = newtest;
            }
            rewritten = true;
        }
        // - forbidden
        if (rules[i].isForbidden() && newtest != null) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            done = true;
            break;
        }
        // - gone
        if (rules[i].isGone() && newtest != null) {
            response.sendError(HttpServletResponse.SC_GONE);
            done = true;
            break;
        }
        // - redirect (code)
        if (rules[i].isRedirect() && newtest != null) {
            // append the query string to the url if there is one and it hasn't been rewritten
            String queryString = request.getQueryString();
            StringBuffer urlString = new StringBuffer(url);
            if (queryString != null && queryString.length() > 0) {
                int index = urlString.indexOf("?");
                if (index != -1) {
                    // if qsa is specified append the query
                    if (rules[i].isQsappend()) {
                        urlString.append('&');
                        urlString.append(queryString);
                    } else // prevent the rewrite module from appending the query string
                    if (index == urlString.length() - 1) {
                        urlString.deleteCharAt(index);
                    }
                } else {
                    urlString.append('?');
                    urlString.append(queryString);
                }
            }
            // 3. the url isn't absolute
            if (urlString.charAt(0) == '/' && !hasScheme(urlString)) {
                urlString.insert(0, request.getContextPath());
            }
            response.sendRedirect(urlString.toString());
            response.setStatus(rules[i].getRedirectCode());
            done = true;
            break;
        }
        // - cookie
        if (rules[i].isCookie() && newtest != null) {
            Cookie cookie = new Cookie(rules[i].getCookieName(), rules[i].getCookieResult());
            cookie.setDomain(rules[i].getCookieDomain());
            cookie.setMaxAge(rules[i].getCookieLifetime());
            cookie.setPath(rules[i].getCookiePath());
            cookie.setSecure(rules[i].isCookieSecure());
            cookie.setHttpOnly(rules[i].isCookieHttpOnly());
            response.addCookie(cookie);
        }
        // - env (note: this sets a request attribute)
        if (rules[i].isEnv() && newtest != null) {
            for (int j = 0; j < rules[i].getEnvSize(); j++) {
                request.setAttribute(rules[i].getEnvName(j), rules[i].getEnvResult(j));
            }
        }
        //   to do that)
        if (rules[i].isType() && newtest != null) {
            exchange.getRequestHeaders().put(Headers.CONTENT_TYPE, rules[i].getTypeValue());
        }
        // - qsappend
        if (rules[i].isQsappend() && newtest != null) {
            String queryString = request.getQueryString();
            String urlString = url.toString();
            if (urlString.indexOf('?') != -1 && queryString != null) {
                url = urlString + "&" + queryString;
            }
        }
        // - chain (skip remaining chained rules if this one does not match)
        if (rules[i].isChain() && newtest == null) {
            for (int j = i; j < rules.length; j++) {
                if (!rules[j].isChain()) {
                    i = j;
                    break;
                }
            }
            continue;
        }
        // - last (stop rewriting here)
        if (rules[i].isLast() && newtest != null) {
            break;
        }
        // - next (redo again)
        if (rules[i].isNext() && newtest != null) {
            i = 0;
            continue;
        }
        // - skip (n rules)
        if (newtest != null) {
            i += rules[i].getSkip();
        }
    }
    if (rewritten) {
        if (!done) {
            // See if we need to replace the query string
            String urlString = url.toString();
            String queryString = null;
            int queryIndex = urlString.indexOf('?');
            if (queryIndex != -1) {
                queryString = urlString.substring(queryIndex + 1);
                urlString = urlString.substring(0, queryIndex);
            }
            // Set the new URL
            StringBuilder chunk = new StringBuilder();
            chunk.append(request.getContextPath());
            chunk.append(urlString);
            String requestPath = chunk.toString();
            exchange.setRequestPath(requestPath);
            exchange.setRelativePath(urlString);
            // Set the new Query if there is one
            if (queryString != null) {
                exchange.setQueryString(queryString);
                exchange.getQueryParameters().clear();
                exchange.getQueryParameters().putAll(QueryParameterUtils.parseQueryString(queryString, exchange.getConnection().getUndertowOptions().get(UndertowOptions.URL_CHARSET, StandardCharsets.UTF_8.name())));
            }
            // Set the new host if it changed
            if (!host.equals(request.getServerName())) {
                exchange.getRequestHeaders().put(Headers.HOST, host + ":" + exchange.getHostPort());
            }
            // Reinvoke the whole request recursively
            src.getDeployment().getHandler().handleRequest(exchange);
        }
    } else {
        next.handleRequest(exchange);
    }
    invoked.set(null);
}
Also used : Cookie(javax.servlet.http.Cookie) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) HttpServletResponseImpl(io.undertow.servlet.spec.HttpServletResponseImpl) HttpServletRequestImpl(io.undertow.servlet.spec.HttpServletRequestImpl)

Example 14 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class ServletRequestURLAttribute method readAttribute.

@Override
public String readAttribute(final HttpServerExchange exchange) {
    ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (src == null) {
        return RequestURLAttribute.INSTANCE.readAttribute(exchange);
    }
    String uri = (String) src.getServletRequest().getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
    if (uri != null) {
        return uri;
    }
    uri = (String) src.getServletRequest().getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    if (uri != null) {
        return uri;
    }
    return RequestURLAttribute.INSTANCE.readAttribute(exchange);
}
Also used : ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext)

Example 15 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class FilePredicate method resolve.

@Override
public boolean resolve(final HttpServerExchange value) {
    String location = this.location.readAttribute(value);
    ServletRequestContext src = value.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (src == null) {
        return false;
    }
    ResourceManager manager = src.getDeployment().getDeploymentInfo().getResourceManager();
    if (manager == null) {
        return false;
    }
    try {
        Resource resource = manager.getResource(location);
        if (resource == null) {
            return false;
        }
        return !resource.isDirectory();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : Resource(io.undertow.server.handlers.resource.Resource) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) ResourceManager(io.undertow.server.handlers.resource.ResourceManager) IOException(java.io.IOException)

Aggregations

ServletRequestContext (io.undertow.servlet.handlers.ServletRequestContext)40 IOException (java.io.IOException)8 Session (io.undertow.server.session.Session)5 HttpSessionImpl (io.undertow.servlet.spec.HttpSessionImpl)5 ServletException (javax.servlet.ServletException)5 SecurityContext (io.undertow.security.api.SecurityContext)4 Account (io.undertow.security.idm.Account)4 HttpServerExchange (io.undertow.server.HttpServerExchange)4 HttpString (io.undertow.util.HttpString)4 ServletRequest (javax.servlet.ServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Subject (javax.security.auth.Subject)3 GenericMessageInfo (org.jboss.security.auth.message.GenericMessageInfo)3 AuthenticatedSessionManager (io.undertow.security.api.AuthenticatedSessionManager)2 Resource (io.undertow.server.handlers.resource.Resource)2 ResourceManager (io.undertow.server.handlers.resource.ResourceManager)2 AuthorizationManager (io.undertow.servlet.api.AuthorizationManager)2 SingleConstraintMatch (io.undertow.servlet.api.SingleConstraintMatch)2