Search in sources :

Example 76 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project tomcat by apache.

the class ApplicationFilterChain method internalDoFilter.

private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
    // Call the next filter if there is one
    if (pos < n) {
        ApplicationFilterConfig filterConfig = filters[pos++];
        try {
            Filter filter = filterConfig.getFilter();
            if (request.isAsyncSupported() && "false".equalsIgnoreCase(filterConfig.getFilterDef().getAsyncSupported())) {
                request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
            }
            if (Globals.IS_SECURITY_ENABLED) {
                final ServletRequest req = request;
                final ServletResponse res = response;
                Principal principal = ((HttpServletRequest) req).getUserPrincipal();
                Object[] args = new Object[] { req, res, this };
                SecurityUtil.doAsPrivilege("doFilter", filter, classType, args, principal);
            } else {
                filter.doFilter(request, response, this);
            }
        } catch (IOException | ServletException | RuntimeException e) {
            throw e;
        } catch (Throwable e) {
            e = ExceptionUtils.unwrapInvocationTargetException(e);
            ExceptionUtils.handleThrowable(e);
            throw new ServletException(sm.getString("filterChain.filter"), e);
        }
        return;
    }
    // We fell off the end of the chain -- call the servlet instance
    try {
        if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
            lastServicedRequest.set(request);
            lastServicedResponse.set(response);
        }
        if (request.isAsyncSupported() && !servletSupportsAsync) {
            request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR, Boolean.FALSE);
        }
        // Use potentially wrapped request from this point
        if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse) && Globals.IS_SECURITY_ENABLED) {
            final ServletRequest req = request;
            final ServletResponse res = response;
            Principal principal = ((HttpServletRequest) req).getUserPrincipal();
            Object[] args = new Object[] { req, res };
            SecurityUtil.doAsPrivilege("service", servlet, classTypeUsedInService, args, principal);
        } else {
            servlet.service(request, response);
        }
    } catch (IOException | ServletException | RuntimeException e) {
        throw e;
    } catch (Throwable e) {
        e = ExceptionUtils.unwrapInvocationTargetException(e);
        ExceptionUtils.handleThrowable(e);
        throw new ServletException(sm.getString("filterChain.servlet"), e);
    } finally {
        if (ApplicationDispatcher.WRAP_SAME_OBJECT) {
            lastServicedRequest.set(null);
            lastServicedResponse.set(null);
        }
    }
}
Also used : ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Filter(javax.servlet.Filter) Principal(java.security.Principal)

Example 77 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project tomcat by apache.

the class SSIFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    // cast once
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    // indicate that we're in SSI processing
    req.setAttribute(Globals.SSI_FLAG_ATTR, "true");
    // setup to capture output
    ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream();
    ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(getServletContext(), req, res, basos);
    // process remainder of filter chain
    chain.doFilter(req, responseIncludeWrapper);
    // we can't assume the chain flushed its output
    responseIncludeWrapper.flushOutputStreamOrWriter();
    byte[] bytes = basos.toByteArray();
    // get content type
    String contentType = responseIncludeWrapper.getContentType();
    // is this an allowed type for SSI processing?
    if (contentTypeRegEx.matcher(contentType).matches()) {
        String encoding = res.getCharacterEncoding();
        // set up SSI processing
        SSIExternalResolver ssiExternalResolver = new SSIServletExternalResolver(getServletContext(), req, res, isVirtualWebappRelative, debug, encoding);
        SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver, debug, allowExec);
        // prepare readers/writers
        Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes), encoding);
        ByteArrayOutputStream ssiout = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(ssiout, encoding));
        // do SSI processing
        long lastModified = ssiProcessor.process(reader, responseIncludeWrapper.getLastModified(), writer);
        // set output bytes
        writer.flush();
        bytes = ssiout.toByteArray();
        // override headers
        if (expires != null) {
            res.setDateHeader("expires", (new java.util.Date()).getTime() + expires.longValue() * 1000);
        }
        if (lastModified > 0) {
            res.setDateHeader("last-modified", lastModified);
        }
        res.setContentLength(bytes.length);
        Matcher shtmlMatcher = shtmlRegEx.matcher(responseIncludeWrapper.getContentType());
        if (shtmlMatcher.matches()) {
            // Convert shtml mime type to ordinary html mime type but preserve
            // encoding, if any.
            String enc = shtmlMatcher.group(1);
            res.setContentType("text/html" + ((enc != null) ? enc : ""));
        }
    }
    // write output
    OutputStream out = null;
    try {
        out = res.getOutputStream();
    } catch (IllegalStateException e) {
    // Ignore, will try to use a writer
    }
    if (out == null) {
        res.getWriter().write(new String(bytes));
    } else {
        out.write(bytes);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) Matcher(java.util.regex.Matcher) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpServletRequest(javax.servlet.http.HttpServletRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter)

Example 78 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project tomcat by apache.

the class JspRuntimeLibrary method getContextRelativePath.

// ************************************************************************
// General Purpose Runtime Methods
// ************************************************************************
/**
     * Convert a possibly relative resource path into a context-relative
     * resource path that starts with a '/'.
     *
     * @param request The servlet request we are processing
     * @param relativePath The possibly relative resource path
     * @return an absolute path
     */
public static String getContextRelativePath(ServletRequest request, String relativePath) {
    if (relativePath.startsWith("/"))
        return (relativePath);
    if (!(request instanceof HttpServletRequest))
        return (relativePath);
    HttpServletRequest hrequest = (HttpServletRequest) request;
    String uri = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
    if (uri != null) {
        String pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
        if (pathInfo == null) {
            if (uri.lastIndexOf('/') >= 0)
                uri = uri.substring(0, uri.lastIndexOf('/'));
        }
    } else {
        uri = hrequest.getServletPath();
        if (uri.lastIndexOf('/') >= 0)
            uri = uri.substring(0, uri.lastIndexOf('/'));
    }
    return uri + '/' + relativePath;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest)

Example 79 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project tomcat by apache.

the class TestRemoteIpFilter method testInvokeAllProxiesAreInternal.

@Test
public void testInvokeAllProxiesAreInternal() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11");
    filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3");
    filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for");
    filterDef.addInitParameter("proxiesHeader", "x-forwarded-by");
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setRemoteHost("remote-host-original-value");
    request.addHeader("x-forwarded-for", "140.211.11.130, 192.168.0.10, 192.168.0.11");
    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest();
    // VERIFY
    String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for");
    assertNull("all proxies are internal, x-forwarded-for must be null", actualXForwardedFor);
    String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by");
    assertNull("all proxies are internal, x-forwarded-by must be null", actualXForwardedBy);
    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr);
    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "140.211.11.130", actualRemoteHost);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterDef(org.apache.tomcat.util.descriptor.web.FilterDef) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 80 with HttpServletRequest

use of javax.servlet.http.HttpServletRequest in project tomcat by apache.

the class TestRemoteIpFilter method testInvokeAllProxiesAreTrusted.

@Test
public void testInvokeAllProxiesAreTrusted() throws Exception {
    // PREPARE
    RemoteIpFilter remoteIpFilter = new RemoteIpFilter();
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11");
    filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3");
    filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for");
    filterDef.addInitParameter("proxiesHeader", "x-forwarded-by");
    filterDef.setFilter(remoteIpFilter);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setRemoteHost("remote-host-original-value");
    request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, proxy2");
    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest();
    // VERIFY
    String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for");
    assertNull("all proxies are trusted, x-forwarded-for must be null", actualXForwardedFor);
    String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by");
    assertEquals("all proxies are trusted, they must appear in x-forwarded-by", "proxy1, proxy2", actualXForwardedBy);
    String actualRemoteAddr = actualRequest.getRemoteAddr();
    assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr);
    String actualRemoteHost = actualRequest.getRemoteHost();
    assertEquals("remoteHost", "140.211.11.130", actualRemoteHost);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterDef(org.apache.tomcat.util.descriptor.web.FilterDef) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Aggregations

HttpServletRequest (javax.servlet.http.HttpServletRequest)2488 HttpServletResponse (javax.servlet.http.HttpServletResponse)1308 Test (org.junit.Test)987 IOException (java.io.IOException)595 ServletException (javax.servlet.ServletException)498 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)223 FilterChain (javax.servlet.FilterChain)200 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)196 Test (org.testng.annotations.Test)168 Request (org.eclipse.jetty.server.Request)164 CountDownLatch (java.util.concurrent.CountDownLatch)160 HttpServlet (javax.servlet.http.HttpServlet)156 HttpSession (javax.servlet.http.HttpSession)150 HashMap (java.util.HashMap)130 PrintWriter (java.io.PrintWriter)121 Map (java.util.Map)100 InterruptedIOException (java.io.InterruptedIOException)97 ServletRequest (javax.servlet.ServletRequest)95 ServletContext (javax.servlet.ServletContext)91 ServletOutputStream (javax.servlet.ServletOutputStream)90