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 2020/10/30 16:50:14 UTC

[httpcomponents-core] branch tls_upgrade_redesign updated (92c0e5e -> aef5a00)

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

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


 discard 92c0e5e  Revised HTTP protocol negotiation for non-blocking I/O sessions
     new aef5a00  Revised HTTP protocol negotiation for non-blocking I/O sessions

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   (92c0e5e)
            \
             N -- N -- N   refs/heads/tls_upgrade_redesign (aef5a00)

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 1 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/ClientHttpProtocolNegotiator.java     | 141 ++---------------
 .../impl/nio/H2OnlyClientProtocolNegotiator.java   | 172 +++++++--------------
 ...Negotiator.java => ProtocolNegotiatorBase.java} | 124 ++++++---------
 .../impl/nio/ServerHttpProtocolNegotiator.java     | 133 +---------------
 4 files changed, 118 insertions(+), 452 deletions(-)
 copy httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/{H2OnlyClientProtocolNegotiator.java => ProtocolNegotiatorBase.java} (53%)


[httpcomponents-core] 01/01: Revised HTTP protocol negotiation for non-blocking I/O sessions

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

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

commit aef5a0077202c6d8ecb5f9226ab71715e9e21dbd
Author: Oleg Kalnichevski <ol...@apache.org>
AuthorDate: Thu Oct 29 15:43:45 2020 +0100

    Revised HTTP protocol negotiation for non-blocking I/O sessions
---
 .../impl/nio/ClientHttpProtocolNegotiator.java     | 203 +++++-----------
 .../impl/nio/H2OnlyClientProtocolNegotiator.java   | 172 +++++---------
 .../impl/nio/ProtocolNegotiationException.java     |  49 ++++
 ...Negotiator.java => ProtocolNegotiatorBase.java} | 124 ++++------
 .../impl/nio/ServerHttpProtocolNegotiator.java     | 254 +++++++--------------
 5 files changed, 294 insertions(+), 508 deletions(-)

diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientHttpProtocolNegotiator.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientHttpProtocolNegotiator.java
index 30e6117..9e1cb7c 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientHttpProtocolNegotiator.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientHttpProtocolNegotiator.java
@@ -28,32 +28,22 @@
 package org.apache.hc.core5.http2.impl.nio;
 
 import java.io.IOException;
-import java.net.SocketAddress;
 import java.nio.ByteBuffer;
 import java.nio.channels.ByteChannel;
 import java.nio.channels.SelectionKey;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.net.ssl.SSLSession;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.apache.hc.core5.annotation.Internal;
-import org.apache.hc.core5.http.EndpointDetails;
-import org.apache.hc.core5.http.ProtocolVersion;
+import org.apache.hc.core5.concurrent.FutureCallback;
 import org.apache.hc.core5.http.impl.nio.BufferedData;
 import org.apache.hc.core5.http.impl.nio.ClientHttp1IOEventHandler;
-import org.apache.hc.core5.http.impl.nio.ClientHttp1StreamDuplexer;
 import org.apache.hc.core5.http.impl.nio.ClientHttp1StreamDuplexerFactory;
-import org.apache.hc.core5.http.impl.nio.HttpConnectionEventHandler;
-import org.apache.hc.core5.http.nio.command.CommandSupport;
 import org.apache.hc.core5.http2.HttpVersionPolicy;
 import org.apache.hc.core5.http2.ssl.ApplicationProtocol;
-import org.apache.hc.core5.io.CloseMode;
-import org.apache.hc.core5.io.SocketTimeoutExceptionFactory;
 import org.apache.hc.core5.reactor.IOSession;
 import org.apache.hc.core5.reactor.ProtocolIOSession;
 import org.apache.hc.core5.reactor.ssl.TlsDetails;
 import org.apache.hc.core5.util.Args;
-import org.apache.hc.core5.util.Timeout;
 
 /**
  * I/O event handler for events fired by {@link ProtocolIOSession} that implements
@@ -63,7 +53,7 @@ import org.apache.hc.core5.util.Timeout;
  * @since 5.0
  */
 @Internal
-public class ClientHttpProtocolNegotiator implements HttpConnectionEventHandler {
+public class ClientHttpProtocolNegotiator extends ProtocolNegotiatorBase {
 
     // PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n
     final static byte[] PREFACE = new byte[] {
@@ -71,11 +61,10 @@ public class ClientHttpProtocolNegotiator implements HttpConnectionEventHandler
             0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a, 0x0d, 0x0a, 0x53, 0x4d,
             0x0d, 0x0a, 0x0d, 0x0a};
 
-    private final ProtocolIOSession ioSession;
     private final ClientHttp1StreamDuplexerFactory http1StreamHandlerFactory;
     private final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory;
     private final HttpVersionPolicy versionPolicy;
-    private final AtomicReference<HttpConnectionEventHandler> protocolHandlerRef;
+    private final AtomicBoolean initialized;
 
     private volatile ByteBuffer preface;
     private volatile BufferedData inBuf;
@@ -85,62 +74,42 @@ public class ClientHttpProtocolNegotiator implements HttpConnectionEventHandler
             final ClientHttp1StreamDuplexerFactory http1StreamHandlerFactory,
             final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory,
             final HttpVersionPolicy versionPolicy) {
-        this.ioSession = Args.notNull(ioSession, "I/O session");
+        this(ioSession, http1StreamHandlerFactory, http2StreamHandlerFactory, versionPolicy, null);
+    }
+
+    /**
+     * @since 5.1
+     */
+    public ClientHttpProtocolNegotiator(
+            final ProtocolIOSession ioSession,
+            final ClientHttp1StreamDuplexerFactory http1StreamHandlerFactory,
+            final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory,
+            final HttpVersionPolicy versionPolicy,
+            final FutureCallback<ProtocolIOSession> resultCallback) {
+        super(ioSession, resultCallback);
         this.http1StreamHandlerFactory = Args.notNull(http1StreamHandlerFactory, "HTTP/1.1 stream handler factory");
         this.http2StreamHandlerFactory = Args.notNull(http2StreamHandlerFactory, "HTTP/2 stream handler factory");
         this.versionPolicy = versionPolicy != null ? versionPolicy : HttpVersionPolicy.NEGOTIATE;
-        this.protocolHandlerRef = new AtomicReference<>(null);
+        this.initialized = new AtomicBoolean();
     }
 
-    private void startHttp1(final IOSession session) {
-        final ClientHttp1StreamDuplexer http1StreamHandler = http1StreamHandlerFactory.create(ioSession);
-        final HttpConnectionEventHandler protocolHandler = new ClientHttp1IOEventHandler(http1StreamHandler);
-        try {
-            ioSession.upgrade(protocolHandler);
-            protocolHandlerRef.set(protocolHandler);
-            protocolHandler.connected(session);
-            if (inBuf != null) {
-                protocolHandler.inputReady(session, inBuf.data());
-                inBuf.clear();
-            }
-        } catch (final Exception ex) {
-            protocolHandler.exception(session, ex);
-            session.close(CloseMode.IMMEDIATE);
+    private void startHttp1() throws IOException {
+        final ByteBuffer data = inBuf != null ? inBuf.data() : null;
+        startProtocol(new ClientHttp1IOEventHandler(http1StreamHandlerFactory.create(ioSession)), data);
+        if (inBuf != null) {
+            inBuf.clear();
         }
     }
 
-    private void startHttp2(final IOSession session) {
-        final ClientH2StreamMultiplexer streamMultiplexer = http2StreamHandlerFactory.create(ioSession);
-        final HttpConnectionEventHandler protocolHandler = new ClientH2IOEventHandler(streamMultiplexer);
-        try {
-            ioSession.upgrade(protocolHandler);
-            protocolHandlerRef.set(protocolHandler);
-            protocolHandler.connected(session);
-            if (inBuf != null) {
-                protocolHandler.inputReady(session, inBuf.data());
-                inBuf.clear();
-            }
-        } catch (final Exception ex) {
-            protocolHandler.exception(session, ex);
-            session.close(CloseMode.IMMEDIATE);
+    private void startHttp2() throws IOException {
+        final ByteBuffer data = inBuf != null ? inBuf.data() : null;
+        startProtocol(new ClientH2IOEventHandler(http2StreamHandlerFactory.create(ioSession)), data);
+        if (inBuf != null) {
+            inBuf.clear();
         }
     }
 
-    private void writeOutPreface(final IOSession session) throws IOException {
-        if (preface.hasRemaining()) {
-            final ByteChannel channel = session;
-            channel.write(preface);
-        }
-        if (!preface.hasRemaining()) {
-            session.clearEvent(SelectionKey.OP_WRITE);
-            startHttp2(session);
-        } else {
-            session.setEvent(SelectionKey.OP_WRITE);
-        }
-    }
-
-    @Override
-    public void connected(final IOSession session) throws IOException {
+    private void initialize() throws IOException {
         switch (versionPolicy) {
             case NEGOTIATE:
                 final TlsDetails tlsDetails = ioSession.getTlsDetails();
@@ -156,8 +125,30 @@ public class ClientHttpProtocolNegotiator implements HttpConnectionEventHandler
                 break;
         }
         if (preface == null) {
-            startHttp1(session);
+            startHttp1();
         } else {
+            ioSession.setEvent(SelectionKey.OP_WRITE);
+        }
+    }
+
+    private void writeOutPreface(final IOSession session) throws IOException {
+        if (preface.hasRemaining()) {
+            final ByteChannel channel = session;
+            channel.write(preface);
+        }
+        if (!preface.hasRemaining()) {
+            session.clearEvent(SelectionKey.OP_WRITE);
+            startHttp2();
+            preface = null;
+        }
+    }
+
+    @Override
+    public void connected(final IOSession session) throws IOException {
+        if (initialized.compareAndSet(false, true)) {
+            initialize();
+        }
+        if (preface != null) {
             writeOutPreface(session);
         }
     }
@@ -170,102 +161,28 @@ public class ClientHttpProtocolNegotiator implements HttpConnectionEventHandler
             }
             inBuf.put(src);
         }
-        outputReady(session);
-    }
-
-    @Override
-    public void outputReady(final IOSession session) throws IOException {
         if (preface != null) {
             writeOutPreface(session);
         } else {
-            session.close(CloseMode.GRACEFUL);
+            throw new ProtocolNegotiationException("Unexpected input");
         }
     }
 
     @Override
-    public void timeout(final IOSession session, final Timeout timeout) {
-        exception(session, SocketTimeoutExceptionFactory.create(timeout));
-    }
-
-    @Override
-    public void exception(final IOSession session, final Exception cause) {
-        session.close(CloseMode.IMMEDIATE);
-        final HttpConnectionEventHandler protocolHandler = protocolHandlerRef.get();
-        if (protocolHandler != null) {
-            protocolHandler.exception(session, cause);
-        } else {
-            CommandSupport.failCommands(session, cause);
+    public void outputReady(final IOSession session) throws IOException {
+        if (initialized.compareAndSet(false, true)) {
+            initialize();
         }
-    }
-
-    @Override
-    public void disconnected(final IOSession session) {
-        final HttpConnectionEventHandler protocolHandler = protocolHandlerRef.getAndSet(null);
-        if (protocolHandler != null) {
-            protocolHandler.disconnected(ioSession);
+        if (preface != null) {
+            writeOutPreface(session);
         } else {
-            CommandSupport.cancelCommands(session);
+            throw new ProtocolNegotiationException("Unexpected output");
         }
     }
 
     @Override
-    public SSLSession getSSLSession() {
-        final TlsDetails tlsDetails = ioSession.getTlsDetails();
-        return tlsDetails != null ? tlsDetails.getSSLSession() : null;
-    }
-
-    @Override
-    public EndpointDetails getEndpointDetails() {
-        final HttpConnectionEventHandler protocolHandler = protocolHandlerRef.get();
-        return protocolHandler != null ? protocolHandler.getEndpointDetails() : null;
-    }
-
-    @Override
-    public void setSocketTimeout(final Timeout timeout) {
-        ioSession.setSocketTimeout(timeout);
-    }
-
-    @Override
-    public Timeout getSocketTimeout() {
-        return ioSession.getSocketTimeout();
-    }
-
-    @Override
-    public ProtocolVersion getProtocolVersion() {
-        final HttpConnectionEventHandler protocolHandler = protocolHandlerRef.get();
-        return protocolHandler != null ? protocolHandler.getProtocolVersion() : null;
-    }
-
-    @Override
-    public SocketAddress getRemoteAddress() {
-        return ioSession.getRemoteAddress();
-    }
-
-    @Override
-    public SocketAddress getLocalAddress() {
-        return ioSession.getLocalAddress();
-    }
-
-    @Override
-    public boolean isOpen() {
-        return ioSession.isOpen();
-    }
-
-    @Override
-    public void close() throws IOException {
-        ioSession.close();
-    }
-
-    @Override
-    public void close(final CloseMode closeMode) {
-        ioSession.close(closeMode);
-    }
-
-    @Override
     public String toString() {
-        return "[" +
-                "versionPolicy=" + versionPolicy +
-                ']';
+        return getClass().getName() + "/" + versionPolicy;
     }
 
 }
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/H2OnlyClientProtocolNegotiator.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/H2OnlyClientProtocolNegotiator.java
index c6721cb..1a14b3c 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/H2OnlyClientProtocolNegotiator.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/H2OnlyClientProtocolNegotiator.java
@@ -28,28 +28,19 @@
 package org.apache.hc.core5.http2.impl.nio;
 
 import java.io.IOException;
-import java.net.SocketAddress;
 import java.nio.ByteBuffer;
 import java.nio.channels.ByteChannel;
-
-import javax.net.ssl.SSLSession;
+import java.nio.channels.SelectionKey;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.apache.hc.core5.annotation.Internal;
-import org.apache.hc.core5.http.EndpointDetails;
-import org.apache.hc.core5.http.HttpException;
-import org.apache.hc.core5.http.ProtocolVersion;
-import org.apache.hc.core5.http.impl.nio.HttpConnectionEventHandler;
-import org.apache.hc.core5.http.nio.command.CommandSupport;
+import org.apache.hc.core5.concurrent.FutureCallback;
 import org.apache.hc.core5.http2.ssl.ApplicationProtocol;
-import org.apache.hc.core5.io.CloseMode;
-import org.apache.hc.core5.io.SocketTimeoutExceptionFactory;
-import org.apache.hc.core5.reactor.IOEventHandler;
 import org.apache.hc.core5.reactor.IOSession;
 import org.apache.hc.core5.reactor.ProtocolIOSession;
 import org.apache.hc.core5.reactor.ssl.TlsDetails;
 import org.apache.hc.core5.util.Args;
 import org.apache.hc.core5.util.TextUtils;
-import org.apache.hc.core5.util.Timeout;
 
 /**
  * I/O event handler for events fired by {@link ProtocolIOSession} that implements
@@ -59,147 +50,100 @@ import org.apache.hc.core5.util.Timeout;
  * @since 5.0
  */
 @Internal
-public class H2OnlyClientProtocolNegotiator implements HttpConnectionEventHandler {
+public class H2OnlyClientProtocolNegotiator extends ProtocolNegotiatorBase {
 
-    private final ProtocolIOSession ioSession;
     private final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory;
     private final boolean strictALPNHandshake;
+    private final AtomicBoolean initialized;
 
-    private final ByteBuffer preface;
+    private volatile ByteBuffer preface;
 
     public H2OnlyClientProtocolNegotiator(
             final ProtocolIOSession ioSession,
             final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory,
             final boolean strictALPNHandshake) {
-        this.ioSession = Args.notNull(ioSession, "I/O session");
+        this(ioSession, http2StreamHandlerFactory, strictALPNHandshake, null);
+    }
+
+    /**
+     * @since 5.1
+     */
+    public H2OnlyClientProtocolNegotiator(
+            final ProtocolIOSession ioSession,
+            final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory,
+            final boolean strictALPNHandshake,
+            final FutureCallback<ProtocolIOSession> resultCallback) {
+        super(ioSession, resultCallback);
         this.http2StreamHandlerFactory = Args.notNull(http2StreamHandlerFactory, "HTTP/2 stream handler factory");
         this.strictALPNHandshake = strictALPNHandshake;
-        this.preface = ByteBuffer.wrap(ClientHttpProtocolNegotiator.PREFACE);
+        this.initialized = new AtomicBoolean();
     }
 
-    @Override
-    public void connected(final IOSession session) {
-        try {
-            final TlsDetails tlsDetails = ioSession.getTlsDetails();
-            if (tlsDetails != null) {
-                final String applicationProtocol = tlsDetails.getApplicationProtocol();
-                if (TextUtils.isEmpty(applicationProtocol)) {
-                    if (strictALPNHandshake) {
-                        throw new HttpException("ALPN: missing application protocol");
-                    }
-                } else {
-                    if (!ApplicationProtocol.HTTP_2.id.equals(applicationProtocol)) {
-                        throw new HttpException("ALPN: unexpected application protocol '" + applicationProtocol + "'");
-                    }
+    private void initialize() throws IOException {
+        final TlsDetails tlsDetails = ioSession.getTlsDetails();
+        if (tlsDetails != null) {
+            final String applicationProtocol = tlsDetails.getApplicationProtocol();
+            if (TextUtils.isEmpty(applicationProtocol)) {
+                if (strictALPNHandshake) {
+                    throw new ProtocolNegotiationException("ALPN: missing application protocol");
+                }
+            } else {
+                if (!ApplicationProtocol.HTTP_2.id.equals(applicationProtocol)) {
+                    throw new ProtocolNegotiationException("ALPN: unexpected application protocol '" + applicationProtocol + "'");
                 }
             }
-            writePreface(session);
-        } catch (final Exception ex) {
-            session.close(CloseMode.IMMEDIATE);
-            exception(session, ex);
         }
+        this.preface = ByteBuffer.wrap(ClientHttpProtocolNegotiator.PREFACE);
+        ioSession.setEvent(SelectionKey.OP_WRITE);
     }
 
-    private void writePreface(final IOSession session) throws IOException  {
+    private void writeOutPreface(final IOSession session) throws IOException  {
         if (preface.hasRemaining()) {
             final ByteChannel channel = session;
             channel.write(preface);
         }
         if (!preface.hasRemaining()) {
+            session.clearEvent(SelectionKey.OP_WRITE);
             final ClientH2StreamMultiplexer streamMultiplexer = http2StreamHandlerFactory.create(ioSession);
-            final IOEventHandler newHandler = new ClientH2IOEventHandler(streamMultiplexer);
-            newHandler.connected(session);
-            ioSession.upgrade(newHandler);
+            startProtocol(new ClientH2IOEventHandler(streamMultiplexer), null);
+            preface = null;
         }
     }
 
     @Override
-    public void inputReady(final IOSession session, final ByteBuffer src) {
-        outputReady(session);
-    }
-
-    @Override
-    public void outputReady(final IOSession session) {
-        try {
-            if (preface != null) {
-                writePreface(session);
-            } else {
-                session.close(CloseMode.GRACEFUL);
-            }
-        } catch (final IOException ex) {
-            session.close(CloseMode.IMMEDIATE);
-            exception(session, ex);
+    public void connected(final IOSession session) throws IOException {
+        if (initialized.compareAndSet(false, true)) {
+            initialize();
         }
     }
 
     @Override
-    public void timeout(final IOSession session, final Timeout timeout) {
-        exception(session, SocketTimeoutExceptionFactory.create(timeout));
-    }
-
-    @Override
-    public void exception(final IOSession session, final Exception cause) {
-        try {
-            CommandSupport.failCommands(session, cause);
-        } finally {
-            session.close(CloseMode.IMMEDIATE);
+    public void outputReady(final IOSession session) throws IOException {
+        if (initialized.compareAndSet(false, true)) {
+            initialize();
+        }
+        if (preface != null) {
+            writeOutPreface(session);
+        } else {
+            throw new ProtocolNegotiationException("Unexpected output");
         }
     }
 
     @Override
-    public void disconnected(final IOSession session) {
-        CommandSupport.cancelCommands(session);
-    }
-
-    @Override
-    public SSLSession getSSLSession() {
-        final TlsDetails tlsDetails = ioSession.getTlsDetails();
-        return tlsDetails != null ? tlsDetails.getSSLSession() : null;
-    }
-
-    @Override
-    public EndpointDetails getEndpointDetails() {
-        return null;
-    }
-
-    @Override
-    public void setSocketTimeout(final Timeout timeout) {
-        ioSession.setSocketTimeout(timeout);
-    }
-
-    @Override
-    public Timeout getSocketTimeout() {
-        return ioSession.getSocketTimeout();
-    }
-
-    @Override
-    public ProtocolVersion getProtocolVersion() {
-        return null;
-    }
-
-    @Override
-    public SocketAddress getRemoteAddress() {
-        return ioSession.getRemoteAddress();
-    }
-
-    @Override
-    public SocketAddress getLocalAddress() {
-        return ioSession.getLocalAddress();
-    }
-
-    @Override
-    public boolean isOpen() {
-        return ioSession.isOpen();
-    }
-
-    @Override
-    public void close() throws IOException {
-        ioSession.close();
+    public void inputReady(final IOSession session, final ByteBuffer src) throws IOException {
+        if (src != null) {
+            throw new ProtocolNegotiationException("Unexpected input");
+        }
+        if (preface != null) {
+            writeOutPreface(session);
+        } else {
+            throw new ProtocolNegotiationException("Unexpected input");
+        }
     }
 
     @Override
-    public void close(final CloseMode closeMode) {
-        ioSession.close(closeMode);
+    public String toString() {
+        return getClass().getName();
     }
 
 }
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ProtocolNegotiationException.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ProtocolNegotiationException.java
new file mode 100644
index 0000000..b984db2
--- /dev/null
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ProtocolNegotiationException.java
@@ -0,0 +1,49 @@
+/*
+ * ====================================================================
+ * 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.http2.impl.nio;
+
+import java.io.IOException;
+
+/**
+ * Signals a protocol error in HTTP protocol negotiation.
+ *
+ * @since 5.1
+ */
+public class ProtocolNegotiationException extends IOException {
+
+    /**
+     * Creates a MessageConstraintException with the specified detail message.
+     *
+     * @param message The exception detail message
+     */
+    public ProtocolNegotiationException(final String message) {
+        super(message);
+    }
+
+
+}
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/H2OnlyClientProtocolNegotiator.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ProtocolNegotiatorBase.java
similarity index 53%
copy from httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/H2OnlyClientProtocolNegotiator.java
copy to httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ProtocolNegotiatorBase.java
index c6721cb..20ef57e 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/H2OnlyClientProtocolNegotiator.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ProtocolNegotiatorBase.java
@@ -30,105 +30,50 @@ package org.apache.hc.core5.http2.impl.nio;
 import java.io.IOException;
 import java.net.SocketAddress;
 import java.nio.ByteBuffer;
-import java.nio.channels.ByteChannel;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
 
 import javax.net.ssl.SSLSession;
 
-import org.apache.hc.core5.annotation.Internal;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ConnectionClosedException;
 import org.apache.hc.core5.http.EndpointDetails;
-import org.apache.hc.core5.http.HttpException;
 import org.apache.hc.core5.http.ProtocolVersion;
 import org.apache.hc.core5.http.impl.nio.HttpConnectionEventHandler;
 import org.apache.hc.core5.http.nio.command.CommandSupport;
-import org.apache.hc.core5.http2.ssl.ApplicationProtocol;
 import org.apache.hc.core5.io.CloseMode;
 import org.apache.hc.core5.io.SocketTimeoutExceptionFactory;
-import org.apache.hc.core5.reactor.IOEventHandler;
 import org.apache.hc.core5.reactor.IOSession;
 import org.apache.hc.core5.reactor.ProtocolIOSession;
 import org.apache.hc.core5.reactor.ssl.TlsDetails;
 import org.apache.hc.core5.util.Args;
-import org.apache.hc.core5.util.TextUtils;
 import org.apache.hc.core5.util.Timeout;
 
-/**
- * I/O event handler for events fired by {@link ProtocolIOSession} that implements
- * client side of the HTTP/2 protocol negotiation handshake always forcing the choice
- * of HTTP/2.
- *
- * @since 5.0
- */
-@Internal
-public class H2OnlyClientProtocolNegotiator implements HttpConnectionEventHandler {
-
-    private final ProtocolIOSession ioSession;
-    private final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory;
-    private final boolean strictALPNHandshake;
+abstract class ProtocolNegotiatorBase implements HttpConnectionEventHandler {
 
-    private final ByteBuffer preface;
+    final ProtocolIOSession ioSession;
+    private final AtomicReference<HttpConnectionEventHandler> protocolHandlerRef;
+    private final FutureCallback<ProtocolIOSession> resultCallback;
+    private final AtomicBoolean completed;
 
-    public H2OnlyClientProtocolNegotiator(
+    ProtocolNegotiatorBase(
             final ProtocolIOSession ioSession,
-            final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory,
-            final boolean strictALPNHandshake) {
+            final FutureCallback<ProtocolIOSession> resultCallback) {
         this.ioSession = Args.notNull(ioSession, "I/O session");
-        this.http2StreamHandlerFactory = Args.notNull(http2StreamHandlerFactory, "HTTP/2 stream handler factory");
-        this.strictALPNHandshake = strictALPNHandshake;
-        this.preface = ByteBuffer.wrap(ClientHttpProtocolNegotiator.PREFACE);
+        this.protocolHandlerRef = new AtomicReference<>(null);
+        this.resultCallback = resultCallback;
+        this.completed = new AtomicBoolean();
     }
 
-    @Override
-    public void connected(final IOSession session) {
-        try {
-            final TlsDetails tlsDetails = ioSession.getTlsDetails();
-            if (tlsDetails != null) {
-                final String applicationProtocol = tlsDetails.getApplicationProtocol();
-                if (TextUtils.isEmpty(applicationProtocol)) {
-                    if (strictALPNHandshake) {
-                        throw new HttpException("ALPN: missing application protocol");
-                    }
-                } else {
-                    if (!ApplicationProtocol.HTTP_2.id.equals(applicationProtocol)) {
-                        throw new HttpException("ALPN: unexpected application protocol '" + applicationProtocol + "'");
-                    }
-                }
-            }
-            writePreface(session);
-        } catch (final Exception ex) {
-            session.close(CloseMode.IMMEDIATE);
-            exception(session, ex);
+    void startProtocol(final HttpConnectionEventHandler protocolHandler, final ByteBuffer data) throws IOException {
+        protocolHandlerRef.set(protocolHandler);
+        ioSession.upgrade(protocolHandler);
+        protocolHandler.connected(ioSession);
+        if (data != null && data.hasRemaining()) {
+            protocolHandler.inputReady(ioSession, data);
         }
-    }
-
-    private void writePreface(final IOSession session) throws IOException  {
-        if (preface.hasRemaining()) {
-            final ByteChannel channel = session;
-            channel.write(preface);
-        }
-        if (!preface.hasRemaining()) {
-            final ClientH2StreamMultiplexer streamMultiplexer = http2StreamHandlerFactory.create(ioSession);
-            final IOEventHandler newHandler = new ClientH2IOEventHandler(streamMultiplexer);
-            newHandler.connected(session);
-            ioSession.upgrade(newHandler);
-        }
-    }
-
-    @Override
-    public void inputReady(final IOSession session, final ByteBuffer src) {
-        outputReady(session);
-    }
-
-    @Override
-    public void outputReady(final IOSession session) {
-        try {
-            if (preface != null) {
-                writePreface(session);
-            } else {
-                session.close(CloseMode.GRACEFUL);
-            }
-        } catch (final IOException ex) {
-            session.close(CloseMode.IMMEDIATE);
-            exception(session, ex);
+        if (completed.compareAndSet(true, false)) {
+            resultCallback.completed(ioSession);
         }
     }
 
@@ -139,16 +84,35 @@ public class H2OnlyClientProtocolNegotiator implements HttpConnectionEventHandle
 
     @Override
     public void exception(final IOSession session, final Exception cause) {
+        final HttpConnectionEventHandler protocolHandler = protocolHandlerRef.get();
         try {
-            CommandSupport.failCommands(session, cause);
-        } finally {
             session.close(CloseMode.IMMEDIATE);
+            if (protocolHandler != null) {
+                protocolHandler.exception(session, cause);
+            } else {
+                CommandSupport.failCommands(session, cause);
+            }
+        } catch (final Exception ex) {
+            if (completed.compareAndSet(true, false)) {
+                resultCallback.failed(ex);
+            }
         }
     }
 
     @Override
     public void disconnected(final IOSession session) {
-        CommandSupport.cancelCommands(session);
+        final HttpConnectionEventHandler protocolHandler = protocolHandlerRef.getAndSet(null);
+        try {
+            if (protocolHandler != null) {
+                protocolHandler.disconnected(ioSession);
+            } else {
+                CommandSupport.cancelCommands(session);
+            }
+        } finally {
+            if (completed.compareAndSet(true, false)) {
+                resultCallback.failed(new ConnectionClosedException());
+            }
+        }
     }
 
     @Override
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerHttpProtocolNegotiator.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerHttpProtocolNegotiator.java
index 7bb65d2..7468497 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerHttpProtocolNegotiator.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerHttpProtocolNegotiator.java
@@ -28,33 +28,23 @@
 package org.apache.hc.core5.http2.impl.nio;
 
 import java.io.IOException;
-import java.net.SocketAddress;
 import java.nio.ByteBuffer;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.net.ssl.SSLSession;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.apache.hc.core5.annotation.Internal;
+import org.apache.hc.core5.concurrent.FutureCallback;
 import org.apache.hc.core5.http.ConnectionClosedException;
-import org.apache.hc.core5.http.EndpointDetails;
-import org.apache.hc.core5.http.HttpException;
-import org.apache.hc.core5.http.ProtocolVersion;
 import org.apache.hc.core5.http.URIScheme;
 import org.apache.hc.core5.http.impl.nio.BufferedData;
-import org.apache.hc.core5.http.impl.nio.HttpConnectionEventHandler;
 import org.apache.hc.core5.http.impl.nio.ServerHttp1IOEventHandler;
 import org.apache.hc.core5.http.impl.nio.ServerHttp1StreamDuplexer;
 import org.apache.hc.core5.http.impl.nio.ServerHttp1StreamDuplexerFactory;
-import org.apache.hc.core5.http.nio.command.CommandSupport;
 import org.apache.hc.core5.http2.HttpVersionPolicy;
 import org.apache.hc.core5.http2.ssl.ApplicationProtocol;
-import org.apache.hc.core5.io.CloseMode;
-import org.apache.hc.core5.io.SocketTimeoutExceptionFactory;
 import org.apache.hc.core5.reactor.IOSession;
 import org.apache.hc.core5.reactor.ProtocolIOSession;
 import org.apache.hc.core5.reactor.ssl.TlsDetails;
 import org.apache.hc.core5.util.Args;
-import org.apache.hc.core5.util.Timeout;
 
 /**
  * I/O event handler for events fired by {@link ProtocolIOSession} that implements
@@ -64,16 +54,15 @@ import org.apache.hc.core5.util.Timeout;
  * @since 5.0
  */
 @Internal
-public class ServerHttpProtocolNegotiator implements HttpConnectionEventHandler {
+public class ServerHttpProtocolNegotiator extends ProtocolNegotiatorBase {
 
     final static byte[] PREFACE = ClientHttpProtocolNegotiator.PREFACE;
 
-    private final ProtocolIOSession ioSession;
     private final ServerHttp1StreamDuplexerFactory http1StreamHandlerFactory;
     private final ServerH2StreamMultiplexerFactory http2StreamHandlerFactory;
     private final HttpVersionPolicy versionPolicy;
     private final BufferedData inBuf;
-    private final AtomicReference<HttpConnectionEventHandler> protocolHandlerRef;
+    private final AtomicBoolean initialized;
 
     private volatile boolean expectValidH2Preface;
 
@@ -82,189 +71,112 @@ public class ServerHttpProtocolNegotiator implements HttpConnectionEventHandler
             final ServerHttp1StreamDuplexerFactory http1StreamHandlerFactory,
             final ServerH2StreamMultiplexerFactory http2StreamHandlerFactory,
             final HttpVersionPolicy versionPolicy) {
-        this.ioSession = Args.notNull(ioSession, "I/O session");
+        this(ioSession, http1StreamHandlerFactory, http2StreamHandlerFactory, versionPolicy, null);
+    }
+
+    /**
+     * @since 5.1
+     */
+    public ServerHttpProtocolNegotiator(
+            final ProtocolIOSession ioSession,
+            final ServerHttp1StreamDuplexerFactory http1StreamHandlerFactory,
+            final ServerH2StreamMultiplexerFactory http2StreamHandlerFactory,
+            final HttpVersionPolicy versionPolicy,
+            final FutureCallback<ProtocolIOSession> resultCallback) {
+        super(ioSession, resultCallback);
         this.http1StreamHandlerFactory = Args.notNull(http1StreamHandlerFactory, "HTTP/1.1 stream handler factory");
         this.http2StreamHandlerFactory = Args.notNull(http2StreamHandlerFactory, "HTTP/2 stream handler factory");
         this.versionPolicy = versionPolicy != null ? versionPolicy : HttpVersionPolicy.NEGOTIATE;
         this.inBuf = BufferedData.allocate(1024);
-        this.protocolHandlerRef = new AtomicReference<>(null);
+        this.initialized = new AtomicBoolean();
     }
 
-    @Override
-    public void connected(final IOSession session) {
-        try {
-            final TlsDetails tlsDetails = ioSession.getTlsDetails();
-            switch (versionPolicy) {
-                case NEGOTIATE:
-                    if (tlsDetails != null &&
-                            ApplicationProtocol.HTTP_2.id.equals(tlsDetails.getApplicationProtocol())) {
-                        expectValidH2Preface = true;
-                    }
-                    break;
-                case FORCE_HTTP_2:
-                    if (tlsDetails == null ||
-                            !ApplicationProtocol.HTTP_1_1.id.equals(tlsDetails.getApplicationProtocol())) {
-                        expectValidH2Preface = true;
-                    }
-                    break;
-                case FORCE_HTTP_1:
-                    final ServerHttp1StreamDuplexer http1StreamHandler = http1StreamHandlerFactory.create(
-                            tlsDetails != null ? URIScheme.HTTPS.id : URIScheme.HTTP.id,
-                            ioSession);
-                    final HttpConnectionEventHandler protocolHandler = new ServerHttp1IOEventHandler(http1StreamHandler);
-                    ioSession.upgrade(protocolHandler);
-                    protocolHandlerRef.set(protocolHandler);
-                    http1StreamHandler.onConnect();
-                    break;
-            }
-        } catch (final Exception ex) {
-            exception(session, ex);
-        }
+    private void startHttp1(final TlsDetails tlsDetails, final ByteBuffer data) throws IOException {
+        final ServerHttp1StreamDuplexer http1StreamHandler = http1StreamHandlerFactory.create(
+                tlsDetails != null ? URIScheme.HTTPS.id : URIScheme.HTTP.id,
+                ioSession);
+        startProtocol(new ServerHttp1IOEventHandler(http1StreamHandler), data);
     }
 
-    @Override
-    public void inputReady(final IOSession session, final ByteBuffer src) {
-        try {
-            if (src != null) {
-                inBuf.put(src);
-            }
-            boolean endOfStream = false;
-            if (inBuf.length() < PREFACE.length) {
-                final int bytesRead = inBuf.readFrom(session);
-                if (bytesRead == -1) {
-                    endOfStream = true;
-                }
-            }
-            final ByteBuffer data = inBuf.data();
-            if (data.remaining() >= PREFACE.length) {
-                boolean validH2Preface = true;
-                for (int i = 0; i < PREFACE.length; i++) {
-                    if (data.get() != PREFACE[i]) {
-                        if (expectValidH2Preface) {
-                            throw new HttpException("Unexpected HTTP/2 preface");
-                        }
-                        validH2Preface = false;
-                    }
-                }
-                if (validH2Preface) {
-                    final ServerH2StreamMultiplexer http2StreamHandler = http2StreamHandlerFactory.create(ioSession);
-                    final HttpConnectionEventHandler protocolHandler = new ServerH2IOEventHandler(http2StreamHandler);
-                    ioSession.upgrade(protocolHandler);
-                    protocolHandlerRef.set(protocolHandler);
-                    http2StreamHandler.onConnect();
-                    http2StreamHandler.onInput(data.hasRemaining() ? data : null);
-                } else {
-                    final TlsDetails tlsDetails = ioSession.getTlsDetails();
-                    final ServerHttp1StreamDuplexer http1StreamHandler = http1StreamHandlerFactory.create(
-                            tlsDetails != null ? URIScheme.HTTPS.id : URIScheme.HTTP.id,
-                            ioSession);
-                    final HttpConnectionEventHandler protocolHandler = new ServerHttp1IOEventHandler(http1StreamHandler);
-                    ioSession.upgrade(protocolHandler);
-                    protocolHandlerRef.set(protocolHandler);
-                    data.rewind();
-                    http1StreamHandler.onConnect();
-                    http1StreamHandler.onInput(data);
+    private void startHttp2(final ByteBuffer data) throws IOException {
+        startProtocol(new ServerH2IOEventHandler(http2StreamHandlerFactory.create(ioSession)), data);
+    }
+
+    private void initialize() throws IOException {
+        final TlsDetails tlsDetails = ioSession.getTlsDetails();
+        switch (versionPolicy) {
+            case NEGOTIATE:
+                if (tlsDetails != null &&
+                        ApplicationProtocol.HTTP_2.id.equals(tlsDetails.getApplicationProtocol())) {
+                    expectValidH2Preface = true;
                 }
-            } else {
-                if (endOfStream) {
-                    throw new ConnectionClosedException();
+                break;
+            case FORCE_HTTP_2:
+                if (tlsDetails == null ||
+                        !ApplicationProtocol.HTTP_1_1.id.equals(tlsDetails.getApplicationProtocol())) {
+                    expectValidH2Preface = true;
                 }
-            }
-            data.clear();
-        } catch (final Exception ex) {
-            exception(session, ex);
+                break;
+            case FORCE_HTTP_1:
+                startHttp1(tlsDetails, null);
+                break;
         }
     }
 
     @Override
-    public void outputReady(final IOSession session) {
-    }
-
-    @Override
-    public void timeout(final IOSession session, final Timeout timeout) {
-        exception(session, SocketTimeoutExceptionFactory.create(timeout));
-    }
-
-    @Override
-    public void exception(final IOSession session, final Exception cause) {
-        session.close(CloseMode.IMMEDIATE);
-        final HttpConnectionEventHandler protocolHandler = protocolHandlerRef.get();
-        if (protocolHandler != null) {
-            protocolHandler.exception(session, cause);
-        } else {
-            CommandSupport.failCommands(session, cause);
+    public void connected(final IOSession session) throws IOException {
+        if (initialized.compareAndSet(false, true)) {
+            initialize();
         }
     }
 
     @Override
-    public void disconnected(final IOSession session) {
-        final HttpConnectionEventHandler protocolHandler = protocolHandlerRef.getAndSet(null);
-        if (protocolHandler != null) {
-            protocolHandler.disconnected(ioSession);
+    public void inputReady(final IOSession session, final ByteBuffer src) throws IOException {
+        if (src != null) {
+            inBuf.put(src);
+        }
+        boolean endOfStream = false;
+        if (inBuf.length() < PREFACE.length) {
+            final int bytesRead = inBuf.readFrom(session);
+            if (bytesRead == -1) {
+                endOfStream = true;
+            }
+        }
+        final ByteBuffer data = inBuf.data();
+        if (data.remaining() >= PREFACE.length) {
+            boolean validH2Preface = true;
+            for (int i = 0; i < PREFACE.length; i++) {
+                if (data.get() != PREFACE[i]) {
+                    if (expectValidH2Preface) {
+                        throw new ProtocolNegotiationException("Unexpected HTTP/2 preface");
+                    }
+                    validH2Preface = false;
+                }
+            }
+            if (validH2Preface) {
+                startHttp2(data.hasRemaining() ? data : null);
+            } else {
+                data.rewind();
+                startHttp1(ioSession.getTlsDetails(), data);
+            }
         } else {
-            CommandSupport.cancelCommands(session);
+            if (endOfStream) {
+                throw new ConnectionClosedException();
+            }
         }
+        data.clear();
     }
 
     @Override
-    public SSLSession getSSLSession() {
-        final TlsDetails tlsDetails = ioSession.getTlsDetails();
-        return tlsDetails != null ? tlsDetails.getSSLSession() : null;
-    }
-
-    @Override
-    public EndpointDetails getEndpointDetails() {
-        final HttpConnectionEventHandler protocolHandler = protocolHandlerRef.get();
-        return protocolHandler != null ? protocolHandler.getEndpointDetails() : null;
-    }
-
-    @Override
-    public void setSocketTimeout(final Timeout timeout) {
-        ioSession.setSocketTimeout(timeout);
-    }
-
-    @Override
-    public Timeout getSocketTimeout() {
-        return ioSession.getSocketTimeout();
-    }
-
-    @Override
-    public ProtocolVersion getProtocolVersion() {
-        final HttpConnectionEventHandler protocolHandler = protocolHandlerRef.get();
-        return protocolHandler != null ? protocolHandler.getProtocolVersion() : null;
-    }
-
-    @Override
-    public SocketAddress getRemoteAddress() {
-        return ioSession.getRemoteAddress();
-    }
-
-    @Override
-    public SocketAddress getLocalAddress() {
-        return ioSession.getLocalAddress();
-    }
-
-    @Override
-    public boolean isOpen() {
-        return ioSession.isOpen();
-    }
-
-    @Override
-    public void close() throws IOException {
-        ioSession.close();
-    }
-
-    @Override
-    public void close(final CloseMode closeMode) {
-        ioSession.close(closeMode);
+    public void outputReady(final IOSession session) throws IOException {
+        if (initialized.compareAndSet(false, true)) {
+            initialize();
+        }
     }
 
     @Override
     public String toString() {
-        return "[" +
-                "versionPolicy=" + versionPolicy +
-                ", expectValidH2Preface=" + expectValidH2Preface +
-                ']';
+        return getClass().getName() + "/" + versionPolicy;
     }
 
 }