package com.android.org.conscrypt;

import android.system.ErrnoException;
import android.system.Os;
import android.system.OsConstants;
import android.system.StructTimeval;
import com.android.org.conscrypt.ct.CTLogStore;
import com.android.org.conscrypt.ct.CTLogStoreImpl;
import com.android.org.conscrypt.ct.CTPolicy;
import com.android.org.conscrypt.ct.CTPolicyImpl;
import com.android.org.conscrypt.metrics.CipherSuite;
import com.android.org.conscrypt.metrics.ConscryptStatsLog;
import com.android.org.conscrypt.metrics.Protocol;
import dalvik.system.BlockGuard;
import dalvik.system.CloseGuard;
import java.io.FileDescriptor;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketImpl;
import java.security.AlgorithmParameters;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.crypto.spec.GCMParameterSpec;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SNIMatcher;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509ExtendedTrustManager;
import javax.net.ssl.X509TrustManager;
import libcore.net.NetworkSecurityPolicy;
import sun.security.x509.AlgorithmId;

/* JADX INFO: loaded from: classes.dex */
final class Platform {

    private static class NoPreloadHolder {
        public static final Platform MAPPER = new Platform();

        private NoPreloadHolder() {
        }
    }

    static void blockGuardOnNetwork() {
        BlockGuard.getThreadPolicy().onNetwork();
    }

    static void checkClientTrusted(X509TrustManager x509TrustManager, X509Certificate[] x509CertificateArr, String str, AbstractConscryptSocket abstractConscryptSocket) throws CertificateException {
        if (x509TrustManager instanceof X509ExtendedTrustManager) {
            ((X509ExtendedTrustManager) x509TrustManager).checkClientTrusted(x509CertificateArr, str, abstractConscryptSocket);
        } else {
            if (checkTrusted("checkClientTrusted", x509TrustManager, x509CertificateArr, str, Socket.class, abstractConscryptSocket) || checkTrusted("checkClientTrusted", x509TrustManager, x509CertificateArr, str, String.class, abstractConscryptSocket.getHandshakeSession().getPeerHost())) {
                return;
            }
            x509TrustManager.checkClientTrusted(x509CertificateArr, str);
        }
    }

    static void checkServerTrusted(X509TrustManager x509TrustManager, X509Certificate[] x509CertificateArr, String str, AbstractConscryptSocket abstractConscryptSocket) throws CertificateException {
        if (x509TrustManager instanceof X509ExtendedTrustManager) {
            ((X509ExtendedTrustManager) x509TrustManager).checkServerTrusted(x509CertificateArr, str, abstractConscryptSocket);
        } else {
            if (checkTrusted("checkServerTrusted", x509TrustManager, x509CertificateArr, str, Socket.class, abstractConscryptSocket) || checkTrusted("checkServerTrusted", x509TrustManager, x509CertificateArr, str, String.class, abstractConscryptSocket.getHandshakeSession().getPeerHost())) {
                return;
            }
            x509TrustManager.checkServerTrusted(x509CertificateArr, str);
        }
    }

    private static boolean checkTrusted(String str, X509TrustManager x509TrustManager, X509Certificate[] x509CertificateArr, String str2, Class<?> cls, Object obj) throws CertificateException {
        try {
            x509TrustManager.getClass().getMethod(str, X509Certificate[].class, String.class, cls).invoke(x509TrustManager, x509CertificateArr, str2, obj);
            return true;
        } catch (IllegalAccessException | NoSuchMethodException unused) {
            return false;
        } catch (InvocationTargetException e3) {
            if (e3.getCause() instanceof CertificateException) {
                throw ((CertificateException) e3.getCause());
            }
            throw new RuntimeException(e3.getCause());
        }
    }

    static void closeGuardClose(Object obj) {
        ((CloseGuard) obj).close();
    }

    static CloseGuard closeGuardGet() {
        return CloseGuard.get();
    }

    static void closeGuardOpen(Object obj, String str) {
        ((CloseGuard) obj).open(str);
    }

    static void closeGuardWarnIfOpen(Object obj) {
        ((CloseGuard) obj).warnIfOpen();
    }

    static void countTlsHandshake(boolean z2, String str, String str2, long j3) {
        Protocol protocolForName = Protocol.forName(str);
        CipherSuite cipherSuiteForName = CipherSuite.forName(str2);
        ConscryptStatsLog.write(ConscryptStatsLog.TLS_HANDSHAKE_REPORTED, z2, protocolForName.getId(), cipherSuiteForName.getId(), (int) j3);
    }

    static ConscryptEngineSocket createEngineSocket(SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8EngineSocket(sSLParametersImpl);
    }

    static ConscryptFileDescriptorSocket createFileDescriptorSocket(SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8FileDescriptorSocket(sSLParametersImpl);
    }

    static GCMParameters fromGCMParameterSpec(AlgorithmParameterSpec algorithmParameterSpec) {
        if (!(algorithmParameterSpec instanceof GCMParameterSpec)) {
            return null;
        }
        GCMParameterSpec gCMParameterSpec = (GCMParameterSpec) algorithmParameterSpec;
        return new GCMParameters(gCMParameterSpec.getTLen(), gCMParameterSpec.getIV());
    }

    static AlgorithmParameterSpec fromGCMParameters(AlgorithmParameters algorithmParameters) {
        try {
            return algorithmParameters.getParameterSpec(GCMParameterSpec.class);
        } catch (InvalidParameterSpecException unused) {
            return null;
        }
    }

    static String getCurveName(ECParameterSpec eCParameterSpec) {
        return eCParameterSpec.getCurveName();
    }

    static KeyStore getDefaultCertKeyStore() throws KeyStoreException {
        KeyStore keyStore = KeyStore.getInstance("AndroidCAStore");
        try {
            keyStore.load(null, null);
            return keyStore;
        } catch (IOException | NoSuchAlgorithmException | CertificateException e3) {
            throw new KeyStoreException(e3);
        }
    }

    public static ConscryptHostnameVerifier getDefaultHostnameVerifier() {
        return Conscrypt.wrapHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier());
    }

    public static String getDefaultProviderName() {
        return "AndroidOpenSSL";
    }

    static FileDescriptor getFileDescriptor(Socket socket) {
        return socket.getFileDescriptor$();
    }

    static FileDescriptor getFileDescriptorFromSSLSocket(AbstractConscryptSocket abstractConscryptSocket) {
        try {
            Field declaredField = Socket.class.getDeclaredField("impl");
            declaredField.setAccessible(true);
            Object obj = declaredField.get(abstractConscryptSocket);
            Field declaredField2 = SocketImpl.class.getDeclaredField("fd");
            declaredField2.setAccessible(true);
            return (FileDescriptor) declaredField2.get(obj);
        } catch (Exception e3) {
            throw new RuntimeException("Can't get FileDescriptor from socket", e3);
        }
    }

    static String getHostStringFromInetSocketAddress(InetSocketAddress inetSocketAddress) {
        return inetSocketAddress.getHostString();
    }

    static long getMillisSinceBoot() {
        return System.currentTimeMillis();
    }

    public static String getOriginalHostNameFromInetAddress(InetAddress inetAddress) {
        try {
            Method declaredMethod = InetAddress.class.getDeclaredMethod("holder", new Class[0]);
            declaredMethod.setAccessible(true);
            Method declaredMethod2 = Class.forName("java.net.InetAddress$InetAddressHolder").getDeclaredMethod("getOriginalHostName", new Class[0]);
            declaredMethod2.setAccessible(true);
            String str = (String) declaredMethod2.invoke(declaredMethod.invoke(inetAddress, new Object[0]), new Object[0]);
            return str == null ? inetAddress.getHostAddress() : str;
        } catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException unused) {
            return inetAddress.getHostAddress();
        } catch (InvocationTargetException e3) {
            throw new RuntimeException("Failed to get originalHostName", e3);
        }
    }

    static void getSSLParameters(SSLParameters sSLParameters, SSLParametersImpl sSLParametersImpl, AbstractConscryptSocket abstractConscryptSocket) {
        sSLParameters.setEndpointIdentificationAlgorithm(sSLParametersImpl.getEndpointIdentificationAlgorithm());
        sSLParameters.setUseCipherSuitesOrder(sSLParametersImpl.getUseCipherSuitesOrder());
        if (sSLParametersImpl.getUseSni() && AddressUtils.isValidSniHostname(abstractConscryptSocket.getHostname())) {
            sSLParameters.setServerNames(Collections.singletonList(new SNIHostName(abstractConscryptSocket.getHostname())));
        }
        sSLParameters.setApplicationProtocols(sSLParametersImpl.getApplicationProtocols());
    }

    static boolean isCTVerificationRequired(String str) {
        return NetworkSecurityPolicy.getInstance().isCertificateTransparencyVerificationRequired(str);
    }

    public static boolean isJavaxCertificateSupported() {
        return true;
    }

    static void logEvent(String str) {
        try {
            Class<?> cls = Class.forName("android.os.Process");
            int iIntValue = ((Integer) cls.getMethod("myUid", null).invoke(cls.newInstance(), new Object[0])).intValue();
            Class<?> cls2 = Class.forName("android.util.EventLog");
            cls2.getMethod("writeEvent", Integer.TYPE, Object[].class).invoke(cls2.newInstance(), 1397638484, new Object[]{"conscrypt", Integer.valueOf(iIntValue), str});
        } catch (Exception unused) {
        }
    }

    static CertBlocklist newDefaultBlocklist() {
        return CertBlocklistImpl.getDefault();
    }

    static ConscryptCertStore newDefaultCertStore() {
        return new TrustedCertificateStore();
    }

    static CTLogStore newDefaultLogStore() {
        return new CTLogStoreImpl();
    }

    static CTPolicy newDefaultPolicy(CTLogStore cTLogStore) {
        return new CTPolicyImpl(cTLogStore, 2);
    }

    static String oidToAlgorithmName(String str) {
        try {
            return AlgorithmId.get(str).getName();
        } catch (NoSuchAlgorithmException unused) {
            return str;
        }
    }

    private void ping() {
    }

    static boolean provideTrustManagerByDefault() {
        return false;
    }

    static boolean serverNamePermitted(SSLParametersImpl sSLParametersImpl, String str) {
        Collection<SNIMatcher> sNIMatchers = sSLParametersImpl.getSNIMatchers();
        if (sNIMatchers == null || sNIMatchers.isEmpty()) {
            return true;
        }
        SNIHostName sNIHostName = new SNIHostName(str);
        Iterator<SNIMatcher> it = sNIMatchers.iterator();
        while (it.hasNext()) {
            if (it.next().matches(sNIHostName)) {
                return true;
            }
        }
        return false;
    }

    static void setCurveName(ECParameterSpec eCParameterSpec, String str) {
        eCParameterSpec.setCurveName(str);
    }

    static void setSSLParameters(SSLParameters sSLParameters, SSLParametersImpl sSLParametersImpl, AbstractConscryptSocket abstractConscryptSocket) {
        sSLParametersImpl.setEndpointIdentificationAlgorithm(sSLParameters.getEndpointIdentificationAlgorithm());
        sSLParametersImpl.setUseCipherSuitesOrder(sSLParameters.getUseCipherSuitesOrder());
        List<SNIServerName> serverNames = sSLParameters.getServerNames();
        if (serverNames != null) {
            Iterator<SNIServerName> it = serverNames.iterator();
            while (true) {
                if (!it.hasNext()) {
                    break;
                }
                SNIServerName next = it.next();
                if (next.getType() == 0) {
                    abstractConscryptSocket.setHostname(((SNIHostName) next).getAsciiName());
                    break;
                }
            }
        }
        sSLParametersImpl.setApplicationProtocols(sSLParameters.getApplicationProtocols());
    }

    static void setSocketWriteTimeout(Socket socket, long j3) throws SocketException {
        try {
            Os.setsockoptTimeval(socket.getFileDescriptor$(), OsConstants.SOL_SOCKET, OsConstants.SO_SNDTIMEO, StructTimeval.fromMillis(j3));
        } catch (ErrnoException e3) {
            throw e3.rethrowAsSocketException();
        }
    }

    public static void setup() {
        NoPreloadHolder.MAPPER.ping();
    }

    static boolean supportsConscryptCertStore() {
        return true;
    }

    static boolean supportsX509ExtendedTrustManager() {
        return true;
    }

    static AlgorithmParameterSpec toGCMParameterSpec(int i3, byte[] bArr) {
        return new GCMParameterSpec(i3, bArr);
    }

    static SSLEngine unwrapEngine(SSLEngine sSLEngine) {
        return Java8EngineWrapper.getDelegate(sSLEngine);
    }

    static SSLEngine wrapEngine(ConscryptEngine conscryptEngine) {
        return new Java8EngineWrapper(conscryptEngine);
    }

    static OpenSSLKey wrapRsaKey(PrivateKey privateKey) {
        return null;
    }

    static SSLSession wrapSSLSession(ExternalSession externalSession) {
        return new Java8ExtendedSSLSession(externalSession);
    }

    static SSLSocketFactory wrapSocketFactoryIfNeeded(OpenSSLSocketFactoryImpl openSSLSocketFactoryImpl) {
        return openSSLSocketFactoryImpl;
    }

    private Platform() {
    }

    static ConscryptEngineSocket createEngineSocket(String str, int i3, SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8EngineSocket(str, i3, sSLParametersImpl);
    }

    static ConscryptFileDescriptorSocket createFileDescriptorSocket(String str, int i3, SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8FileDescriptorSocket(str, i3, sSLParametersImpl);
    }

    static ConscryptEngineSocket createEngineSocket(InetAddress inetAddress, int i3, SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8EngineSocket(inetAddress, i3, sSLParametersImpl);
    }

    static ConscryptFileDescriptorSocket createFileDescriptorSocket(InetAddress inetAddress, int i3, SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8FileDescriptorSocket(inetAddress, i3, sSLParametersImpl);
    }

    static ConscryptEngineSocket createEngineSocket(String str, int i3, InetAddress inetAddress, int i4, SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8EngineSocket(str, i3, inetAddress, i4, sSLParametersImpl);
    }

    static ConscryptFileDescriptorSocket createFileDescriptorSocket(String str, int i3, InetAddress inetAddress, int i4, SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8FileDescriptorSocket(str, i3, inetAddress, i4, sSLParametersImpl);
    }

    static ConscryptEngineSocket createEngineSocket(InetAddress inetAddress, int i3, InetAddress inetAddress2, int i4, SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8EngineSocket(inetAddress, i3, inetAddress2, i4, sSLParametersImpl);
    }

    static ConscryptFileDescriptorSocket createFileDescriptorSocket(InetAddress inetAddress, int i3, InetAddress inetAddress2, int i4, SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8FileDescriptorSocket(inetAddress, i3, inetAddress2, i4, sSLParametersImpl);
    }

    static ConscryptEngineSocket createEngineSocket(Socket socket, String str, int i3, boolean z2, SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8EngineSocket(socket, str, i3, z2, sSLParametersImpl);
    }

    static ConscryptFileDescriptorSocket createFileDescriptorSocket(Socket socket, String str, int i3, boolean z2, SSLParametersImpl sSLParametersImpl) throws IOException {
        return new Java8FileDescriptorSocket(socket, str, i3, z2, sSLParametersImpl);
    }

    static void checkClientTrusted(X509TrustManager x509TrustManager, X509Certificate[] x509CertificateArr, String str, ConscryptEngine conscryptEngine) throws CertificateException {
        if (x509TrustManager instanceof X509ExtendedTrustManager) {
            ((X509ExtendedTrustManager) x509TrustManager).checkClientTrusted(x509CertificateArr, str, conscryptEngine);
        } else {
            if (checkTrusted("checkClientTrusted", x509TrustManager, x509CertificateArr, str, SSLEngine.class, conscryptEngine) || checkTrusted("checkClientTrusted", x509TrustManager, x509CertificateArr, str, String.class, conscryptEngine.getHandshakeSession().getPeerHost())) {
                return;
            }
            x509TrustManager.checkClientTrusted(x509CertificateArr, str);
        }
    }

    static void checkServerTrusted(X509TrustManager x509TrustManager, X509Certificate[] x509CertificateArr, String str, ConscryptEngine conscryptEngine) throws CertificateException {
        if (x509TrustManager instanceof X509ExtendedTrustManager) {
            ((X509ExtendedTrustManager) x509TrustManager).checkServerTrusted(x509CertificateArr, str, conscryptEngine);
        } else {
            if (checkTrusted("checkServerTrusted", x509TrustManager, x509CertificateArr, str, SSLEngine.class, conscryptEngine) || checkTrusted("checkServerTrusted", x509TrustManager, x509CertificateArr, str, String.class, conscryptEngine.getHandshakeSession().getPeerHost())) {
                return;
            }
            x509TrustManager.checkServerTrusted(x509CertificateArr, str);
        }
    }

    static void getSSLParameters(SSLParameters sSLParameters, SSLParametersImpl sSLParametersImpl, ConscryptEngine conscryptEngine) {
        sSLParameters.setEndpointIdentificationAlgorithm(sSLParametersImpl.getEndpointIdentificationAlgorithm());
        sSLParameters.setUseCipherSuitesOrder(sSLParametersImpl.getUseCipherSuitesOrder());
        if (sSLParametersImpl.getUseSni() && AddressUtils.isValidSniHostname(conscryptEngine.getHostname())) {
            sSLParameters.setServerNames(Collections.singletonList(new SNIHostName(conscryptEngine.getHostname())));
        }
        sSLParameters.setApplicationProtocols(sSLParametersImpl.getApplicationProtocols());
    }

    static void setSSLParameters(SSLParameters sSLParameters, SSLParametersImpl sSLParametersImpl, ConscryptEngine conscryptEngine) {
        sSLParametersImpl.setEndpointIdentificationAlgorithm(sSLParameters.getEndpointIdentificationAlgorithm());
        sSLParametersImpl.setUseCipherSuitesOrder(sSLParameters.getUseCipherSuitesOrder());
        List<SNIServerName> serverNames = sSLParameters.getServerNames();
        if (serverNames != null) {
            Iterator<SNIServerName> it = serverNames.iterator();
            while (true) {
                if (!it.hasNext()) {
                    break;
                }
                SNIServerName next = it.next();
                if (next.getType() == 0) {
                    conscryptEngine.setHostname(((SNIHostName) next).getAsciiName());
                    break;
                }
            }
        }
        sSLParametersImpl.setApplicationProtocols(sSLParameters.getApplicationProtocols());
    }
}
