From d0325cfed137fe5ea400d7344c38f0deac43959a Mon Sep 17 00:00:00 2001
From: Mat Booth <mat.booth@redhat.com>
Date: Mon, 7 Sep 2020 13:24:30 +0100
Subject: [PATCH 2/7] Remove optional dep conscrypt

---
 handler/pom.xml                               |   6 -
 .../java/io/netty/handler/ssl/Conscrypt.java  |  75 -------
 .../handler/ssl/ConscryptAlpnSslEngine.java   | 212 ------------------
 .../JdkAlpnApplicationProtocolNegotiator.java |  11 +-
 .../java/io/netty/handler/ssl/SslHandler.java |  52 +----
 pom.xml                                       |  10 -
 6 files changed, 2 insertions(+), 364 deletions(-)
 delete mode 100644 handler/src/main/java/io/netty/handler/ssl/Conscrypt.java
 delete mode 100644 handler/src/main/java/io/netty/handler/ssl/ConscryptAlpnSslEngine.java

diff --git a/handler/pom.xml b/handler/pom.xml
index 8e21f87533..46c20028eb 100644
--- a/handler/pom.xml
+++ b/handler/pom.xml
@@ -96,12 +96,6 @@
       <artifactId>alpn-api</artifactId>
       <optional>true</optional>
     </dependency>
-    <dependency>
-      <groupId>${conscrypt.groupId}</groupId>
-      <artifactId>${conscrypt.artifactId}</artifactId>
-      <classifier>${conscrypt.classifier}</classifier>
-      <optional>true</optional>
-    </dependency>
     <dependency>
       <groupId>org.mockito</groupId>
       <artifactId>mockito-core</artifactId>
diff --git a/handler/src/main/java/io/netty/handler/ssl/Conscrypt.java b/handler/src/main/java/io/netty/handler/ssl/Conscrypt.java
deleted file mode 100644
index c5af3fd39a..0000000000
--- a/handler/src/main/java/io/netty/handler/ssl/Conscrypt.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright 2017 The Netty Project
- *
- * The Netty Project 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:
- *
- *   https://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.
- */
-package io.netty.handler.ssl;
-
-import io.netty.util.internal.PlatformDependent;
-
-import javax.net.ssl.SSLEngine;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-/**
- * Contains methods that can be used to detect if conscrypt is usable.
- */
-final class Conscrypt {
-    // This class exists to avoid loading other conscrypt related classes using features only available in JDK8+,
-    // because we need to maintain JDK6+ runtime compatibility.
-    private static final Method IS_CONSCRYPT_SSLENGINE;
-
-    static {
-        Method isConscryptSSLEngine = null;
-
-        if ((PlatformDependent.javaVersion() >= 8 &&
-                // Only works on Java14 and earlier for now
-                // See https://github.com/google/conscrypt/issues/838
-                PlatformDependent.javaVersion() < 15) || PlatformDependent.isAndroid()) {
-            try {
-                Class<?> providerClass = Class.forName("org.conscrypt.OpenSSLProvider", true,
-                        PlatformDependent.getClassLoader(ConscryptAlpnSslEngine.class));
-                providerClass.newInstance();
-
-                Class<?> conscryptClass = Class.forName("org.conscrypt.Conscrypt", true,
-                        PlatformDependent.getClassLoader(ConscryptAlpnSslEngine.class));
-                isConscryptSSLEngine = conscryptClass.getMethod("isConscrypt", SSLEngine.class);
-            } catch (Throwable ignore) {
-                // ignore
-            }
-        }
-        IS_CONSCRYPT_SSLENGINE = isConscryptSSLEngine;
-    }
-
-    /**
-     * Indicates whether or not conscrypt is available on the current system.
-     */
-    static boolean isAvailable() {
-        return IS_CONSCRYPT_SSLENGINE != null;
-    }
-
-    /**
-     * Returns {@code true} if the passed in {@link SSLEngine} is handled by Conscrypt, {@code false} otherwise.
-     */
-    static boolean isEngineSupported(SSLEngine engine) {
-        try {
-            return IS_CONSCRYPT_SSLENGINE != null && (Boolean) IS_CONSCRYPT_SSLENGINE.invoke(null, engine);
-        } catch (IllegalAccessException ignore) {
-            return false;
-        } catch (InvocationTargetException ex) {
-            throw new RuntimeException(ex);
-        }
-    }
-
-    private Conscrypt() { }
-}
diff --git a/handler/src/main/java/io/netty/handler/ssl/ConscryptAlpnSslEngine.java b/handler/src/main/java/io/netty/handler/ssl/ConscryptAlpnSslEngine.java
deleted file mode 100644
index 917ebaea79..0000000000
--- a/handler/src/main/java/io/netty/handler/ssl/ConscryptAlpnSslEngine.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Copyright 2017 The Netty Project
- *
- * The Netty Project 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:
- *
- *   https://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.
- */
-package io.netty.handler.ssl;
-
-import static io.netty.handler.ssl.SslUtils.toSSLHandshakeException;
-import static io.netty.util.internal.ObjectUtil.checkNotNull;
-import static java.lang.Math.min;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.ByteBufAllocator;
-import io.netty.handler.ssl.JdkApplicationProtocolNegotiator.ProtocolSelectionListener;
-import io.netty.handler.ssl.JdkApplicationProtocolNegotiator.ProtocolSelector;
-import java.nio.ByteBuffer;
-import java.util.Collections;
-import java.util.LinkedHashSet;
-import java.util.List;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLException;
-
-import io.netty.util.internal.EmptyArrays;
-import io.netty.util.internal.SystemPropertyUtil;
-import org.conscrypt.AllocatedBuffer;
-import org.conscrypt.BufferAllocator;
-import org.conscrypt.Conscrypt;
-import org.conscrypt.HandshakeListener;
-
-/**
- * A {@link JdkSslEngine} that uses the Conscrypt provider or SSL with ALPN.
- */
-abstract class ConscryptAlpnSslEngine extends JdkSslEngine {
-    private static final boolean USE_BUFFER_ALLOCATOR = SystemPropertyUtil.getBoolean(
-            "io.netty.handler.ssl.conscrypt.useBufferAllocator", true);
-
-    static ConscryptAlpnSslEngine newClientEngine(SSLEngine engine, ByteBufAllocator alloc,
-            JdkApplicationProtocolNegotiator applicationNegotiator) {
-        return new ClientEngine(engine, alloc, applicationNegotiator);
-    }
-
-    static ConscryptAlpnSslEngine newServerEngine(SSLEngine engine, ByteBufAllocator alloc,
-            JdkApplicationProtocolNegotiator applicationNegotiator) {
-        return new ServerEngine(engine, alloc, applicationNegotiator);
-    }
-
-    private ConscryptAlpnSslEngine(SSLEngine engine, ByteBufAllocator alloc, List<String> protocols) {
-        super(engine);
-
-        // Configure the Conscrypt engine to use Netty's buffer allocator. This is a trade-off of memory vs
-        // performance.
-        //
-        // If no allocator is provided, the engine will internally allocate a direct buffer of max packet size in
-        // order to optimize JNI calls (this happens the first time it is provided a non-direct buffer from the
-        // application).
-        //
-        // Alternatively, if an allocator is provided, no internal buffer will be created and direct buffers will be
-        // retrieved from the allocator on-demand.
-        if (USE_BUFFER_ALLOCATOR) {
-            Conscrypt.setBufferAllocator(engine, new BufferAllocatorAdapter(alloc));
-        }
-
-        // Set the list of supported ALPN protocols on the engine.
-        Conscrypt.setApplicationProtocols(engine, protocols.toArray(EmptyArrays.EMPTY_STRINGS));
-    }
-
-    /**
-     * Calculates the maximum size of the encrypted output buffer required to wrap the given plaintext bytes. Assumes
-     * as a worst case that there is one TLS record per buffer.
-     *
-     * @param plaintextBytes the number of plaintext bytes to be wrapped.
-     * @param numBuffers the number of buffers that the plaintext bytes are spread across.
-     * @return the maximum size of the encrypted output buffer required for the wrap operation.
-     */
-    final int calculateOutNetBufSize(int plaintextBytes, int numBuffers) {
-        // Assuming a max of one frame per component in a composite buffer.
-        return calculateSpace(plaintextBytes, numBuffers, Integer.MAX_VALUE);
-    }
-
-    /**
-     * Calculate the space necessary in an out buffer to hold the max size that the given
-     * plaintextBytes and numBuffers can produce when encrypted. Assumes as a worst case
-     * that there is one TLS record per buffer.
-     * @param plaintextBytes the number of plaintext bytes to be wrapped.
-     * @param numBuffers the number of buffers that the plaintext bytes are spread across.
-     * @return the maximum size of the encrypted output buffer required for the wrap operation.
-     */
-    final int calculateRequiredOutBufSpace(int plaintextBytes, int numBuffers) {
-        return calculateSpace(plaintextBytes, numBuffers, Conscrypt.maxEncryptedPacketLength());
-    }
-
-    private int calculateSpace(int plaintextBytes, int numBuffers, long maxPacketLength) {
-         long maxOverhead = (long) Conscrypt.maxSealOverhead(getWrappedEngine()) * numBuffers;
-         return (int) min(maxPacketLength, plaintextBytes + maxOverhead);
-    }
-
-    final SSLEngineResult unwrap(ByteBuffer[] srcs, ByteBuffer[] dests) throws SSLException {
-        return Conscrypt.unwrap(getWrappedEngine(), srcs, dests);
-    }
-
-    private static final class ClientEngine extends ConscryptAlpnSslEngine {
-        private final ProtocolSelectionListener protocolListener;
-
-        ClientEngine(SSLEngine engine, ByteBufAllocator alloc,
-                JdkApplicationProtocolNegotiator applicationNegotiator) {
-            super(engine, alloc, applicationNegotiator.protocols());
-            // Register for completion of the handshake.
-            Conscrypt.setHandshakeListener(engine, new HandshakeListener() {
-                @Override
-                public void onHandshakeFinished() throws SSLException {
-                    selectProtocol();
-                }
-            });
-
-            protocolListener = checkNotNull(applicationNegotiator
-                            .protocolListenerFactory().newListener(this, applicationNegotiator.protocols()),
-                    "protocolListener");
-        }
-
-        private void selectProtocol() throws SSLException {
-            String protocol = Conscrypt.getApplicationProtocol(getWrappedEngine());
-            try {
-                protocolListener.selected(protocol);
-            } catch (Throwable e) {
-                throw toSSLHandshakeException(e);
-            }
-        }
-    }
-
-    private static final class ServerEngine extends ConscryptAlpnSslEngine {
-        private final ProtocolSelector protocolSelector;
-
-        ServerEngine(SSLEngine engine, ByteBufAllocator alloc,
-                     JdkApplicationProtocolNegotiator applicationNegotiator) {
-            super(engine, alloc, applicationNegotiator.protocols());
-
-            // Register for completion of the handshake.
-            Conscrypt.setHandshakeListener(engine, new HandshakeListener() {
-                @Override
-                public void onHandshakeFinished() throws SSLException {
-                    selectProtocol();
-                }
-            });
-
-            protocolSelector = checkNotNull(applicationNegotiator.protocolSelectorFactory()
-                            .newSelector(this,
-                                    new LinkedHashSet<String>(applicationNegotiator.protocols())),
-                    "protocolSelector");
-        }
-
-        private void selectProtocol() throws SSLException {
-            try {
-                String protocol = Conscrypt.getApplicationProtocol(getWrappedEngine());
-                protocolSelector.select(protocol != null ? Collections.singletonList(protocol)
-                        : Collections.<String>emptyList());
-            } catch (Throwable e) {
-                throw toSSLHandshakeException(e);
-            }
-        }
-    }
-
-    private static final class BufferAllocatorAdapter extends BufferAllocator {
-        private final ByteBufAllocator alloc;
-
-        BufferAllocatorAdapter(ByteBufAllocator alloc) {
-            this.alloc = alloc;
-        }
-
-        @Override
-        public AllocatedBuffer allocateDirectBuffer(int capacity) {
-            return new BufferAdapter(alloc.directBuffer(capacity));
-        }
-    }
-
-    private static final class BufferAdapter extends AllocatedBuffer {
-        private final ByteBuf nettyBuffer;
-        private final ByteBuffer buffer;
-
-        BufferAdapter(ByteBuf nettyBuffer) {
-            this.nettyBuffer = nettyBuffer;
-            buffer = nettyBuffer.nioBuffer(0, nettyBuffer.capacity());
-        }
-
-        @Override
-        public ByteBuffer nioBuffer() {
-            return buffer;
-        }
-
-        @Override
-        public AllocatedBuffer retain() {
-            nettyBuffer.retain();
-            return this;
-        }
-
-        @Override
-        public AllocatedBuffer release() {
-            nettyBuffer.release();
-            return this;
-        }
-    }
-}
diff --git a/handler/src/main/java/io/netty/handler/ssl/JdkAlpnApplicationProtocolNegotiator.java b/handler/src/main/java/io/netty/handler/ssl/JdkAlpnApplicationProtocolNegotiator.java
index 9eb8f15d14..b5715e87ff 100644
--- a/handler/src/main/java/io/netty/handler/ssl/JdkAlpnApplicationProtocolNegotiator.java
+++ b/handler/src/main/java/io/netty/handler/ssl/JdkAlpnApplicationProtocolNegotiator.java
@@ -26,8 +26,7 @@ import javax.net.ssl.SSLEngine;
  */
 @Deprecated
 public final class JdkAlpnApplicationProtocolNegotiator extends JdkBaseApplicationProtocolNegotiator {
-    private static final boolean AVAILABLE = Conscrypt.isAvailable() ||
-                                             JdkAlpnSslUtils.supportsAlpn() ||
+    private static final boolean AVAILABLE = JdkAlpnSslUtils.supportsAlpn() ||
                                              JettyAlpnSslEngine.isAvailable() ||
                                              BouncyCastle.isAvailable();
 
@@ -120,7 +119,6 @@ public final class JdkAlpnApplicationProtocolNegotiator extends JdkBaseApplicati
         public SSLEngine wrapSslEngine(SSLEngine engine, ByteBufAllocator alloc,
                                        JdkApplicationProtocolNegotiator applicationNegotiator, boolean isServer) {
             throw new RuntimeException("ALPN unsupported. Is your classpath configured correctly?"
-                    + " For Conscrypt, add the appropriate Conscrypt JAR to classpath and set the security provider."
                     + " For Jetty-ALPN, see "
                     + "https://www.eclipse.org/jetty/documentation/current/alpn-chapter.html#alpn-starting");
         }
@@ -130,13 +128,6 @@ public final class JdkAlpnApplicationProtocolNegotiator extends JdkBaseApplicati
         @Override
         public SSLEngine wrapSslEngine(SSLEngine engine, ByteBufAllocator alloc,
                                        JdkApplicationProtocolNegotiator applicationNegotiator, boolean isServer) {
-            if (Conscrypt.isEngineSupported(engine)) {
-                return isServer ? ConscryptAlpnSslEngine.newServerEngine(engine, alloc, applicationNegotiator)
-                        : ConscryptAlpnSslEngine.newClientEngine(engine, alloc, applicationNegotiator);
-            }
-            if (BouncyCastle.isInUse(engine)) {
-                return new BouncyCastleAlpnSslEngine(engine, applicationNegotiator, isServer);
-            }
             // ALPN support was recently backported to Java8 as
             // https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8230977.
             // Because of this lets not do a Java version runtime check but just depend on if the required methods are
diff --git a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java
index 019bb38f90..40a46d21b7 100644
--- a/handler/src/main/java/io/netty/handler/ssl/SslHandler.java
+++ b/handler/src/main/java/io/netty/handler/ssl/SslHandler.java
@@ -251,55 +251,6 @@ public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundH
                 return ((ReferenceCountedOpenSslEngine) engine).jdkCompatibilityMode;
             }
         },
-        CONSCRYPT(true, COMPOSITE_CUMULATOR) {
-            @Override
-            SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int len, ByteBuf out) throws SSLException {
-                int nioBufferCount = in.nioBufferCount();
-                int writerIndex = out.writerIndex();
-                final SSLEngineResult result;
-                if (nioBufferCount > 1) {
-                    /*
-                     * Use a special unwrap method without additional memory copies.
-                     */
-                    try {
-                        handler.singleBuffer[0] = toByteBuffer(out, writerIndex, out.writableBytes());
-                        result = ((ConscryptAlpnSslEngine) handler.engine).unwrap(
-                                in.nioBuffers(in.readerIndex(), len),
-                                handler.singleBuffer);
-                    } finally {
-                        handler.singleBuffer[0] = null;
-                    }
-                } else {
-                    result = handler.engine.unwrap(toByteBuffer(in, in.readerIndex(), len),
-                            toByteBuffer(out, writerIndex, out.writableBytes()));
-                }
-                out.writerIndex(writerIndex + result.bytesProduced());
-                return result;
-            }
-
-            @Override
-            ByteBuf allocateWrapBuffer(SslHandler handler, ByteBufAllocator allocator,
-                                       int pendingBytes, int numComponents) {
-                return allocator.directBuffer(
-                        ((ConscryptAlpnSslEngine) handler.engine).calculateOutNetBufSize(pendingBytes, numComponents));
-            }
-
-            @Override
-            int calculateRequiredOutBufSpace(SslHandler handler, int pendingBytes, int numComponents) {
-                return ((ConscryptAlpnSslEngine) handler.engine)
-                        .calculateRequiredOutBufSpace(pendingBytes, numComponents);
-            }
-
-            @Override
-            int calculatePendingData(SslHandler handler, int guess) {
-                return guess;
-            }
-
-            @Override
-            boolean jdkCompatibilityMode(SSLEngine engine) {
-                return true;
-            }
-        },
         JDK(false, MERGE_CUMULATOR) {
             @Override
             SSLEngineResult unwrap(SslHandler handler, ByteBuf in, int len, ByteBuf out) throws SSLException {
@@ -358,8 +309,7 @@ public class SslHandler extends ByteToMessageDecoder implements ChannelOutboundH
         };
 
         static SslEngineType forEngine(SSLEngine engine) {
-            return engine instanceof ReferenceCountedOpenSslEngine ? TCNATIVE :
-                   engine instanceof ConscryptAlpnSslEngine ? CONSCRYPT : JDK;
+            return engine instanceof ReferenceCountedOpenSslEngine ? TCNATIVE : JDK;
         }
 
         SslEngineType(boolean wantsDirectBuffer, Cumulator cumulator) {
diff --git a/pom.xml b/pom.xml
index bf36e0b533..ae68f4ebe8 100644
--- a/pom.xml
+++ b/pom.xml
@@ -858,16 +858,6 @@
         <optional>true</optional>
       </dependency>
 
-      <!-- Conscrypt - needed for running tests, used for accelerating SSL with OpenSSL. -->
-      <dependency>
-        <groupId>${conscrypt.groupId}</groupId>
-        <artifactId>${conscrypt.artifactId}</artifactId>
-        <classifier>${conscrypt.classifier}</classifier>
-        <version>${conscrypt.version}</version>
-        <scope>compile</scope>
-        <optional>true</optional>
-      </dependency>
-
       <!--
         Bouncy Castle - completely optional, only needed when:
         - you generate a temporary self-signed certificate using SelfSignedCertificate, and
-- 
2.46.1

