package io.netty.handler.ssl;

import io.netty.buffer.ByteBuf;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.util.internal.NativeLibraryLoader;
import io.netty.util.internal.SystemPropertyUtil;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Set;
import org.apache.tomcat.jni.Buffer;
import org.apache.tomcat.jni.Library;
import org.apache.tomcat.jni.Pool;
import org.apache.tomcat.jni.SSL;
import org.apache.tomcat.jni.SSLContext;

/* JADX INFO: loaded from: classes.dex */
public final class OpenSsl {
    static final /* synthetic */ boolean $assertionsDisabled = false;
    static final Set<String> AVAILABLE_CIPHER_SUITES;
    private static final Set<String> AVAILABLE_JAVA_CIPHER_SUITES;
    private static final Set<String> AVAILABLE_OPENSSL_CIPHER_SUITES;
    private static final String LINUX = "linux";
    static final String PROTOCOL_SSL_V2 = "SSLv2";
    static final String PROTOCOL_SSL_V2_HELLO = "SSLv2Hello";
    static final String PROTOCOL_SSL_V3 = "SSLv3";
    static final String PROTOCOL_TLS_V1 = "TLSv1";
    static final String PROTOCOL_TLS_V1_1 = "TLSv1.1";
    static final String PROTOCOL_TLS_V1_2 = "TLSv1.2";
    private static final String[] SUPPORTED_PROTOCOLS;
    static final Set<String> SUPPORTED_PROTOCOLS_SET;
    private static final boolean SUPPORTS_KEYMANAGER_FACTORY;
    private static final Throwable UNAVAILABILITY_CAUSE;
    private static final String UNKNOWN = "unknown";
    private static final InternalLogger logger = InternalLoggerFactory.getInstance((Class<?>) OpenSsl.class);

    static {
        long jMake;
        long bio;
        String[] strArr = {PROTOCOL_SSL_V2_HELLO, PROTOCOL_SSL_V2, PROTOCOL_SSL_V3, PROTOCOL_TLS_V1, PROTOCOL_TLS_V1_1, PROTOCOL_TLS_V1_2};
        SUPPORTED_PROTOCOLS = strArr;
        SUPPORTED_PROTOCOLS_SET = Collections.unmodifiableSet(new HashSet(Arrays.asList(strArr)));
        ClassNotFoundException classNotFoundException = null;
        boolean z = false;
        try {
            Class.forName("org.apache.tomcat.jni.SSL", false, OpenSsl.class.getClassLoader());
            th = null;
        } catch (ClassNotFoundException e2) {
            th = e2;
            logger.debug("netty-tcnative not in the classpath; " + OpenSslEngine.class.getSimpleName() + " will be unavailable.");
        }
        if (th == null) {
            try {
                loadTcNative();
            } catch (Throwable th) {
                th = th;
                logger.debug("Failed to load netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable, unless the application has already loaded the symbols by some other means. See http://netty.io/wiki/forked-tomcat-native.html for more information.", (Throwable) th);
            }
            try {
                initializeTcNative();
            } catch (Throwable th2) {
                if (th == null) {
                    th = th2;
                }
                logger.debug("Failed to initialize netty-tcnative; " + OpenSslEngine.class.getSimpleName() + " will be unavailable. See http://netty.io/wiki/forked-tomcat-native.html for more information.", (Throwable) th2);
                classNotFoundException = th;
            }
        } else {
            classNotFoundException = th;
        }
        UNAVAILABILITY_CAUSE = classNotFoundException;
        if (classNotFoundException != null) {
            AVAILABLE_OPENSSL_CIPHER_SUITES = Collections.emptySet();
            AVAILABLE_JAVA_CIPHER_SUITES = Collections.emptySet();
            AVAILABLE_CIPHER_SUITES = Collections.emptySet();
            SUPPORTS_KEYMANAGER_FACTORY = false;
            return;
        }
        LinkedHashSet linkedHashSet = new LinkedHashSet(128);
        long jCreate = Pool.create(0L);
        try {
            try {
                jMake = SSLContext.make(jCreate, 31, 1);
            } catch (Exception e3) {
                logger.warn("Failed to get the list of available OpenSSL cipher suites.", (Throwable) e3);
            }
            try {
                SSLContext.setOptions(jMake, 4095);
                SSLContext.setCipherSuite(jMake, "ALL");
                long jNewSSL = SSL.newSSL(jMake, true);
                try {
                    for (String str : SSL.getCiphers(jNewSSL)) {
                        if (str != null && str.length() != 0 && !linkedHashSet.contains(str)) {
                            linkedHashSet.add(str);
                        }
                    }
                    try {
                        bio = OpenSslContext.toBIO(new SelfSignedCertificate().cert());
                    } catch (Throwable unused) {
                        bio = 0;
                    }
                    try {
                        SSL.setCertificateChainBio(jNewSSL, bio, false);
                        z = true;
                    } catch (Throwable unused2) {
                        try {
                            logger.debug("KeyManagerFactory not supported.");
                        } catch (Throwable th3) {
                            th = th3;
                            SSL.freeSSL(jNewSSL);
                            if (bio != 0) {
                                SSL.freeBIO(bio);
                            }
                            throw th;
                        }
                    }
                    SSL.freeSSL(jNewSSL);
                    if (bio != 0) {
                        SSL.freeBIO(bio);
                    }
                    Pool.destroy(jCreate);
                    Set<String> setUnmodifiableSet = Collections.unmodifiableSet(linkedHashSet);
                    AVAILABLE_OPENSSL_CIPHER_SUITES = setUnmodifiableSet;
                    LinkedHashSet linkedHashSet2 = new LinkedHashSet(setUnmodifiableSet.size() * 2);
                    for (String str2 : setUnmodifiableSet) {
                        linkedHashSet2.add(CipherSuiteConverter.toJava(str2, "TLS"));
                        linkedHashSet2.add(CipherSuiteConverter.toJava(str2, "SSL"));
                    }
                    Set<String> setUnmodifiableSet2 = Collections.unmodifiableSet(linkedHashSet2);
                    AVAILABLE_JAVA_CIPHER_SUITES = setUnmodifiableSet2;
                    Set<String> set = AVAILABLE_OPENSSL_CIPHER_SUITES;
                    LinkedHashSet linkedHashSet3 = new LinkedHashSet(set.size() + setUnmodifiableSet2.size());
                    Iterator<String> it = set.iterator();
                    while (it.hasNext()) {
                        linkedHashSet3.add(it.next());
                    }
                    Iterator<String> it2 = AVAILABLE_JAVA_CIPHER_SUITES.iterator();
                    while (it2.hasNext()) {
                        linkedHashSet3.add(it2.next());
                    }
                    AVAILABLE_CIPHER_SUITES = linkedHashSet3;
                    SUPPORTS_KEYMANAGER_FACTORY = z;
                } catch (Throwable th4) {
                    th = th4;
                    bio = 0;
                }
            } finally {
                SSLContext.free(jMake);
            }
        } catch (Throwable th5) {
            Pool.destroy(jCreate);
            throw th5;
        }
    }

    private OpenSsl() {
    }

    @Deprecated
    public static Set<String> availableCipherSuites() {
        return availableOpenSslCipherSuites();
    }

    public static Set<String> availableJavaCipherSuites() {
        return AVAILABLE_JAVA_CIPHER_SUITES;
    }

    public static Set<String> availableOpenSslCipherSuites() {
        return AVAILABLE_OPENSSL_CIPHER_SUITES;
    }

    public static void ensureAvailability() {
        Throwable th = UNAVAILABILITY_CAUSE;
        if (th != null) {
            throw ((Error) new UnsatisfiedLinkError("failed to load the required native library").initCause(th));
        }
    }

    private static void initializeTcNative() throws Exception {
        Library.initialize("provided");
        SSL.initialize((String) null);
    }

    public static boolean isAlpnSupported() {
        return ((long) version()) >= 268443648;
    }

    public static boolean isAvailable() {
        return UNAVAILABILITY_CAUSE == null;
    }

    public static boolean isCipherSuiteAvailable(String str) {
        String openSsl = CipherSuiteConverter.toOpenSsl(str);
        if (openSsl != null) {
            str = openSsl;
        }
        return AVAILABLE_OPENSSL_CIPHER_SUITES.contains(str);
    }

    static boolean isError(long j) {
        return j != 0;
    }

    private static void loadTcNative() throws Exception {
        String strNormalizeOs = normalizeOs(SystemPropertyUtil.get("os.name", ""));
        String strNormalizeArch = normalizeArch(SystemPropertyUtil.get("os.arch", ""));
        LinkedHashSet linkedHashSet = new LinkedHashSet(3);
        linkedHashSet.add("netty-tcnative-" + strNormalizeOs + '-' + strNormalizeArch);
        if (LINUX.equalsIgnoreCase(strNormalizeOs)) {
            linkedHashSet.add("netty-tcnative-" + strNormalizeOs + '-' + strNormalizeArch + "-fedora");
        }
        linkedHashSet.add("netty-tcnative");
        NativeLibraryLoader.loadFirstAvailable(SSL.class.getClassLoader(), (String[]) linkedHashSet.toArray(new String[linkedHashSet.size()]));
    }

    static long memoryAddress(ByteBuf byteBuf) {
        return byteBuf.hasMemoryAddress() ? byteBuf.memoryAddress() : Buffer.address(byteBuf.nioBuffer());
    }

    private static String normalize(String str) {
        return str.toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", "");
    }

    private static String normalizeArch(String str) {
        String strNormalize = normalize(str);
        return strNormalize.matches("^(x8664|amd64|ia32e|em64t|x64)$") ? "x86_64" : strNormalize.matches("^(x8632|x86|i[3-6]86|ia32|x32)$") ? "x86_32" : strNormalize.matches("^(ia64|itanium64)$") ? "itanium_64" : strNormalize.matches("^(sparc|sparc32)$") ? "sparc_32" : strNormalize.matches("^(sparcv9|sparc64)$") ? "sparc_64" : strNormalize.matches("^(arm|arm32)$") ? "arm_32" : "aarch64".equals(strNormalize) ? "aarch_64" : strNormalize.matches("^(ppc|ppc32)$") ? "ppc_32" : "ppc64".equals(strNormalize) ? "ppc_64" : "ppc64le".equals(strNormalize) ? "ppcle_64" : "s390".equals(strNormalize) ? "s390_32" : "s390x".equals(strNormalize) ? "s390_64" : UNKNOWN;
    }

    private static String normalizeOs(String str) {
        String strNormalize = normalize(str);
        if (strNormalize.startsWith("aix")) {
            return "aix";
        }
        if (strNormalize.startsWith("hpux")) {
            return "hpux";
        }
        if (strNormalize.startsWith("os400") && (strNormalize.length() <= 5 || !Character.isDigit(strNormalize.charAt(5)))) {
            return "os400";
        }
        if (strNormalize.startsWith(LINUX)) {
            return LINUX;
        }
        String str2 = "osx";
        if (!strNormalize.startsWith("macosx") && !strNormalize.startsWith("osx")) {
            if (strNormalize.startsWith("freebsd")) {
                return "freebsd";
            }
            if (strNormalize.startsWith("openbsd")) {
                return "openbsd";
            }
            if (strNormalize.startsWith("netbsd")) {
                return "netbsd";
            }
            str2 = "sunos";
            if (!strNormalize.startsWith("solaris") && !strNormalize.startsWith("sunos")) {
                return strNormalize.startsWith("windows") ? "windows" : UNKNOWN;
            }
        }
        return str2;
    }

    public static boolean supportsKeyManagerFactory() {
        return SUPPORTS_KEYMANAGER_FACTORY;
    }

    public static Throwable unavailabilityCause() {
        return UNAVAILABILITY_CAUSE;
    }

    public static int version() {
        if (isAvailable()) {
            return SSL.version();
        }
        return -1;
    }

    public static String versionString() {
        if (isAvailable()) {
            return SSL.versionString();
        }
        return null;
    }
}
