You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hc.apache.org by ol...@apache.org on 2019/12/23 13:57:20 UTC

[httpcomponents-core] branch development updated (c2be4f0 -> 04531ef)

This is an automated email from the ASF dual-hosted git repository.

olegk pushed a change to branch development
in repository https://gitbox.apache.org/repos/asf/httpcomponents-core.git.


 discard c2be4f0  Re-use server support code in classic HttpService
 discard 7fcfe9e  Fix `SETTINGS_HEADER_TABLE_SIZE` implementation
     add 6d6f1fa  Allow for timeout while acquiring lock in StrictConnPool. (#163)
     add 4ffbee2  ReactiveResponseConsumer: Fix empty response handling
     add 29976c9  Fix `SETTINGS_HEADER_TABLE_SIZE` implementation
     add a684305  Don't apply INITIAL_WINDOW_SIZE to connection window
     add fd57d35  AbstractHttp1StreamDuplexer: don't synchronize on `this`
     new 272d0c6  Re-use server support code in classic HttpService
     new 6e38b3d  Fixed connection and wire logging in classic test server and client
     new 337401f  Corrected handling of illegal or invalid request heads by async server side protocol handler
     new 04531ef  Support for status code 431 (Request Header Fields Too Large)

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (c2be4f0)
            \
             N -- N -- N   refs/heads/development (04531ef)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../impl/nio/AbstractH2StreamMultiplexer.java      | 19 +++---
 .../hc/core5/reactive/ReactiveDataConsumer.java    | 13 ++++
 .../core5/reactive/ReactiveResponseConsumer.java   | 12 ++--
 .../core5/testing/classic/ClassicTestClient.java   |  3 +-
 .../core5/testing/classic/ClassicTestServer.java   | 14 ++--
 .../LoggingBHttpClientConnectionFactory.java       | 57 +++++++++++++++-
 .../LoggingBHttpServerConnectionFactory.java       | 63 +++++++++++++++++-
 .../testing/classic/ClassicIntegrationTest.java    | 77 ++++++++++++++++------
 .../hc/core5/testing/nio/Http1IntegrationTest.java | 33 ++++++++++
 ...a => RequestHeaderFieldsTooLargeException.java} | 14 ++--
 .../apache/hc/core5/http/impl/ServerSupport.java   |  3 +
 .../http/impl/io/DefaultHttpRequestParser.java     | 14 ++++
 .../apache/hc/core5/http/impl/io/HttpService.java  |  6 +-
 .../http/impl/nio/AbstractHttp1StreamDuplexer.java | 48 +++++++++-----
 .../http/impl/nio/DefaultHttpRequestParser.java    | 14 ++++
 .../http/impl/nio/ServerHttp1StreamDuplexer.java   | 36 ++++++++++
 .../http/impl/nio/ServerHttp1StreamHandler.java    | 73 +++++++++++---------
 .../org/apache/hc/core5/pool/StrictConnPool.java   | 37 +++++++----
 .../hc/core5/http/impl/io/TestRequestParser.java   |  4 +-
 .../apache/hc/core5/pool/TestStrictConnPool.java   | 71 ++++++++++++++++++++
 20 files changed, 492 insertions(+), 119 deletions(-)
 copy httpcore5/src/main/java/org/apache/hc/core5/http/{MethodNotSupportedException.java => RequestHeaderFieldsTooLargeException.java} (75%)


[httpcomponents-core] 04/04: Support for status code 431 (Request Header Fields Too Large)

Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

olegk pushed a commit to branch development
in repository https://gitbox.apache.org/repos/asf/httpcomponents-core.git

commit 04531ef0c0b3e58db25f00776ee58e1e97ce6790
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Sat Dec 14 19:24:06 2019 +0100

    Support for status code 431 (Request Header Fields Too Large)
---
 .../core5/testing/classic/ClassicTestServer.java   |  9 ++-
 .../testing/classic/ClassicIntegrationTest.java    | 77 ++++++++++++++++------
 .../hc/core5/testing/nio/Http1IntegrationTest.java | 33 ++++++++++
 .../http/RequestHeaderFieldsTooLargeException.java | 58 ++++++++++++++++
 .../apache/hc/core5/http/impl/ServerSupport.java   |  3 +
 .../http/impl/io/DefaultHttpRequestParser.java     | 14 ++++
 .../apache/hc/core5/http/impl/io/HttpService.java  |  6 +-
 .../http/impl/nio/DefaultHttpRequestParser.java    | 14 ++++
 .../hc/core5/http/impl/io/TestRequestParser.java   |  4 +-
 9 files changed, 187 insertions(+), 31 deletions(-)

diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestServer.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestServer.java
index c7d4ff4..4abe8b2 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestServer.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestServer.java
@@ -99,7 +99,10 @@ public class ClassicTestServer {
         throw new IllegalStateException("Server not running");
     }
 
-    public void start(final HttpProcessor httpProcessor, final Decorator<HttpServerRequestHandler> handlerDecorator) throws IOException {
+    public void start(
+            final Http1Config http1Config,
+            final HttpProcessor httpProcessor,
+            final Decorator<HttpServerRequestHandler> handlerDecorator) throws IOException {
         if (serverRef.get() == null) {
             final HttpServerRequestHandler handler = new BasicHttpServerRequestHandler(registry);
             final HttpService httpService = new HttpService(
@@ -115,7 +118,7 @@ public class ClassicTestServer {
                     sslContext != null ? sslContext.getServerSocketFactory() : ServerSocketFactory.getDefault(),
                     new LoggingBHttpServerConnectionFactory(
                             sslContext != null ? URIScheme.HTTPS.id : URIScheme.HTTP.id,
-                            Http1Config.DEFAULT,
+                            http1Config != null ? http1Config : Http1Config.DEFAULT,
                             CharCodingConfig.DEFAULT),
                     null,
                     LoggingExceptionListener.INSTANCE);
@@ -128,7 +131,7 @@ public class ClassicTestServer {
     }
 
     public void start() throws IOException {
-        start(null, null);
+        start(null, null, null);
     }
 
     public void shutdown(final CloseMode closeMode) {
diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicIntegrationTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicIntegrationTest.java
index 6971c4e..4ce02d6 100644
--- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicIntegrationTest.java
+++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/classic/ClassicIntegrationTest.java
@@ -57,6 +57,7 @@ import org.apache.hc.core5.http.HttpStatus;
 import org.apache.hc.core5.http.HttpVersion;
 import org.apache.hc.core5.http.Method;
 import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.config.Http1Config;
 import org.apache.hc.core5.http.io.HttpRequestHandler;
 import org.apache.hc.core5.http.io.HttpServerRequestHandler;
 import org.apache.hc.core5.http.io.SocketConfig;
@@ -90,8 +91,8 @@ public class ClassicIntegrationTest {
     @Parameterized.Parameters(name = "{0}")
     public static Collection<Object[]> protocols() {
         return Arrays.asList(new Object[][]{
-                { URIScheme.HTTP },
-                { URIScheme.HTTPS }
+                {URIScheme.HTTP},
+                {URIScheme.HTTPS}
         });
     }
 
@@ -108,7 +109,7 @@ public class ClassicIntegrationTest {
         @Override
         protected void before() throws Throwable {
             server = new ClassicTestServer(
-                    scheme == URIScheme.HTTPS  ? SSLTestContexts.createServerSSLContext() : null,
+                    scheme == URIScheme.HTTPS ? SSLTestContexts.createServerSSLContext() : null,
                     SocketConfig.custom()
                             .setSoTimeout(5, TimeUnit.SECONDS)
                             .build());
@@ -135,7 +136,7 @@ public class ClassicIntegrationTest {
         @Override
         protected void before() throws Throwable {
             client = new ClassicTestClient(
-                    scheme == URIScheme.HTTPS  ? SSLTestContexts.createClientSSLContext() : null,
+                    scheme == URIScheme.HTTPS ? SSLTestContexts.createClientSSLContext() : null,
                     SocketConfig.custom()
                             .setSoTimeout(5, TimeUnit.SECONDS)
                             .build());
@@ -489,7 +490,7 @@ public class ClassicIntegrationTest {
 
         });
 
-        this.server.start(null, new Decorator<HttpServerRequestHandler>() {
+        this.server.start(null, null, new Decorator<HttpServerRequestHandler>() {
 
             @Override
             public HttpServerRequestHandler decorate(final HttpServerRequestHandler handler) {
@@ -602,22 +603,22 @@ public class ClassicIntegrationTest {
 
         final String[] patterns = {
 
-            "0123456789ABCDEF",
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
-            "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that"
+                "0123456789ABCDEF",
+                "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that-" +
+                        "yadayada-blahblah-this-and-that-yadayada-blahblah-this-and-that"
         };
 
         // Initialize the server-side request handler
@@ -885,4 +886,38 @@ public class ClassicIntegrationTest {
         }
     }
 
+    @Test
+    public void testHeaderTooLarge() throws Exception {
+        this.server.registerHandler("*", new HttpRequestHandler() {
+
+            @Override
+            public void handle(
+                    final ClassicHttpRequest request,
+                    final ClassicHttpResponse response,
+                    final HttpContext context) throws HttpException, IOException {
+                response.setEntity(new StringEntity("All is well", StandardCharsets.US_ASCII));
+            }
+
+        });
+
+        this.server.start(
+                Http1Config.custom()
+                        .setMaxLineLength(100)
+                        .build(),
+                null,
+                null);
+        this.client.start();
+
+        final HttpCoreContext context = HttpCoreContext.create();
+        final HttpHost host = new HttpHost(scheme.id, "localhost", this.server.getPort());
+
+        final BasicClassicHttpRequest get1 = new BasicClassicHttpRequest(Method.GET, "/");
+        get1.setHeader("big-f-header", "1234567890123456789012345678901234567890123456789012345678901234567890" +
+                "1234567890123456789012345678901234567890");
+        try (final ClassicHttpResponse response1 = this.client.execute(host, get1, context)) {
+            Assert.assertEquals(431, response1.getCode());
+            EntityUtils.consume(response1.getEntity());
+        }
+    }
+
 }
diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java
index 6132f15..79c1dc0 100644
--- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java
+++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java
@@ -1789,4 +1789,37 @@ public class Http1IntegrationTest extends InternalHttp1ServerTestBase {
         Assert.assertEquals("Boom!!!", entity1);
     }
 
+    @Test
+    public void testHeaderTooLarge() throws Exception {
+        server.register("/hello", new Supplier<AsyncServerExchangeHandler>() {
+
+            @Override
+            public AsyncServerExchangeHandler get() {
+                return new SingleLineResponseHandler("Hi there");
+            }
+
+        });
+        final InetSocketAddress serverEndpoint = server.start(null, Http1Config.custom()
+                .setMaxLineLength(100)
+                .build());
+        client.start();
+
+        final Future<ClientSessionEndpoint> connectFuture = client.connect(
+                "localhost", serverEndpoint.getPort(), TIMEOUT);
+        final ClientSessionEndpoint streamEndpoint = connectFuture.get();
+
+        final HttpRequest request1 = new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/hello"));
+        request1.setHeader("big-f-header", "1234567890123456789012345678901234567890123456789012345678901234567890" +
+                "1234567890123456789012345678901234567890");
+        final Future<Message<HttpResponse, String>> future1 = streamEndpoint.execute(
+                new BasicRequestProducer(request1, null),
+                new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), null);
+        final Message<HttpResponse, String> result1 = future1.get(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
+        Assert.assertNotNull(result1);
+        final HttpResponse response1 = result1.getHead();
+        Assert.assertNotNull(response1);
+        Assert.assertEquals(431, response1.getCode());
+        Assert.assertEquals("Maximum line length limit exceeded", result1.getBody());
+    }
+
 }
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/RequestHeaderFieldsTooLargeException.java b/httpcore5/src/main/java/org/apache/hc/core5/http/RequestHeaderFieldsTooLargeException.java
new file mode 100644
index 0000000..ac6cbe3
--- /dev/null
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/RequestHeaderFieldsTooLargeException.java
@@ -0,0 +1,58 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation.  For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ *
+ */
+
+package org.apache.hc.core5.http;
+
+/**
+ * Signals request header field length or total field size violation.
+ *
+ * @since 5.0
+ */
+public class RequestHeaderFieldsTooLargeException extends ProtocolException {
+
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * Creates a new RequestHeaderFieldsTooLargeException with the specified detail message.
+     *
+     * @param message The exception detail message
+     */
+    public RequestHeaderFieldsTooLargeException(final String message) {
+        super(message);
+    }
+
+    /**
+     * Creates a new RequestHeaderFieldsTooLargeException with the specified detail message and cause.
+     *
+     * @param message the exception detail message
+     * @param cause the {@code Throwable} that caused this exception, or {@code null}
+     * if the cause is unavailable, unknown, or not a {@code Throwable}
+     */
+    public RequestHeaderFieldsTooLargeException(final String message, final Throwable cause) {
+        super(message, cause);
+    }
+}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/ServerSupport.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/ServerSupport.java
index 29cca6b..df6bc12 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/ServerSupport.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/ServerSupport.java
@@ -34,6 +34,7 @@ import org.apache.hc.core5.http.HttpStatus;
 import org.apache.hc.core5.http.MethodNotSupportedException;
 import org.apache.hc.core5.http.NotImplementedException;
 import org.apache.hc.core5.http.ProtocolException;
+import org.apache.hc.core5.http.RequestHeaderFieldsTooLargeException;
 import org.apache.hc.core5.http.UnsupportedHttpVersionException;
 
 /**
@@ -70,6 +71,8 @@ public class ServerSupport {
             code = HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED;
         } else if (ex instanceof NotImplementedException) {
             code = HttpStatus.SC_NOT_IMPLEMENTED;
+        } else if (ex instanceof RequestHeaderFieldsTooLargeException) {
+            code = HttpStatus.SC_REQUEST_HEADER_FIELDS_TOO_LARGE;
         } else if (ex instanceof ProtocolException) {
             code = HttpStatus.SC_BAD_REQUEST;
         } else {
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/DefaultHttpRequestParser.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/DefaultHttpRequestParser.java
index a1e8e59..55e6caf 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/DefaultHttpRequestParser.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/DefaultHttpRequestParser.java
@@ -28,12 +28,16 @@
 package org.apache.hc.core5.http.impl.io;
 
 import java.io.IOException;
+import java.io.InputStream;
 
 import org.apache.hc.core5.http.ClassicHttpRequest;
 import org.apache.hc.core5.http.ConnectionClosedException;
 import org.apache.hc.core5.http.HttpException;
 import org.apache.hc.core5.http.HttpRequestFactory;
+import org.apache.hc.core5.http.MessageConstraintException;
+import org.apache.hc.core5.http.RequestHeaderFieldsTooLargeException;
 import org.apache.hc.core5.http.config.Http1Config;
+import org.apache.hc.core5.http.io.SessionInputBuffer;
 import org.apache.hc.core5.http.message.LineParser;
 import org.apache.hc.core5.http.message.RequestLine;
 import org.apache.hc.core5.util.CharArrayBuffer;
@@ -88,6 +92,16 @@ public class DefaultHttpRequestParser extends AbstractMessageParser<ClassicHttpR
     }
 
     @Override
+    public ClassicHttpRequest parse(
+            final SessionInputBuffer buffer, final InputStream inputStream) throws IOException, HttpException {
+        try {
+            return super.parse(buffer, inputStream);
+        } catch (final MessageConstraintException ex) {
+            throw new RequestHeaderFieldsTooLargeException(ex.getMessage(), ex);
+        }
+    }
+
+    @Override
     protected ClassicHttpRequest createMessage(final CharArrayBuffer buffer) throws IOException, HttpException {
         final RequestLine requestLine = getLineParser().parseRequestLine(buffer);
         final ClassicHttpRequest request = this.requestFactory.newHttpRequest(requestLine.getMethod(), requestLine.getUri());
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java
index 31dd3a1..72ef10d 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java
@@ -266,11 +266,7 @@ public class HttpService {
      */
     protected void handleException(final HttpException ex, final ClassicHttpResponse response) {
         response.setCode(toStatusCode(ex));
-        String message = ex.getMessage();
-        if (message == null) {
-            message = ex.toString();
-        }
-        response.setEntity(new StringEntity(message, ContentType.TEXT_PLAIN));
+        response.setEntity(new StringEntity(ServerSupport.toErrorMessage(ex), ContentType.TEXT_PLAIN));
     }
 
     protected int toStatusCode(final Exception ex) {
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/DefaultHttpRequestParser.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/DefaultHttpRequestParser.java
index 0f61845..67724df 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/DefaultHttpRequestParser.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/DefaultHttpRequestParser.java
@@ -27,12 +27,17 @@
 
 package org.apache.hc.core5.http.impl.nio;
 
+import java.io.IOException;
+
 import org.apache.hc.core5.http.HttpException;
 import org.apache.hc.core5.http.HttpRequest;
 import org.apache.hc.core5.http.HttpRequestFactory;
+import org.apache.hc.core5.http.MessageConstraintException;
+import org.apache.hc.core5.http.RequestHeaderFieldsTooLargeException;
 import org.apache.hc.core5.http.config.Http1Config;
 import org.apache.hc.core5.http.message.LineParser;
 import org.apache.hc.core5.http.message.RequestLine;
+import org.apache.hc.core5.http.nio.SessionInputBuffer;
 import org.apache.hc.core5.util.Args;
 import org.apache.hc.core5.util.CharArrayBuffer;
 
@@ -79,6 +84,15 @@ public class DefaultHttpRequestParser<T extends HttpRequest> extends AbstractMes
     }
 
     @Override
+    public T parse(final SessionInputBuffer sessionBuffer, final boolean endOfStream) throws IOException, HttpException {
+        try {
+            return super.parse(sessionBuffer, endOfStream);
+        } catch (final MessageConstraintException ex) {
+            throw new RequestHeaderFieldsTooLargeException(ex.getMessage(), ex);
+        }
+    }
+
+    @Override
     protected T createMessage(final CharArrayBuffer buffer) throws HttpException {
         final RequestLine requestLine = getLineParser().parseRequestLine(buffer);
         final T request = this.requestFactory.newHttpRequest(requestLine.getMethod(), requestLine.getUri());
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestRequestParser.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestRequestParser.java
index 918f7dd..0fe8a20 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestRequestParser.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestRequestParser.java
@@ -33,8 +33,8 @@ import java.nio.charset.StandardCharsets;
 import org.apache.hc.core5.http.ClassicHttpRequest;
 import org.apache.hc.core5.http.ConnectionClosedException;
 import org.apache.hc.core5.http.Header;
-import org.apache.hc.core5.http.MessageConstraintException;
 import org.apache.hc.core5.http.Method;
+import org.apache.hc.core5.http.RequestHeaderFieldsTooLargeException;
 import org.apache.hc.core5.http.config.Http1Config;
 import org.apache.hc.core5.http.io.SessionInputBuffer;
 import org.junit.Assert;
@@ -95,7 +95,7 @@ public class TestRequestParser {
         Assert.assertEquals(1, headers.length);
     }
 
-    @Test(expected = MessageConstraintException.class)
+    @Test(expected = RequestHeaderFieldsTooLargeException.class)
     public void testBasicMessageParsingTooManyLeadingEmptyLines() throws Exception {
         final String s =
                 "\r\n" +


[httpcomponents-core] 03/04: Corrected handling of illegal or invalid request heads by async server side protocol handler

Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

olegk pushed a commit to branch development
in repository https://gitbox.apache.org/repos/asf/httpcomponents-core.git

commit 337401f41da3bfdf10cce0975f7780fea437cdb5
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Mon Dec 23 14:27:06 2019 +0100

    Corrected handling of illegal or invalid request heads by async server side protocol handler
---
 .../http/impl/nio/AbstractHttp1StreamDuplexer.java | 12 +++-
 .../http/impl/nio/ServerHttp1StreamDuplexer.java   | 36 +++++++++++
 .../http/impl/nio/ServerHttp1StreamHandler.java    | 73 +++++++++++++---------
 3 files changed, 88 insertions(+), 33 deletions(-)

diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/AbstractHttp1StreamDuplexer.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/AbstractHttp1StreamDuplexer.java
index 24aa6b8..70807f3 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/AbstractHttp1StreamDuplexer.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/AbstractHttp1StreamDuplexer.java
@@ -234,6 +234,14 @@ abstract class AbstractHttp1StreamDuplexer<IncomingMessage extends HttpMessage,
         processCommands();
     }
 
+    IncomingMessage parseMessageHead(final boolean endOfStream) throws IOException, HttpException {
+        final IncomingMessage messageHead = incomingMessageParser.parse(inbuf, endOfStream);
+        if (messageHead != null) {
+            incomingMessageParser.reset();
+        }
+        return messageHead;
+    }
+
     public final void onInput(final ByteBuffer src) throws HttpException, IOException {
         if (src != null) {
             inbuf.put(src);
@@ -256,10 +264,8 @@ abstract class AbstractHttp1StreamDuplexer<IncomingMessage extends HttpMessage,
         do {
             if (incomingMessage == null) {
 
-                final IncomingMessage messageHead = incomingMessageParser.parse(inbuf, endOfStream);
+                final IncomingMessage messageHead = parseMessageHead(endOfStream);
                 if (messageHead != null) {
-                    incomingMessageParser.reset();
-
                     this.version = messageHead.getVersion();
 
                     updateInputMetrics(messageHead, connMetrics);
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamDuplexer.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamDuplexer.java
index 850d645..50161f7 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamDuplexer.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamDuplexer.java
@@ -298,6 +298,42 @@ public class ServerHttp1StreamDuplexer extends AbstractHttp1StreamDuplexer<HttpR
     }
 
     @Override
+    HttpRequest parseMessageHead(final boolean endOfStream) throws IOException, HttpException {
+        try {
+            return super.parseMessageHead(endOfStream);
+        } catch (final HttpException ex) {
+            terminateExchange(ex);
+            return null;
+        }
+    }
+
+    void terminateExchange(final HttpException ex) throws HttpException, IOException {
+        final ServerHttp1StreamHandler streamHandler;
+        final HttpCoreContext context = HttpCoreContext.create();
+        context.setAttribute(HttpCoreContext.SSL_SESSION, getSSLSession());
+        context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, getEndpointDetails());
+        if (outgoing == null) {
+            streamHandler = new ServerHttp1StreamHandler(
+                    outputChannel,
+                    httpProcessor,
+                    connectionReuseStrategy,
+                    exchangeHandlerFactory,
+                    context);
+            outgoing = streamHandler;
+        } else {
+            streamHandler = new ServerHttp1StreamHandler(
+                    new DelayedOutputChannel(outputChannel),
+                    httpProcessor,
+                    connectionReuseStrategy,
+                    exchangeHandlerFactory,
+                    context);
+            pipeline.add(streamHandler);
+        }
+        streamHandler.terminateExchange(ex);
+        incoming = streamHandler;
+    }
+
+    @Override
     void consumeHeader(final HttpRequest request, final EntityDetails entityDetails) throws HttpException, IOException {
         if (streamListener != null) {
             streamListener.onRequestHead(this, request);
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java
index 6c7cb1b..0515179 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java
@@ -58,12 +58,12 @@ import org.apache.hc.core5.http.nio.support.ImmediateResponseExchangeHandler;
 import org.apache.hc.core5.http.protocol.HttpContext;
 import org.apache.hc.core5.http.protocol.HttpCoreContext;
 import org.apache.hc.core5.http.protocol.HttpProcessor;
-import org.apache.hc.core5.util.Asserts;
 
 class ServerHttp1StreamHandler implements ResourceHolder {
 
     private final Http1StreamChannel<HttpResponse> outputChannel;
     private final DataStreamChannel internalDataChannel;
+    private final ResponseChannel responseChannel;
     private final HttpProcessor httpProcessor;
     private final HandlerFactory<AsyncServerExchangeHandler> exchangeHandlerFactory;
     private final ConnectionReuseStrategy connectionReuseStrategy;
@@ -112,6 +112,33 @@ class ServerHttp1StreamHandler implements ResourceHolder {
 
         };
 
+        this.responseChannel = new ResponseChannel() {
+
+            @Override
+            public void sendInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
+                commitInformation(response);
+            }
+
+            @Override
+            public void sendResponse(
+                    final HttpResponse response, final EntityDetails responseEntityDetails, final HttpContext httpContext) throws HttpException, IOException {
+                ServerSupport.validateResponse(response, responseEntityDetails);
+                commitResponse(response, responseEntityDetails);
+            }
+
+            @Override
+            public void pushPromise(
+                    final HttpRequest promise, final AsyncPushProducer pushProducer, final HttpContext httpContext) throws HttpException, IOException {
+                commitPromise();
+            }
+
+            @Override
+            public String toString() {
+                return super.toString() + " " + ServerHttp1StreamHandler.this.toString();
+            }
+
+        };
+
         this.httpProcessor = httpProcessor;
         this.connectionReuseStrategy = connectionReuseStrategy;
         this.exchangeHandlerFactory = exchangeHandlerFactory;
@@ -138,12 +165,11 @@ class ServerHttp1StreamHandler implements ResourceHolder {
                 throw new HttpException("Invalid response: " + status);
             }
 
-            Asserts.notNull(receivedRequest, "Received request");
-            final String method = receivedRequest.getMethod();
             context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
             httpProcessor.process(response, responseEntityDetails, context);
 
-            final boolean endStream = responseEntityDetails == null || Method.HEAD.isSame(method);
+            final boolean endStream = responseEntityDetails == null ||
+                    (receivedRequest != null && Method.HEAD.isSame(receivedRequest.getMethod()));
 
             if (!connectionReuseStrategy.keepAlive(receivedRequest, response, context)) {
                 keepAlive = false;
@@ -195,6 +221,19 @@ class ServerHttp1StreamHandler implements ResourceHolder {
         return requestState == MessageState.COMPLETE && responseState == MessageState.COMPLETE;
     }
 
+    void terminateExchange(final HttpException ex) throws HttpException, IOException {
+        if (done.get() || requestState != MessageState.HEADERS) {
+            throw new ProtocolException("Unexpected message head");
+        }
+        receivedRequest = null;
+        requestState = MessageState.COMPLETE;
+        final AsyncResponseProducer responseProducer = new BasicResponseProducer(
+                ServerSupport.toStatusCode(ex),
+                ServerSupport.toErrorMessage(ex));
+        exchangeHandler = new ImmediateResponseExchangeHandler(responseProducer);
+        exchangeHandler.handleRequest(null, null, responseChannel, context);
+    }
+
     void consumeHeader(final HttpRequest request, final EntityDetails requestEntityDetails) throws HttpException, IOException {
         if (done.get() || requestState != MessageState.HEADERS) {
             throw new ProtocolException("Unexpected message head");
@@ -223,32 +262,6 @@ class ServerHttp1StreamHandler implements ResourceHolder {
         context.setProtocolVersion(transportVersion);
         context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
 
-        final ResponseChannel responseChannel = new ResponseChannel() {
-
-            @Override
-            public void sendInformation(final HttpResponse response, final HttpContext httpContext) throws HttpException, IOException {
-                commitInformation(response);
-            }
-
-            @Override
-            public void sendResponse(
-                    final HttpResponse response, final EntityDetails responseEntityDetails, final HttpContext httpContext) throws HttpException, IOException {
-                ServerSupport.validateResponse(response, responseEntityDetails);
-                commitResponse(response, responseEntityDetails);
-            }
-
-            @Override
-            public void pushPromise(
-                    final HttpRequest promise, final AsyncPushProducer pushProducer, final HttpContext httpContext) throws HttpException, IOException {
-                commitPromise();
-            }
-
-            @Override
-            public String toString() {
-                return super.toString() + " " + ServerHttp1StreamHandler.this.toString();
-            }
-
-        };
         try {
             httpProcessor.process(request, requestEntityDetails, context);
             exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);


[httpcomponents-core] 02/04: Fixed connection and wire logging in classic test server and client

Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

olegk pushed a commit to branch development
in repository https://gitbox.apache.org/repos/asf/httpcomponents-core.git

commit 6e38b3dcdf32d52d429b181f4d4eda976a5f975d
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Sat Dec 14 18:23:12 2019 +0100

    Fixed connection and wire logging in classic test server and client
---
 .../core5/testing/classic/ClassicTestClient.java   |  3 +-
 .../core5/testing/classic/ClassicTestServer.java   |  5 +-
 .../LoggingBHttpClientConnectionFactory.java       | 57 +++++++++++++++++++-
 .../LoggingBHttpServerConnectionFactory.java       | 63 +++++++++++++++++++++-
 4 files changed, 120 insertions(+), 8 deletions(-)

diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestClient.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestClient.java
index 2c2a4d8..9fc3e92 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestClient.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestClient.java
@@ -42,7 +42,6 @@ import org.apache.hc.core5.http.impl.DefaultAddressResolver;
 import org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy;
 import org.apache.hc.core5.http.impl.HttpProcessors;
 import org.apache.hc.core5.http.impl.bootstrap.HttpRequester;
-import org.apache.hc.core5.http.impl.io.DefaultBHttpClientConnectionFactory;
 import org.apache.hc.core5.http.impl.io.HttpRequestExecutor;
 import org.apache.hc.core5.http.io.HttpClientConnection;
 import org.apache.hc.core5.http.io.SocketConfig;
@@ -97,7 +96,7 @@ public class ClassicTestClient {
                     httpProcessor != null ? httpProcessor : HttpProcessors.client(),
                     connPool,
                     socketConfig,
-                    new DefaultBHttpClientConnectionFactory(Http1Config.DEFAULT, CharCodingConfig.DEFAULT),
+                    new LoggingBHttpClientConnectionFactory(Http1Config.DEFAULT, CharCodingConfig.DEFAULT),
                     sslContext != null ? sslContext.getSocketFactory() : null,
                     null,
                     null,
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestServer.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestServer.java
index 07590e4..c7d4ff4 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestServer.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/ClassicTestServer.java
@@ -38,14 +38,13 @@ import org.apache.hc.core5.function.Decorator;
 import org.apache.hc.core5.http.URIScheme;
 import org.apache.hc.core5.http.config.CharCodingConfig;
 import org.apache.hc.core5.http.config.Http1Config;
-import org.apache.hc.core5.http.io.SocketConfig;
 import org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy;
 import org.apache.hc.core5.http.impl.HttpProcessors;
 import org.apache.hc.core5.http.impl.bootstrap.HttpServer;
-import org.apache.hc.core5.http.impl.io.DefaultBHttpServerConnectionFactory;
 import org.apache.hc.core5.http.impl.io.HttpService;
 import org.apache.hc.core5.http.io.HttpRequestHandler;
 import org.apache.hc.core5.http.io.HttpServerRequestHandler;
+import org.apache.hc.core5.http.io.SocketConfig;
 import org.apache.hc.core5.http.io.support.BasicHttpServerExpectationDecorator;
 import org.apache.hc.core5.http.io.support.BasicHttpServerRequestHandler;
 import org.apache.hc.core5.http.protocol.HttpProcessor;
@@ -114,7 +113,7 @@ public class ClassicTestServer {
                     null,
                     socketConfig,
                     sslContext != null ? sslContext.getServerSocketFactory() : ServerSocketFactory.getDefault(),
-                    new DefaultBHttpServerConnectionFactory(
+                    new LoggingBHttpServerConnectionFactory(
                             sslContext != null ? URIScheme.HTTPS.id : URIScheme.HTTP.id,
                             Http1Config.DEFAULT,
                             CharCodingConfig.DEFAULT),
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpClientConnectionFactory.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpClientConnectionFactory.java
index 31a45a0..40ed703 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpClientConnectionFactory.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpClientConnectionFactory.java
@@ -30,16 +30,71 @@ package org.apache.hc.core5.testing.classic;
 import java.io.IOException;
 import java.net.Socket;
 
+import org.apache.hc.core5.http.ClassicHttpRequest;
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.ContentLengthStrategy;
+import org.apache.hc.core5.http.config.CharCodingConfig;
 import org.apache.hc.core5.http.config.Http1Config;
+import org.apache.hc.core5.http.impl.CharCodingSupport;
 import org.apache.hc.core5.http.io.HttpConnectionFactory;
+import org.apache.hc.core5.http.io.HttpMessageParserFactory;
+import org.apache.hc.core5.http.io.HttpMessageWriterFactory;
 
 public class LoggingBHttpClientConnectionFactory implements HttpConnectionFactory<LoggingBHttpClientConnection> {
 
     public static final LoggingBHttpClientConnectionFactory INSTANCE = new LoggingBHttpClientConnectionFactory();
 
+    private final Http1Config http1Config;
+    private final CharCodingConfig charCodingConfig;
+    private final ContentLengthStrategy incomingContentStrategy;
+    private final ContentLengthStrategy outgoingContentStrategy;
+    private final HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory;
+    private final HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory;
+
+    public LoggingBHttpClientConnectionFactory(
+            final Http1Config http1Config,
+            final CharCodingConfig charCodingConfig,
+            final ContentLengthStrategy incomingContentStrategy,
+            final ContentLengthStrategy outgoingContentStrategy,
+            final HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory,
+            final HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory) {
+        super();
+        this.http1Config = http1Config != null ? http1Config : Http1Config.DEFAULT;
+        this.charCodingConfig = charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT;
+        this.incomingContentStrategy = incomingContentStrategy;
+        this.outgoingContentStrategy = outgoingContentStrategy;
+        this.requestWriterFactory = requestWriterFactory;
+        this.responseParserFactory = responseParserFactory;
+    }
+
+    public LoggingBHttpClientConnectionFactory(
+            final Http1Config http1Config,
+            final CharCodingConfig charCodingConfig,
+            final HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory,
+            final HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory) {
+        this(http1Config, charCodingConfig, null, null, requestWriterFactory, responseParserFactory);
+    }
+
+    public LoggingBHttpClientConnectionFactory(
+            final Http1Config http1Config,
+            final CharCodingConfig charCodingConfig) {
+        this(http1Config, charCodingConfig, null, null, null, null);
+    }
+
+    public LoggingBHttpClientConnectionFactory() {
+        this(null, null, null, null, null, null);
+    }
+
     @Override
     public LoggingBHttpClientConnection createConnection(final Socket socket) throws IOException {
-        final LoggingBHttpClientConnection conn = new LoggingBHttpClientConnection(Http1Config.DEFAULT);
+        final LoggingBHttpClientConnection conn = new LoggingBHttpClientConnection(
+                http1Config,
+                CharCodingSupport.createDecoder(charCodingConfig),
+                CharCodingSupport.createEncoder(charCodingConfig),
+                incomingContentStrategy,
+                outgoingContentStrategy,
+                requestWriterFactory,
+                responseParserFactory);
         conn.bind(socket);
         return conn;
     }
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpServerConnectionFactory.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpServerConnectionFactory.java
index ad57c20..8e9a2aa 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpServerConnectionFactory.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpServerConnectionFactory.java
@@ -32,19 +32,78 @@ import java.net.Socket;
 
 import javax.net.ssl.SSLSocket;
 
+import org.apache.hc.core5.http.ClassicHttpRequest;
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.ContentLengthStrategy;
 import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.config.CharCodingConfig;
 import org.apache.hc.core5.http.config.Http1Config;
+import org.apache.hc.core5.http.impl.CharCodingSupport;
 import org.apache.hc.core5.http.io.HttpConnectionFactory;
+import org.apache.hc.core5.http.io.HttpMessageParserFactory;
+import org.apache.hc.core5.http.io.HttpMessageWriterFactory;
 
 public class LoggingBHttpServerConnectionFactory implements HttpConnectionFactory<LoggingBHttpServerConnection> {
 
     public static final LoggingBHttpServerConnectionFactory INSTANCE = new LoggingBHttpServerConnectionFactory();
 
+    private final String scheme;
+    private final Http1Config http1Config;
+    private final CharCodingConfig charCodingConfig;
+    private final ContentLengthStrategy incomingContentStrategy;
+    private final ContentLengthStrategy outgoingContentStrategy;
+    private final HttpMessageParserFactory<ClassicHttpRequest> requestParserFactory;
+    private final HttpMessageWriterFactory<ClassicHttpResponse> responseWriterFactory;
+
+    public LoggingBHttpServerConnectionFactory(
+            final String scheme,
+            final Http1Config http1Config,
+            final CharCodingConfig charCodingConfig,
+            final ContentLengthStrategy incomingContentStrategy,
+            final ContentLengthStrategy outgoingContentStrategy,
+            final HttpMessageParserFactory<ClassicHttpRequest> requestParserFactory,
+            final HttpMessageWriterFactory<ClassicHttpResponse> responseWriterFactory) {
+        super();
+        this.scheme = scheme;
+        this.http1Config = http1Config != null ? http1Config : Http1Config.DEFAULT;
+        this.charCodingConfig = charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT;
+        this.incomingContentStrategy = incomingContentStrategy;
+        this.outgoingContentStrategy = outgoingContentStrategy;
+        this.requestParserFactory = requestParserFactory;
+        this.responseWriterFactory = responseWriterFactory;
+    }
+
+    public LoggingBHttpServerConnectionFactory(
+            final String scheme,
+            final Http1Config http1Config,
+            final CharCodingConfig charCodingConfig,
+            final HttpMessageParserFactory<ClassicHttpRequest> requestParserFactory,
+            final HttpMessageWriterFactory<ClassicHttpResponse> responseWriterFactory) {
+        this(scheme, http1Config, charCodingConfig, null, null, requestParserFactory, responseWriterFactory);
+    }
+
+    public LoggingBHttpServerConnectionFactory(
+            final String scheme,
+            final Http1Config http1Config,
+            final CharCodingConfig charCodingConfig) {
+        this(scheme, http1Config, charCodingConfig, null, null, null, null);
+    }
+
+    public LoggingBHttpServerConnectionFactory() {
+        this(null, null, null, null, null, null, null);
+    }
+
     @Override
     public LoggingBHttpServerConnection createConnection(final Socket socket) throws IOException {
         final LoggingBHttpServerConnection conn = new LoggingBHttpServerConnection(
-                socket instanceof SSLSocket ? URIScheme.HTTPS.id : URIScheme.HTTP.id,
-                Http1Config.DEFAULT);
+                scheme != null ? scheme : (socket instanceof SSLSocket ? URIScheme.HTTPS.id : URIScheme.HTTP.id),
+                http1Config,
+                CharCodingSupport.createDecoder(charCodingConfig),
+                CharCodingSupport.createEncoder(charCodingConfig),
+                incomingContentStrategy,
+                outgoingContentStrategy,
+                requestParserFactory,
+                responseWriterFactory);
         conn.bind(socket);
         return conn;
     }


[httpcomponents-core] 01/04: Re-use server support code in classic HttpService

Posted by ol...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

olegk pushed a commit to branch development
in repository https://gitbox.apache.org/repos/asf/httpcomponents-core.git

commit 272d0c6de221cce49bc75d2ef7b1e393906b89af
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Fri Dec 13 15:19:34 2019 +0100

    Re-use server support code in classic HttpService
---
 .../http2/impl/nio/ServerH2StreamHandler.java      |  7 +++++--
 .../core5/http/impl/{nio => }/ServerSupport.java   | 13 ++++--------
 .../apache/hc/core5/http/impl/io/HttpService.java  | 24 +++++-----------------
 .../http/impl/nio/ServerHttp1StreamHandler.java    |  6 +++++-
 4 files changed, 19 insertions(+), 31 deletions(-)

diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2StreamHandler.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2StreamHandler.java
index 9a5db5f..fb61bf3 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2StreamHandler.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2StreamHandler.java
@@ -42,8 +42,8 @@ import org.apache.hc.core5.http.Method;
 import org.apache.hc.core5.http.ProtocolException;
 import org.apache.hc.core5.http.impl.BasicHttpConnectionMetrics;
 import org.apache.hc.core5.http.impl.IncomingEntityDetails;
+import org.apache.hc.core5.http.impl.ServerSupport;
 import org.apache.hc.core5.http.impl.nio.MessageState;
-import org.apache.hc.core5.http.impl.nio.ServerSupport;
 import org.apache.hc.core5.http.nio.AsyncPushConsumer;
 import org.apache.hc.core5.http.nio.AsyncPushProducer;
 import org.apache.hc.core5.http.nio.AsyncResponseProducer;
@@ -51,6 +51,7 @@ import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
 import org.apache.hc.core5.http.nio.DataStreamChannel;
 import org.apache.hc.core5.http.nio.HandlerFactory;
 import org.apache.hc.core5.http.nio.ResponseChannel;
+import org.apache.hc.core5.http.nio.support.BasicResponseProducer;
 import org.apache.hc.core5.http.nio.support.ImmediateResponseExchangeHandler;
 import org.apache.hc.core5.http.protocol.HttpContext;
 import org.apache.hc.core5.http.protocol.HttpCoreContext;
@@ -241,7 +242,9 @@ public class ServerH2StreamHandler implements H2StreamHandler {
                     exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
                 } catch (final HttpException ex) {
                     if (!responseCommitted.get()) {
-                        final AsyncResponseProducer responseProducer = ServerSupport.handleException(ex);
+                        final AsyncResponseProducer responseProducer = new BasicResponseProducer(
+                                ServerSupport.toStatusCode(ex),
+                                ServerSupport.toErrorMessage(ex));
                         exchangeHandler = new ImmediateResponseExchangeHandler(responseProducer);
                         exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
                     } else {
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerSupport.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/ServerSupport.java
similarity index 86%
rename from httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerSupport.java
rename to httpcore5/src/main/java/org/apache/hc/core5/http/impl/ServerSupport.java
index db20285..29cca6b 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerSupport.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/ServerSupport.java
@@ -24,7 +24,7 @@
  * <http://www.apache.org/>.
  *
  */
-package org.apache.hc.core5.http.impl.nio;
+package org.apache.hc.core5.http.impl;
 
 import org.apache.hc.core5.annotation.Internal;
 import org.apache.hc.core5.http.EntityDetails;
@@ -35,8 +35,6 @@ import org.apache.hc.core5.http.MethodNotSupportedException;
 import org.apache.hc.core5.http.NotImplementedException;
 import org.apache.hc.core5.http.ProtocolException;
 import org.apache.hc.core5.http.UnsupportedHttpVersionException;
-import org.apache.hc.core5.http.nio.AsyncResponseProducer;
-import org.apache.hc.core5.http.nio.support.BasicResponseProducer;
 
 /**
  * HTTP Server support methods.
@@ -59,12 +57,9 @@ public class ServerSupport {
         }
     }
 
-    public static AsyncResponseProducer handleException(final Exception ex) {
-        String message = ex.getMessage();
-        if (message == null) {
-            message = ex.toString();
-        }
-        return new BasicResponseProducer(toStatusCode(ex), message);
+    public static String toErrorMessage(final Exception ex) {
+        final String message = ex.getMessage();
+        return message != null ? message : ex.toString();
     }
 
     public static int toStatusCode(final Exception ex) {
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java
index 91a3955..31dd3a1 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java
@@ -42,13 +42,10 @@ import org.apache.hc.core5.http.HttpHeaders;
 import org.apache.hc.core5.http.HttpRequestMapper;
 import org.apache.hc.core5.http.HttpResponseFactory;
 import org.apache.hc.core5.http.HttpStatus;
-import org.apache.hc.core5.http.MethodNotSupportedException;
-import org.apache.hc.core5.http.NotImplementedException;
-import org.apache.hc.core5.http.ProtocolException;
 import org.apache.hc.core5.http.ProtocolVersion;
-import org.apache.hc.core5.http.UnsupportedHttpVersionException;
 import org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy;
 import org.apache.hc.core5.http.impl.Http1StreamListener;
+import org.apache.hc.core5.http.impl.ServerSupport;
 import org.apache.hc.core5.http.io.HttpRequestHandler;
 import org.apache.hc.core5.http.io.HttpServerConnection;
 import org.apache.hc.core5.http.io.HttpServerRequestHandler;
@@ -210,6 +207,7 @@ public class HttpService {
                 @Override
                 public void submitResponse(final ClassicHttpResponse response) throws HttpException, IOException {
                     try {
+                        ServerSupport.validateResponse(response, response.getEntity());
                         context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
                         processor.process(response, response.getEntity(), context);
 
@@ -267,7 +265,7 @@ public class HttpService {
      * @param response the HTTP response.
      */
     protected void handleException(final HttpException ex, final ClassicHttpResponse response) {
-        response.setCode(toStatusCode(ex, response));
+        response.setCode(toStatusCode(ex));
         String message = ex.getMessage();
         if (message == null) {
             message = ex.toString();
@@ -275,20 +273,8 @@ public class HttpService {
         response.setEntity(new StringEntity(message, ContentType.TEXT_PLAIN));
     }
 
-    protected int toStatusCode(final Exception ex, final ClassicHttpResponse response) {
-        final int code;
-        if (ex instanceof MethodNotSupportedException) {
-            code = HttpStatus.SC_NOT_IMPLEMENTED;
-        } else if (ex instanceof UnsupportedHttpVersionException) {
-            code = HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED;
-        } else if (ex instanceof NotImplementedException) {
-            code = HttpStatus.SC_NOT_IMPLEMENTED;
-        } else if (ex instanceof ProtocolException) {
-            code = HttpStatus.SC_BAD_REQUEST;
-        } else {
-            code = HttpStatus.SC_INTERNAL_SERVER_ERROR;
-        }
-        return code;
+    protected int toStatusCode(final Exception ex) {
+        return ServerSupport.toStatusCode(ex);
     }
 
 }
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java
index 4083ca9..6c7cb1b 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java
@@ -44,6 +44,7 @@ import org.apache.hc.core5.http.MisdirectedRequestException;
 import org.apache.hc.core5.http.ProtocolException;
 import org.apache.hc.core5.http.ProtocolVersion;
 import org.apache.hc.core5.http.UnsupportedHttpVersionException;
+import org.apache.hc.core5.http.impl.ServerSupport;
 import org.apache.hc.core5.http.nio.AsyncPushProducer;
 import org.apache.hc.core5.http.nio.AsyncResponseProducer;
 import org.apache.hc.core5.http.nio.AsyncServerExchangeHandler;
@@ -52,6 +53,7 @@ import org.apache.hc.core5.http.nio.DataStreamChannel;
 import org.apache.hc.core5.http.nio.HandlerFactory;
 import org.apache.hc.core5.http.nio.ResourceHolder;
 import org.apache.hc.core5.http.nio.ResponseChannel;
+import org.apache.hc.core5.http.nio.support.BasicResponseProducer;
 import org.apache.hc.core5.http.nio.support.ImmediateResponseExchangeHandler;
 import org.apache.hc.core5.http.protocol.HttpContext;
 import org.apache.hc.core5.http.protocol.HttpCoreContext;
@@ -252,7 +254,9 @@ class ServerHttp1StreamHandler implements ResourceHolder {
             exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
         } catch (final HttpException ex) {
             if (!responseCommitted.get()) {
-                final AsyncResponseProducer responseProducer = ServerSupport.handleException(ex);
+                final AsyncResponseProducer responseProducer = new BasicResponseProducer(
+                        ServerSupport.toStatusCode(ex),
+                        ServerSupport.toErrorMessage(ex));
                 exchangeHandler = new ImmediateResponseExchangeHandler(responseProducer);
                 exchangeHandler.handleRequest(request, requestEntityDetails, responseChannel, context);
             } else {