package com.android.org.conscrypt;

import android.compat.annotation.UnsupportedAppUsage;
import com.android.org.conscrypt.io.IoUtils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import javax.security.auth.x500.X500Principal;

/* JADX INFO: loaded from: classes.dex */
public class TrustedCertificateStore implements ConscryptCertStore {
    private static final CertificateFactory CERT_FACTORY;
    private static final String PREFIX_SYSTEM = "system:";
    private static final String PREFIX_USER = "user:";
    private final File addedDir;
    private final File deletedDir;
    private final File systemDir;

    private interface CertSelector {
        boolean match(X509Certificate x509Certificate);
    }

    private static class PreloadHolder {
        private static File defaultCaCertsAddedDir;
        private static File defaultCaCertsDeletedDir;
        private static File defaultCaCertsSystemDir;

        static {
            String str = System.getenv("ANDROID_ROOT");
            String str2 = System.getenv("ANDROID_DATA");
            defaultCaCertsSystemDir = new File(str + "/etc/security/cacerts");
            TrustedCertificateStore.setDefaultUserDirectory(new File(str2 + "/misc/keychain"));
        }

        private PreloadHolder() {
        }
    }

    static {
        try {
            CERT_FACTORY = CertificateFactory.getInstance("X509");
        } catch (CertificateException e3) {
            throw new AssertionError(e3);
        }
    }

    @UnsupportedAppUsage
    public TrustedCertificateStore() {
        this(PreloadHolder.defaultCaCertsSystemDir, PreloadHolder.defaultCaCertsAddedDir, PreloadHolder.defaultCaCertsDeletedDir);
    }

    private void addAliases(Set<String> set, String str, File file) {
        String[] list = file.list();
        if (list == null) {
            return;
        }
        for (String str2 : list) {
            String str3 = str + str2;
            if (containsAlias(str3)) {
                set.add(str3);
            }
        }
    }

    private static OpenSSLX509Certificate convertToOpenSSLIfNeeded(X509Certificate x509Certificate) throws CertificateException {
        if (x509Certificate == null) {
            return null;
        }
        if (x509Certificate instanceof OpenSSLX509Certificate) {
            return (OpenSSLX509Certificate) x509Certificate;
        }
        try {
            return OpenSSLX509Certificate.fromX509Der(x509Certificate.getEncoded());
        } catch (Exception e3) {
            throw new CertificateException(e3);
        }
    }

    private File file(File file, String str, int i3) {
        return new File(file, str + '.' + i3);
    }

    private File fileForAlias(String str) {
        File file;
        Objects.requireNonNull(str, "alias == null");
        if (!isSystem(str)) {
            if (isUser(str)) {
                file = new File(this.addedDir, str.substring(5));
            }
            return null;
        }
        file = new File(this.systemDir, str.substring(7));
        if (!file.exists() || isTombstone(file)) {
            return null;
        }
        return file;
    }

    /* JADX WARN: Multi-variable type inference failed */
    /* JADX WARN: Type inference failed for: r4v0, types: [T, java.io.File] */
    /* JADX WARN: Type inference failed for: r5v2, types: [T, java.lang.Object, java.security.cert.X509Certificate] */
    private <T> T findCert(File file, X500Principal x500Principal, CertSelector certSelector, Class<T> cls) {
        ?? r5;
        String strHash = hash(x500Principal);
        int i3 = 0;
        T t2 = null;
        while (true) {
            ?? r4 = (T) file(file, strHash, i3);
            if (!r4.isFile()) {
                if (cls == Boolean.class) {
                    return (T) Boolean.FALSE;
                }
                if (cls == File.class) {
                    return r4;
                }
                if (cls == Set.class) {
                    return t2;
                }
                return null;
            }
            if (!isTombstone(r4) && (r5 = (T) readCertificate(r4)) != 0 && certSelector.match(r5)) {
                if (cls == X509Certificate.class) {
                    return r5;
                }
                if (cls == Boolean.class) {
                    return (T) Boolean.TRUE;
                }
                if (cls == File.class) {
                    return r4;
                }
                if (cls != Set.class) {
                    throw new AssertionError();
                }
                if (t2 == null) {
                    t2 = (T) new HashSet();
                }
                ((Set) t2).add(r5);
            }
            i3++;
        }
    }

    private Set<X509Certificate> findCertSet(File file, X500Principal x500Principal, CertSelector certSelector) {
        return (Set) findCert(file, x500Principal, certSelector, Set.class);
    }

    private String hash(X500Principal x500Principal) {
        return Hex.intToHexString(NativeCrypto.X509_NAME_hash_old(x500Principal), 8);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public boolean isDeletedSystemCertificate(X509Certificate x509Certificate) {
        return getCertificateFile(this.deletedDir, x509Certificate).exists();
    }

    private static boolean isSelfIssuedCertificate(OpenSSLX509Certificate openSSLX509Certificate) {
        long context = openSSLX509Certificate.getContext();
        return NativeCrypto.X509_check_issued(context, openSSLX509Certificate, context, openSSLX509Certificate) == 0;
    }

    public static final boolean isSystem(String str) {
        return str.startsWith(PREFIX_SYSTEM);
    }

    private boolean isTombstone(File file) {
        return file.length() == 0;
    }

    public static final boolean isUser(String str) {
        return str.startsWith(PREFIX_USER);
    }

    private X509Certificate readCertificate(File file) throws Throwable {
        BufferedInputStream bufferedInputStream;
        BufferedInputStream bufferedInputStream2 = null;
        if (!file.isFile()) {
            return null;
        }
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
        } catch (IOException unused) {
            bufferedInputStream = null;
        } catch (CertificateException unused2) {
            bufferedInputStream = null;
        } catch (Throwable th) {
            th = th;
        }
        try {
            X509Certificate x509Certificate = (X509Certificate) CERT_FACTORY.generateCertificate(bufferedInputStream);
            IoUtils.closeQuietly(bufferedInputStream);
            return x509Certificate;
        } catch (IOException unused3) {
            IoUtils.closeQuietly(bufferedInputStream);
            return null;
        } catch (CertificateException unused4) {
            IoUtils.closeQuietly(bufferedInputStream);
            return null;
        } catch (Throwable th2) {
            th = th2;
            bufferedInputStream2 = bufferedInputStream;
            IoUtils.closeQuietly(bufferedInputStream2);
            throw th;
        }
    }

    private void removeUnnecessaryTombstones(String str) throws IOException {
        if (!isUser(str)) {
            throw new AssertionError(str);
        }
        int iLastIndexOf = str.lastIndexOf(46);
        if (iLastIndexOf == -1) {
            throw new AssertionError(str);
        }
        String strSubstring = str.substring(5, iLastIndexOf);
        int i3 = Integer.parseInt(str.substring(iLastIndexOf + 1));
        if (file(this.addedDir, strSubstring, i3 + 1).exists()) {
            return;
        }
        while (i3 >= 0) {
            File file = file(this.addedDir, strSubstring, i3);
            if (!isTombstone(file)) {
                return;
            }
            if (!file.delete()) {
                throw new IOException("Could not remove " + file);
            }
            i3--;
        }
    }

    public static void setDefaultUserDirectory(File file) {
        File unused = PreloadHolder.defaultCaCertsAddedDir = new File(file, "cacerts-added");
        File unused2 = PreloadHolder.defaultCaCertsDeletedDir = new File(file, "cacerts-removed");
    }

    private void writeCertificate(File file, X509Certificate x509Certificate) throws Throwable {
        FileOutputStream fileOutputStream;
        Throwable th;
        File parentFile = file.getParentFile();
        parentFile.mkdirs();
        parentFile.setReadable(true, false);
        parentFile.setExecutable(true, false);
        try {
            fileOutputStream = new FileOutputStream(file);
            try {
                fileOutputStream.write(x509Certificate.getEncoded());
                IoUtils.closeQuietly(fileOutputStream);
                file.setReadable(true, false);
            } catch (Throwable th2) {
                th = th2;
                IoUtils.closeQuietly(fileOutputStream);
                throw th;
            }
        } catch (Throwable th3) {
            fileOutputStream = null;
            th = th3;
        }
    }

    public Set<String> aliases() {
        HashSet hashSet = new HashSet();
        addAliases(hashSet, PREFIX_USER, this.addedDir);
        addAliases(hashSet, PREFIX_SYSTEM, this.systemDir);
        return hashSet;
    }

    public Set<String> allSystemAliases() {
        HashSet hashSet = new HashSet();
        String[] list = this.systemDir.list();
        if (list == null) {
            return hashSet;
        }
        for (String str : list) {
            String str2 = PREFIX_SYSTEM + str;
            if (containsAlias(str2, true)) {
                hashSet.add(str2);
            }
        }
        return hashSet;
    }

    public boolean containsAlias(String str) {
        return containsAlias(str, false);
    }

    public void deleteCertificateEntry(String str) throws Throwable {
        File fileFileForAlias;
        if (str == null || (fileFileForAlias = fileForAlias(str)) == null) {
            return;
        }
        if (!isSystem(str)) {
            if (isUser(str)) {
                new FileOutputStream(fileFileForAlias).close();
                removeUnnecessaryTombstones(str);
                return;
            }
            return;
        }
        X509Certificate certificate = readCertificate(fileFileForAlias);
        if (certificate == null) {
            return;
        }
        File certificateFile = getCertificateFile(this.deletedDir, certificate);
        if (certificateFile.exists()) {
            return;
        }
        writeCertificate(certificateFile, certificate);
    }

    @Override // com.android.org.conscrypt.ConscryptCertStore
    public Set<X509Certificate> findAllIssuers(final X509Certificate x509Certificate) {
        CertSelector certSelector = new CertSelector() { // from class: com.android.org.conscrypt.TrustedCertificateStore.4
            @Override // com.android.org.conscrypt.TrustedCertificateStore.CertSelector
            public boolean match(X509Certificate x509Certificate2) {
                try {
                    x509Certificate.verify(x509Certificate2.getPublicKey());
                    return true;
                } catch (Exception unused) {
                    return false;
                }
            }
        };
        X500Principal issuerX500Principal = x509Certificate.getIssuerX500Principal();
        Set<X509Certificate> setFindCertSet = findCertSet(this.addedDir, issuerX500Principal, certSelector);
        if (setFindCertSet == null) {
            setFindCertSet = null;
        }
        Set<X509Certificate> setFindCertSet2 = findCertSet(this.systemDir, issuerX500Principal, new CertSelector() { // from class: com.android.org.conscrypt.TrustedCertificateStore.5
            @Override // com.android.org.conscrypt.TrustedCertificateStore.CertSelector
            public boolean match(X509Certificate x509Certificate2) {
                try {
                    if (TrustedCertificateStore.this.isDeletedSystemCertificate(x509Certificate2)) {
                        return false;
                    }
                    x509Certificate.verify(x509Certificate2.getPublicKey());
                    return true;
                } catch (Exception unused) {
                    return false;
                }
            }
        });
        if (setFindCertSet2 != null) {
            if (setFindCertSet != null) {
                setFindCertSet.addAll(setFindCertSet2);
            } else {
                setFindCertSet = setFindCertSet2;
            }
        }
        return setFindCertSet != null ? setFindCertSet : Collections.emptySet();
    }

    public X509Certificate findIssuer(final X509Certificate x509Certificate) {
        CertSelector certSelector = new CertSelector() { // from class: com.android.org.conscrypt.TrustedCertificateStore.3
            @Override // com.android.org.conscrypt.TrustedCertificateStore.CertSelector
            public boolean match(X509Certificate x509Certificate2) {
                try {
                    x509Certificate.verify(x509Certificate2.getPublicKey());
                    return true;
                } catch (Exception unused) {
                    return false;
                }
            }
        };
        X500Principal issuerX500Principal = x509Certificate.getIssuerX500Principal();
        X509Certificate x509Certificate2 = (X509Certificate) findCert(this.addedDir, issuerX500Principal, certSelector, X509Certificate.class);
        if (x509Certificate2 != null) {
            return x509Certificate2;
        }
        X509Certificate x509Certificate3 = (X509Certificate) findCert(this.systemDir, issuerX500Principal, certSelector, X509Certificate.class);
        if (x509Certificate3 == null || isDeletedSystemCertificate(x509Certificate3)) {
            return null;
        }
        return x509Certificate3;
    }

    public Certificate getCertificate(String str) {
        return getCertificate(str, false);
    }

    public String getCertificateAlias(Certificate certificate) {
        return getCertificateAlias(certificate, false);
    }

    @UnsupportedAppUsage
    public List<X509Certificate> getCertificateChain(X509Certificate x509Certificate) throws CertificateException {
        LinkedHashSet linkedHashSet = new LinkedHashSet();
        OpenSSLX509Certificate openSSLX509CertificateConvertToOpenSSLIfNeeded = convertToOpenSSLIfNeeded(x509Certificate);
        linkedHashSet.add(openSSLX509CertificateConvertToOpenSSLIfNeeded);
        while (!isSelfIssuedCertificate(openSSLX509CertificateConvertToOpenSSLIfNeeded) && (openSSLX509CertificateConvertToOpenSSLIfNeeded = convertToOpenSSLIfNeeded(findIssuer(openSSLX509CertificateConvertToOpenSSLIfNeeded))) != null && !linkedHashSet.contains(openSSLX509CertificateConvertToOpenSSLIfNeeded)) {
            linkedHashSet.add(openSSLX509CertificateConvertToOpenSSLIfNeeded);
        }
        return new ArrayList(linkedHashSet);
    }

    public File getCertificateFile(File file, final X509Certificate x509Certificate) {
        return (File) findCert(file, x509Certificate.getSubjectX500Principal(), new CertSelector() { // from class: com.android.org.conscrypt.TrustedCertificateStore.1
            @Override // com.android.org.conscrypt.TrustedCertificateStore.CertSelector
            public boolean match(X509Certificate x509Certificate2) {
                return x509Certificate2.equals(x509Certificate);
            }
        }, File.class);
    }

    public Date getCreationDate(String str) {
        File fileFileForAlias;
        if (!containsAlias(str) || (fileFileForAlias = fileForAlias(str)) == null) {
            return null;
        }
        long jLastModified = fileFileForAlias.lastModified();
        if (jLastModified == 0) {
            return null;
        }
        return new Date(jLastModified);
    }

    @Override // com.android.org.conscrypt.ConscryptCertStore
    public X509Certificate getTrustAnchor(final X509Certificate x509Certificate) {
        CertSelector certSelector = new CertSelector() { // from class: com.android.org.conscrypt.TrustedCertificateStore.2
            @Override // com.android.org.conscrypt.TrustedCertificateStore.CertSelector
            public boolean match(X509Certificate x509Certificate2) {
                return x509Certificate2.getPublicKey().equals(x509Certificate.getPublicKey());
            }
        };
        X509Certificate x509Certificate2 = (X509Certificate) findCert(this.addedDir, x509Certificate.getSubjectX500Principal(), certSelector, X509Certificate.class);
        if (x509Certificate2 != null) {
            return x509Certificate2;
        }
        X509Certificate x509Certificate3 = (X509Certificate) findCert(this.systemDir, x509Certificate.getSubjectX500Principal(), certSelector, X509Certificate.class);
        if (x509Certificate3 == null || isDeletedSystemCertificate(x509Certificate3)) {
            return null;
        }
        return x509Certificate3;
    }

    public void installCertificate(X509Certificate x509Certificate) throws Throwable {
        Objects.requireNonNull(x509Certificate, "cert == null");
        if (!getCertificateFile(this.systemDir, x509Certificate).exists()) {
            File certificateFile = getCertificateFile(this.addedDir, x509Certificate);
            if (certificateFile.exists()) {
                return;
            }
            writeCertificate(certificateFile, x509Certificate);
            return;
        }
        File certificateFile2 = getCertificateFile(this.deletedDir, x509Certificate);
        if (!certificateFile2.exists() || certificateFile2.delete()) {
            return;
        }
        throw new IOException("Could not remove " + certificateFile2);
    }

    public boolean isUserAddedCertificate(X509Certificate x509Certificate) {
        return getCertificateFile(this.addedDir, x509Certificate).exists();
    }

    public Set<String> userAliases() {
        HashSet hashSet = new HashSet();
        addAliases(hashSet, PREFIX_USER, this.addedDir);
        return hashSet;
    }

    private boolean containsAlias(String str, boolean z2) {
        return getCertificate(str, z2) != null;
    }

    public Certificate getCertificate(String str, boolean z2) {
        X509Certificate certificate;
        File fileFileForAlias = fileForAlias(str);
        if (fileFileForAlias == null || ((isUser(str) && isTombstone(fileFileForAlias)) || (certificate = readCertificate(fileFileForAlias)) == null || (isSystem(str) && !z2 && isDeletedSystemCertificate(certificate)))) {
            return null;
        }
        return certificate;
    }

    public String getCertificateAlias(Certificate certificate, boolean z2) {
        if (certificate != null && (certificate instanceof X509Certificate)) {
            X509Certificate x509Certificate = (X509Certificate) certificate;
            File certificateFile = getCertificateFile(this.addedDir, x509Certificate);
            if (certificateFile.exists()) {
                return PREFIX_USER + certificateFile.getName();
            }
            if (!z2 && isDeletedSystemCertificate(x509Certificate)) {
                return null;
            }
            File certificateFile2 = getCertificateFile(this.systemDir, x509Certificate);
            if (certificateFile2.exists()) {
                return PREFIX_SYSTEM + certificateFile2.getName();
            }
        }
        return null;
    }

    public TrustedCertificateStore(File file, File file2, File file3) {
        this.systemDir = file;
        this.addedDir = file2;
        this.deletedDir = file3;
    }
}
