Search in sources :

Example 91 with ServletException

use of jakarta.servlet.ServletException in project tomcat by apache.

the class Request method upgrade.

@SuppressWarnings("unchecked")
@Override
public <T extends HttpUpgradeHandler> T upgrade(Class<T> httpUpgradeHandlerClass) throws java.io.IOException, ServletException {
    T handler;
    InstanceManager instanceManager = null;
    try {
        // need injection
        if (InternalHttpUpgradeHandler.class.isAssignableFrom(httpUpgradeHandlerClass)) {
            handler = httpUpgradeHandlerClass.getConstructor().newInstance();
        } else {
            instanceManager = getContext().getInstanceManager();
            handler = (T) instanceManager.newInstance(httpUpgradeHandlerClass);
        }
    } catch (ReflectiveOperationException | NamingException | IllegalArgumentException | SecurityException e) {
        throw new ServletException(e);
    }
    UpgradeToken upgradeToken = new UpgradeToken(handler, getContext(), instanceManager, getUpgradeProtocolName(httpUpgradeHandlerClass));
    coyoteRequest.action(ActionCode.UPGRADE, upgradeToken);
    // Output required by RFC2616. Protocol specific headers should have
    // already been set.
    response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS);
    return handler;
}
Also used : ServletException(jakarta.servlet.ServletException) UpgradeToken(org.apache.coyote.UpgradeToken) InstanceManager(org.apache.tomcat.InstanceManager) NamingException(javax.naming.NamingException)

Example 92 with ServletException

use of jakarta.servlet.ServletException in project tomcat by apache.

the class Request method parseParts.

private void parseParts(boolean explicit) {
    // Return immediately if the parts have already been parsed
    if (parts != null || partsParseException != null) {
        return;
    }
    Context context = getContext();
    MultipartConfigElement mce = getWrapper().getMultipartConfigElement();
    if (mce == null) {
        if (context.getAllowCasualMultipartParsing()) {
            mce = new MultipartConfigElement(null, connector.getMaxPostSize(), connector.getMaxPostSize(), connector.getMaxPostSize());
        } else {
            if (explicit) {
                partsParseException = new IllegalStateException(sm.getString("coyoteRequest.noMultipartConfig"));
                return;
            } else {
                parts = Collections.emptyList();
                return;
            }
        }
    }
    Parameters parameters = coyoteRequest.getParameters();
    parameters.setLimit(getConnector().getMaxParameterCount());
    boolean success = false;
    try {
        File location;
        String locationStr = mce.getLocation();
        if (locationStr == null || locationStr.length() == 0) {
            location = ((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR));
        } else {
            // If relative, it is relative to TEMPDIR
            location = new File(locationStr);
            if (!location.isAbsolute()) {
                location = new File((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR), locationStr).getAbsoluteFile();
            }
        }
        if (!location.exists() && context.getCreateUploadTargets()) {
            log.warn(sm.getString("coyoteRequest.uploadCreate", location.getAbsolutePath(), getMappingData().wrapper.getName()));
            if (!location.mkdirs()) {
                log.warn(sm.getString("coyoteRequest.uploadCreateFail", location.getAbsolutePath()));
            }
        }
        if (!location.isDirectory()) {
            parameters.setParseFailedReason(FailReason.MULTIPART_CONFIG_INVALID);
            partsParseException = new IOException(sm.getString("coyoteRequest.uploadLocationInvalid", location));
            return;
        }
        // Create a new file upload handler
        DiskFileItemFactory factory = new DiskFileItemFactory();
        try {
            factory.setRepository(location.getCanonicalFile());
        } catch (IOException ioe) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = ioe;
            return;
        }
        factory.setSizeThreshold(mce.getFileSizeThreshold());
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);
        upload.setFileSizeMax(mce.getMaxFileSize());
        upload.setSizeMax(mce.getMaxRequestSize());
        parts = new ArrayList<>();
        try {
            List<FileItem> items = upload.parseRequest(new ServletRequestContext(this));
            int maxPostSize = getConnector().getMaxPostSize();
            int postSize = 0;
            Charset charset = getCharset();
            for (FileItem item : items) {
                ApplicationPart part = new ApplicationPart(item, location);
                parts.add(part);
                if (part.getSubmittedFileName() == null) {
                    String name = part.getName();
                    if (maxPostSize >= 0) {
                        // Have to calculate equivalent size. Not completely
                        // accurate but close enough.
                        postSize += name.getBytes(charset).length;
                        // Equals sign
                        postSize++;
                        // Value length
                        postSize += part.getSize();
                        // Value separator
                        postSize++;
                        if (postSize > maxPostSize) {
                            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
                            throw new IllegalStateException(sm.getString("coyoteRequest.maxPostSizeExceeded"));
                        }
                    }
                    String value = null;
                    try {
                        value = part.getString(charset.name());
                    } catch (UnsupportedEncodingException uee) {
                    // Not possible
                    }
                    parameters.addParameter(name, value);
                }
            }
            success = true;
        } catch (InvalidContentTypeException e) {
            parameters.setParseFailedReason(FailReason.INVALID_CONTENT_TYPE);
            partsParseException = new ServletException(e);
        } catch (SizeException e) {
            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
            checkSwallowInput();
            partsParseException = new IllegalStateException(e);
        } catch (IOException e) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = new IOException(e);
        } catch (IllegalStateException e) {
            // addParameters() will set parseFailedReason
            checkSwallowInput();
            partsParseException = e;
        }
    } finally {
        // respect to changes in the remainder of the method.
        if (partsParseException != null || !success) {
            parameters.setParseFailedReason(FailReason.UNKNOWN);
        }
    }
}
Also used : ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) ServletContext(jakarta.servlet.ServletContext) AsyncContext(jakarta.servlet.AsyncContext) Context(org.apache.catalina.Context) Parameters(org.apache.tomcat.util.http.Parameters) InvalidContentTypeException(org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException) ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) ServletException(jakarta.servlet.ServletException) FileItem(org.apache.tomcat.util.http.fileupload.FileItem) MultipartConfigElement(jakarta.servlet.MultipartConfigElement) ServletFileUpload(org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload) ApplicationPart(org.apache.catalina.core.ApplicationPart) File(java.io.File) SizeException(org.apache.tomcat.util.http.fileupload.impl.SizeException)

Example 93 with ServletException

use of jakarta.servlet.ServletException in project tomcat by apache.

the class JspRuntimeContext method checkCompile.

/**
 * Method used by background thread to check the JSP dependencies
 * registered with this class for JSP's.
 */
public void checkCompile() {
    if (lastCompileCheck < 0) {
        // Checking was disabled
        return;
    }
    long now = System.currentTimeMillis();
    if (now > (lastCompileCheck + (options.getCheckInterval() * 1000L))) {
        lastCompileCheck = now;
    } else {
        return;
    }
    List<JspServletWrapper> wrappersToReload = new ArrayList<>();
    // Tell JspServletWrapper to ignore the reload attribute while this
    // check is in progress. See BZ 62603.
    compileCheckInProgress = true;
    Object[] wrappers = jsps.values().toArray();
    for (Object wrapper : wrappers) {
        JspServletWrapper jsw = (JspServletWrapper) wrapper;
        JspCompilationContext ctxt = jsw.getJspEngineContext();
        // Sync on JspServletWrapper when calling ctxt.compile()
        synchronized (jsw) {
            try {
                ctxt.compile();
                if (jsw.getReload()) {
                    wrappersToReload.add(jsw);
                }
            } catch (FileNotFoundException ex) {
                ctxt.incrementRemoved();
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                jsw.getServletContext().log(Localizer.getMessage("jsp.error.backgroundCompilationFailed"), t);
            }
        }
    }
    // See BZ 62603.
    // OK to process reload flag now.
    compileCheckInProgress = false;
    // Ensure all servlets and tags that need to be reloaded, are reloaded.
    for (JspServletWrapper jsw : wrappersToReload) {
        // Triggers reload
        try {
            if (jsw.isTagFile()) {
                // conditions during the reload.
                synchronized (this) {
                    jsw.loadTagFile();
                }
            } else {
                jsw.getServlet();
            }
        } catch (ServletException e) {
            jsw.getServletContext().log(Localizer.getMessage("jsp.error.reload"), e);
        }
    }
}
Also used : JspServletWrapper(org.apache.jasper.servlet.JspServletWrapper) ServletException(jakarta.servlet.ServletException) JspCompilationContext(org.apache.jasper.JspCompilationContext) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException)

Example 94 with ServletException

use of jakarta.servlet.ServletException in project tomcat by apache.

the class TestRequestFilterValve method oneTest.

private void oneTest(String allow, String deny, boolean denyStatus, boolean addConnectorPort, boolean usePeerAddress, boolean auth, String property, String type, boolean allowed) {
    // PREPARE
    RequestFilterValve valve = null;
    Connector connector = new Connector();
    Context context = new StandardContext();
    Request request = new Request(connector);
    Response response = new MockResponse();
    StringBuilder msg = new StringBuilder();
    int expected = allowed ? OK : FORBIDDEN;
    connector.setPort(PORT);
    request.getMappingData().context = context;
    request.setCoyoteRequest(new org.apache.coyote.Request());
    Assert.assertNotNull("Invalid test with null type", type);
    request.setCoyoteRequest(new org.apache.coyote.Request());
    if (property != null) {
        if (type.equals("Addr")) {
            valve = new RemoteAddrValve();
            if (usePeerAddress) {
                request.setRemoteAddr(ADDR_OTHER);
                request.getCoyoteRequest().peerAddr().setString(property);
                ((RemoteAddrValve) valve).setUsePeerAddress(true);
                msg.append(" peer='" + property + "'");
            } else {
                request.setRemoteAddr(property);
                request.getCoyoteRequest().peerAddr().setString(ADDR_OTHER);
                msg.append(" ip='" + property + "'");
            }
        } else if (type.equals("Host")) {
            valve = new RemoteHostValve();
            request.setRemoteHost(property);
            msg.append(" host='" + property + "'");
        } else if (type.equals("CIDR")) {
            valve = new RemoteCIDRValve();
            if (usePeerAddress) {
                request.setRemoteAddr(ADDR_OTHER);
                request.getCoyoteRequest().peerAddr().setString(property);
                ((RemoteCIDRValve) valve).setUsePeerAddress(true);
                msg.append(" peer='" + property + "'");
            } else {
                request.setRemoteAddr(property);
                request.getCoyoteRequest().peerAddr().setString(ADDR_OTHER);
                msg.append(" ip='" + property + "'");
            }
        }
    }
    Assert.assertNotNull("Invalid test type" + type, valve);
    valve.setNext(new TerminatingValve());
    if (allow != null) {
        valve.setAllow(allow);
        msg.append(" allow='" + allow + "'");
    }
    if (deny != null) {
        valve.setDeny(deny);
        msg.append(" deny='" + deny + "'");
    }
    if (denyStatus) {
        valve.setDenyStatus(CUSTOM);
        msg.append(" denyStatus='" + CUSTOM + "'");
        if (!allowed) {
            expected = CUSTOM;
        }
    }
    if (addConnectorPort) {
        if (valve instanceof RemoteAddrValve) {
            ((RemoteAddrValve) valve).setAddConnectorPort(true);
        } else if (valve instanceof RemoteHostValve) {
            ((RemoteHostValve) valve).setAddConnectorPort(true);
        } else if (valve instanceof RemoteCIDRValve) {
            ((RemoteCIDRValve) valve).setAddConnectorPort(true);
        } else {
            Assert.fail("Can only set 'addConnectorPort' for RemoteAddrValve, RemoteHostValve and RemoteCIDRValve");
        }
        msg.append(" addConnectorPort='true'");
    }
    if (auth) {
        context.setPreemptiveAuthentication(true);
        valve.setInvalidAuthenticationWhenDeny(true);
        msg.append(" auth='true'");
    }
    // TEST
    try {
        valve.invoke(request, response);
    } catch (IOException | ServletException ex) {
    // Ignore
    }
    // VERIFY
    if (!allowed && auth) {
        Assert.assertEquals(msg.toString(), OK, response.getStatus());
        Assert.assertEquals(msg.toString(), "invalid", request.getHeader("authorization"));
    } else {
        Assert.assertEquals(msg.toString(), expected, response.getStatus());
    }
}
Also used : Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) Connector(org.apache.catalina.connector.Connector) Request(org.apache.catalina.connector.Request) IOException(java.io.IOException) Response(org.apache.catalina.connector.Response) ServletException(jakarta.servlet.ServletException) StandardContext(org.apache.catalina.core.StandardContext)

Example 95 with ServletException

use of jakarta.servlet.ServletException in project spring-security by spring-projects.

the class Saml2WebSsoAuthenticationRequestFilterTests method doFilterWhenPostThenSaveRedirectRequest.

@Test
public void doFilterWhenPostThenSaveRedirectRequest() throws ServletException, IOException {
    RelyingPartyRegistration registration = this.rpBuilder.assertingPartyDetails((asserting) -> asserting.singleSignOnServiceBinding(Saml2MessageBinding.POST)).build();
    Saml2AuthenticationRequestContext context = authenticationRequestContext().relyingPartyRegistration(registration).build();
    Saml2PostAuthenticationRequest request = postAuthenticationRequest(context).build();
    given(this.resolver.resolve(any())).willReturn(context);
    given(this.factory.createPostAuthenticationRequest(any())).willReturn(request);
    this.filter.doFilterInternal(this.request, this.response, this.filterChain);
    verify(this.authenticationRequestRepository).saveAuthenticationRequest(any(Saml2PostAuthenticationRequest.class), eq(this.request), eq(this.response));
}
Also used : RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) Saml2AuthenticationRequestRepository(org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestRepository) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) MockFilterChain(org.springframework.mock.web.MockFilterChain) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RelyingPartyRegistrationRepository(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Saml2AuthenticationRequestResolver(org.springframework.security.saml2.provider.service.web.authentication.Saml2AuthenticationRequestResolver) DefaultSaml2AuthenticationRequestContextResolver(org.springframework.security.saml2.provider.service.web.DefaultSaml2AuthenticationRequestContextResolver) ServletException(jakarta.servlet.ServletException) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) HtmlUtils(org.springframework.web.util.HtmlUtils) Saml2MessageBinding(org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) Saml2AuthenticationRequestContextResolver(org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestContextResolver) BDDMockito.given(org.mockito.BDDMockito.given) AbstractSaml2AuthenticationRequest(org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest) Saml2AuthenticationRequestContext(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestContext) Saml2PostAuthenticationRequest(org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest) Saml2RedirectAuthenticationRequest(org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest) DefaultRelyingPartyRegistrationResolver(org.springframework.security.saml2.provider.service.web.DefaultRelyingPartyRegistrationResolver) Saml2AuthenticationRequestFactory(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestFactory) ServletRequest(jakarta.servlet.ServletRequest) RelyingPartyRegistrationResolver(org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver) IOException(java.io.IOException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) RequestMatcher(org.springframework.security.web.util.matcher.RequestMatcher) StandardCharsets(java.nio.charset.StandardCharsets) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) TestSaml2X509Credentials(org.springframework.security.saml2.credentials.TestSaml2X509Credentials) ServletResponse(jakarta.servlet.ServletResponse) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) UriUtils(org.springframework.web.util.UriUtils) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TestSaml2AuthenticationRequestContexts(org.springframework.security.saml2.provider.service.authentication.TestSaml2AuthenticationRequestContexts) TestRelyingPartyRegistrations(org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) Mockito.mock(org.mockito.Mockito.mock) Saml2PostAuthenticationRequest(org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest) Saml2AuthenticationRequestContext(org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestContext) Test(org.junit.jupiter.api.Test)

Aggregations

ServletException (jakarta.servlet.ServletException)115 IOException (java.io.IOException)72 Test (org.junit.jupiter.api.Test)26 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)17 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)16 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)15 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)15 ServletContext (jakarta.servlet.ServletContext)14 FilterChain (jakarta.servlet.FilterChain)13 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)13 BeforeEach (org.junit.jupiter.api.BeforeEach)12 BeforeMethod (org.testng.annotations.BeforeMethod)11 ServletConfig (jakarta.servlet.ServletConfig)10 Arrays (java.util.Arrays)10 Enumeration (java.util.Enumeration)10 UnavailableException (jakarta.servlet.UnavailableException)9 HttpHeaders (org.springframework.http.HttpHeaders)9 HttpMethod (org.springframework.http.HttpMethod)9 CorsConfiguration (org.springframework.web.cors.CorsConfiguration)9 ServletRequest (jakarta.servlet.ServletRequest)8