Search in sources :

Example 11 with AbstractHttp11Protocol

use of org.apache.coyote.http11.AbstractHttp11Protocol in project spring-boot by spring-projects.

the class TomcatServletWebServerFactoryTests method tomcatProtocolHandlerCanBeCustomized.

@Test
void tomcatProtocolHandlerCanBeCustomized() {
    TomcatServletWebServerFactory factory = getFactory();
    TomcatProtocolHandlerCustomizer<AbstractHttp11Protocol<?>> customizer = (protocolHandler) -> protocolHandler.setProcessorCache(250);
    factory.addProtocolHandlerCustomizers(customizer);
    Tomcat tomcat = getTomcat(factory);
    Connector connector = ((TomcatWebServer) this.webServer).getServiceConnectors().get(tomcat.getService())[0];
    AbstractHttp11Protocol<?> protocolHandler = (AbstractHttp11Protocol<?>) connector.getProtocolHandler();
    assertThat(protocolHandler.getProcessorCache()).isEqualTo(250);
}
Also used : Arrays(java.util.Arrays) URISyntaxException(java.net.URISyntaxException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) NoHttpResponseException(org.apache.http.NoHttpResponseException) NamingException(javax.naming.NamingException) ServletException(jakarta.servlet.ServletException) LifecycleListener(org.apache.catalina.LifecycleListener) ByteArrayResource(org.springframework.core.io.ByteArrayResource) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) Future(java.util.concurrent.Future) Locale(java.util.Locale) Duration(java.time.Duration) Map(java.util.Map) LifecycleState(org.apache.catalina.LifecycleState) PortInUseException(org.springframework.boot.web.server.PortInUseException) RestTemplate(org.springframework.web.client.RestTemplate) AprLifecycleListener(org.apache.catalina.core.AprLifecycleListener) InitialContext(javax.naming.InitialContext) JspServlet(org.apache.jasper.servlet.JspServlet) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) SessionIdGenerator(org.apache.catalina.SessionIdGenerator) AbstractServletWebServerFactoryTests(org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests) FileSystemUtils(org.springframework.util.FileSystemUtils) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) HttpEntity(org.springframework.http.HttpEntity) JarScanFilter(org.apache.tomcat.JarScanFilter) Mockito.inOrder(org.mockito.Mockito.inOrder) ServletContext(jakarta.servlet.ServletContext) StandardContext(org.apache.catalina.core.StandardContext) Awaitility(org.awaitility.Awaitility) HttpClients(org.apache.http.impl.client.HttpClients) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) LifecycleEvent(org.apache.catalina.LifecycleEvent) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) WebServerException(org.springframework.boot.web.server.WebServerException) Valve(org.apache.catalina.Valve) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol) HashMap(java.util.HashMap) Dynamic(jakarta.servlet.ServletRegistration.Dynamic) Connector(org.apache.catalina.connector.Connector) AtomicReference(java.util.concurrent.atomic.AtomicReference) SocketException(java.net.SocketException) CharsetMapper(org.apache.catalina.util.CharsetMapper) ThrowingCallable(org.assertj.core.api.ThrowableAssert.ThrowingCallable) ArgumentCaptor(org.mockito.ArgumentCaptor) Charset(java.nio.charset.Charset) Shutdown(org.springframework.boot.web.server.Shutdown) HttpClient(org.apache.http.client.HttpClient) StandardJarScanFilter(org.apache.tomcat.util.scan.StandardJarScanFilter) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Service(org.apache.catalina.Service) RemoteIpValve(org.apache.catalina.valves.RemoteIpValve) InOrder(org.mockito.InOrder) JarScanType(org.apache.tomcat.JarScanType) MultiValueMap(org.springframework.util.MultiValueMap) BDDMockito.then(org.mockito.BDDMockito.then) IOException(java.io.IOException) Context(org.apache.catalina.Context) HttpServlet(jakarta.servlet.http.HttpServlet) File(java.io.File) MultipartConfigElement(jakarta.servlet.MultipartConfigElement) Tomcat(org.apache.catalina.startup.Tomcat) HttpStatus(org.springframework.http.HttpStatus) AfterEach(org.junit.jupiter.api.AfterEach) Container(org.apache.catalina.Container) ProtocolHandler(org.apache.coyote.ProtocolHandler) AbstractServletWebServerFactory(org.springframework.boot.web.servlet.server.AbstractServletWebServerFactory) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) HttpResponse(org.apache.http.HttpResponse) StandardWrapper(org.apache.catalina.core.StandardWrapper) ResponseEntity(org.springframework.http.ResponseEntity) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) CapturedOutput(org.springframework.boot.testsupport.system.CapturedOutput) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Connector(org.apache.catalina.connector.Connector) Tomcat(org.apache.catalina.startup.Tomcat) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol) Test(org.junit.jupiter.api.Test)

Example 12 with AbstractHttp11Protocol

use of org.apache.coyote.http11.AbstractHttp11Protocol in project metasfresh-webui-api by metasfresh.

the class WebRestApiApplication method servletContainerCustomizer.

@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
    return new EmbeddedServletContainerCustomizer() {

        @Override
        public void customize(final ConfigurableEmbeddedServletContainer servletContainer) {
            final TomcatEmbeddedServletContainerFactory tomcatContainerFactory = (TomcatEmbeddedServletContainerFactory) servletContainer;
            tomcatContainerFactory.addConnectorCustomizers(new TomcatConnectorCustomizer() {

                @Override
                public void customize(final Connector connector) {
                    final AbstractHttp11Protocol<?> httpProtocol = (AbstractHttp11Protocol<?>) connector.getProtocolHandler();
                    httpProtocol.setCompression("on");
                    httpProtocol.setCompressionMinSize(256);
                    final String mimeTypes = httpProtocol.getCompressibleMimeType();
                    final String mimeTypesWithJson = mimeTypes + "," + MediaType.APPLICATION_JSON_VALUE + ",application/javascript";
                    httpProtocol.setCompressibleMimeType(mimeTypesWithJson);
                }
            });
        }
    };
}
Also used : Connector(org.apache.catalina.connector.Connector) ConfigurableEmbeddedServletContainer(org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer) TomcatEmbeddedServletContainerFactory(org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory) TomcatConnectorCustomizer(org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer) EmbeddedServletContainerCustomizer(org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol) Bean(org.springframework.context.annotation.Bean)

Example 13 with AbstractHttp11Protocol

use of org.apache.coyote.http11.AbstractHttp11Protocol in project tomcat by apache.

the class TestHttp2Section_8_1 method doTestPostWithTrailerHeaders.

private void doTestPostWithTrailerHeaders(boolean allowTrailerHeader) throws Exception {
    http2Connect();
    if (allowTrailerHeader) {
        ((AbstractHttp11Protocol<?>) http2Protocol.getHttp11Protocol()).setAllowedTrailerHeaders(TRAILER_HEADER_NAME);
    }
    // Disable overhead protection for window update as it breaks some tests
    http2Protocol.setOverheadWindowUpdateThreshold(0);
    byte[] headersFrameHeader = new byte[9];
    ByteBuffer headersPayload = ByteBuffer.allocate(128);
    byte[] dataFrameHeader = new byte[9];
    ByteBuffer dataPayload = ByteBuffer.allocate(256);
    byte[] trailerFrameHeader = new byte[9];
    ByteBuffer trailerPayload = ByteBuffer.allocate(256);
    buildPostRequest(headersFrameHeader, headersPayload, false, dataFrameHeader, dataPayload, null, trailerFrameHeader, trailerPayload, 3);
    // Write the headers
    writeFrame(headersFrameHeader, headersPayload);
    // Body
    writeFrame(dataFrameHeader, dataPayload);
    // Trailers
    writeFrame(trailerFrameHeader, trailerPayload);
    parser.readFrame(true);
    parser.readFrame(true);
    parser.readFrame(true);
    parser.readFrame(true);
    String len;
    if (allowTrailerHeader) {
        len = Integer.toString(256 + TRAILER_HEADER_VALUE.length());
    } else {
        len = "256";
    }
    Assert.assertEquals("0-WindowSize-[256]\n" + "3-WindowSize-[256]\n" + "3-HeadersStart\n" + "3-Header-[:status]-[200]\n" + "3-Header-[content-length]-[" + len + "]\n" + "3-Header-[date]-[" + DEFAULT_DATE + "]\n" + "3-HeadersEnd\n" + "3-Body-" + len + "\n" + "3-EndOfStream\n", output.getTrace());
}
Also used : ByteBuffer(java.nio.ByteBuffer) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol)

Example 14 with AbstractHttp11Protocol

use of org.apache.coyote.http11.AbstractHttp11Protocol in project tomcat by apache.

the class TestHttp2Limits method doTestHeaderLimits.

private void doTestHeaderLimits(int headerCount, int headerSize, int maxHeaderPayloadSize, int maxHeaderCount, int maxHeaderSize, int delayms, FailureMode failMode) throws Exception {
    // Build the custom headers
    List<String[]> customHeaders = new ArrayList<>();
    StringBuilder headerValue = new StringBuilder(headerSize);
    // Does not need to be secure
    Random r = new Random();
    for (int i = 0; i < headerSize; i++) {
        // Random lower case characters
        headerValue.append((char) ('a' + r.nextInt(26)));
    }
    String v = headerValue.toString();
    for (int i = 0; i < headerCount; i++) {
        customHeaders.add(new String[] { "X-TomcatTest" + i, v });
    }
    enableHttp2();
    configureAndStartWebApplication();
    http2Protocol.setMaxHeaderCount(maxHeaderCount);
    ((AbstractHttp11Protocol<?>) http2Protocol.getHttp11Protocol()).setMaxHttpHeaderSize(maxHeaderSize);
    openClientConnection();
    doHttpUpgrade();
    sendClientPreface();
    validateHttp2InitialResponse();
    if (maxHeaderPayloadSize == -1) {
        maxHeaderPayloadSize = output.getMaxFrameSize();
    }
    // Build the simple request
    byte[] frameHeader = new byte[9];
    // Assumes at least one custom header and that all headers are the same
    // length. These assumptions are valid for these tests.
    ByteBuffer headersPayload = ByteBuffer.allocate(200 + (int) (customHeaders.size() * customHeaders.iterator().next()[1].length() * 1.2));
    populateHeadersPayload(headersPayload, customHeaders, "/simple");
    Exception e = null;
    try {
        int written = 0;
        int left = headersPayload.limit() - written;
        while (left > 0) {
            int thisTime = Math.min(left, maxHeaderPayloadSize);
            populateFrameHeader(frameHeader, written, left, thisTime, 3);
            writeFrame(frameHeader, headersPayload, headersPayload.limit() - left, thisTime, delayms);
            left -= thisTime;
            written += thisTime;
        }
    } catch (IOException ioe) {
        e = ioe;
    }
    switch(failMode) {
        case NONE:
            {
                // Expect a normal response
                readSimpleGetResponse();
                Assert.assertEquals(getSimpleResponseTrace(3), output.getTrace());
                Assert.assertNull(e);
                break;
            }
        case STREAM_RESET:
            {
                // Expect a stream reset
                parser.readFrame(true);
                Assert.assertEquals("3-RST-[11]\n", output.getTrace());
                Assert.assertNull(e);
                break;
            }
        case CONNECTION_RESET:
            {
                // This message uses i18n and needs to be used in a regular
                // expression (since we don't know the connection ID). Generate the
                // string as a regular expression and then replace '[' and ']' with
                // the escaped values.
                String limitMessage = sm.getString("http2Parser.headerLimitSize", "\\p{XDigit}++", "3");
                limitMessage = limitMessage.replace("[", "\\[").replace("]", "\\]");
                // above.
                try {
                    parser.readFrame(true);
                    MatcherAssert.assertThat(output.getTrace(), RegexMatcher.matchesRegex("0-Goaway-\\[1\\]-\\[11\\]-\\[" + limitMessage + "\\]"));
                } catch (IOException se) {
                // Expected on some platforms
                }
                break;
            }
    }
}
Also used : Random(java.util.Random) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol) IOException(java.io.IOException)

Example 15 with AbstractHttp11Protocol

use of org.apache.coyote.http11.AbstractHttp11Protocol in project tomcat by apache.

the class TestCancelledUpload method testCancelledRequest.

@Test
public void testCancelledRequest() throws Exception {
    http2Connect();
    LogManager.getLogManager().getLogger("org.apache.coyote.http2").setLevel(Level.ALL);
    try {
        ((AbstractHttp11Protocol<?>) http2Protocol.getHttp11Protocol()).setAllowedTrailerHeaders(TRAILER_HEADER_NAME);
        int bodySize = 8192;
        int bodyCount = 20;
        byte[] headersFrameHeader = new byte[9];
        ByteBuffer headersPayload = ByteBuffer.allocate(128);
        byte[] dataFrameHeader = new byte[9];
        ByteBuffer dataPayload = ByteBuffer.allocate(bodySize);
        byte[] trailerFrameHeader = new byte[9];
        ByteBuffer trailerPayload = ByteBuffer.allocate(256);
        buildPostRequest(headersFrameHeader, headersPayload, false, dataFrameHeader, dataPayload, null, trailerFrameHeader, trailerPayload, 3);
        // Write the headers
        writeFrame(headersFrameHeader, headersPayload);
        // Body
        for (int i = 0; i < bodyCount; i++) {
            writeFrame(dataFrameHeader, dataPayload);
        }
        // Trailers
        writeFrame(trailerFrameHeader, trailerPayload);
        // The Server will process the request on a separate thread to the
        // incoming frames.
        // The request processing thread will:
        // - read up to 128 bytes of request body
        // (and issue a window update for bytes read)
        // - write a 403 response with no response body
        // The connection processing thread will:
        // - read the request body until the flow control window is exhausted
        // - reset the stream if further DATA frames are received
        parser.readFrame(true);
        // Check for reset and exit if found
        if (checkReset()) {
            return;
        }
        // Not window update, not reset, must be the headers
        Assert.assertEquals("3-HeadersStart\n" + "3-Header-[:status]-[403]\n" + "3-Header-[content-length]-[0]\n" + "3-Header-[date]-[Wed, 11 Nov 2015 19:18:42 GMT]\n" + "3-HeadersEnd\n", output.getTrace());
        output.clearTrace();
        parser.readFrame(true);
        // Check for reset and exit if found
        if (checkReset()) {
            return;
        }
        // Not window update, not reset, must be the response body
        Assert.assertEquals("3-Body-0\n" + "3-EndOfStream\n", output.getTrace());
        output.clearTrace();
        parser.readFrame(true);
        Assert.assertTrue(checkReset());
    // If there are any more frames after this, ignore them
    } finally {
        LogManager.getLogManager().getLogger("org.apache.coyote.http2").setLevel(Level.INFO);
    }
}
Also used : ByteBuffer(java.nio.ByteBuffer) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol) Test(org.junit.Test)

Aggregations

AbstractHttp11Protocol (org.apache.coyote.http11.AbstractHttp11Protocol)16 ProtocolHandler (org.apache.coyote.ProtocolHandler)7 ByteBuffer (java.nio.ByteBuffer)5 Connector (org.apache.catalina.connector.Connector)4 TomcatConnectorCustomizer (org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer)3 TomcatEmbeddedServletContainerFactory (org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory)3 Bean (org.springframework.context.annotation.Bean)3 IOException (java.io.IOException)2 SpringApplication (org.springframework.boot.SpringApplication)2 SpringBootApplication (org.springframework.boot.autoconfigure.SpringBootApplication)2 MultipartConfigElement (jakarta.servlet.MultipartConfigElement)1 ServletContext (jakarta.servlet.ServletContext)1 ServletException (jakarta.servlet.ServletException)1 Dynamic (jakarta.servlet.ServletRegistration.Dynamic)1 HttpServlet (jakarta.servlet.http.HttpServlet)1 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 SocketException (java.net.SocketException)1