View Javadoc
1   /*
2    * Copyright 2017 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.ssl;
17  
18  import io.netty.util.internal.PlatformDependent;
19  
20  import javax.net.ssl.SSLEngine;
21  import java.lang.reflect.Method;
22  
23  /**
24   * Contains methods that can be used to detect if conscrypt is usable.
25   */
26  final class Conscrypt {
27      // This class exists to avoid loading other conscrypt related classes using features only available in JDK8+,
28      // because we need to maintain JDK6+ runtime compatibility.
29      private static final Class<?> ENGINES_CLASS = getEnginesClass();
30  
31      /**
32       * Indicates whether or not conscrypt is available on the current system.
33       */
34      static boolean isAvailable() {
35          return ENGINES_CLASS != null && PlatformDependent.javaVersion() >= 8;
36      }
37  
38      static boolean isEngineSupported(SSLEngine engine) {
39          return isAvailable() && isConscryptEngine(engine, ENGINES_CLASS);
40      }
41  
42      private static Class<?> getEnginesClass() {
43          try {
44              // Always use bootstrap class loader.
45              Class<?> engineClass = Class.forName("org.conscrypt.Conscrypt$Engines", true,
46                      ConscryptAlpnSslEngine.class.getClassLoader());
47              // Ensure that it also has the isConscrypt method.
48              getIsConscryptMethod(engineClass);
49              return engineClass;
50          } catch (Throwable ignore) {
51              // Conscrypt was not loaded.
52              return null;
53          }
54      }
55  
56      private static boolean isConscryptEngine(SSLEngine engine, Class<?> enginesClass) {
57          try {
58              Method method = getIsConscryptMethod(enginesClass);
59              return (Boolean) method.invoke(null, engine);
60          } catch (Throwable ignore) {
61              return false;
62          }
63      }
64  
65      private static Method getIsConscryptMethod(Class<?> enginesClass) throws NoSuchMethodException {
66          return enginesClass.getMethod("isConscrypt", SSLEngine.class);
67      }
68  
69      private Conscrypt() { }
70  }