package df.root;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.bouncycastle.asn1.cmp.PKIFailureInfo;
import org.bouncycastle.pqc.crypto.xmss.XMSSKeyParameters;

/* JADX INFO: loaded from: classes2.dex */
public final class DFLaunchReporter {
    public static final String APP_LAUNCH = "APP_LAUNCH";
    private static final String APP_VERSION = "2026.11.17.1109";
    private static final String LOG_TRUNCATED = "\n[log truncated]\n";
    private static final int MAX_FAILURE_LOG_LENGTH = 32768;
    public static final String PRIVILEGE_FAILED = "PRIVILEGE_FAILED";
    public static final String PRIVILEGE_SUCCESS = "PRIVILEGE_SUCCESS";
    private static String deviceId;
    private static String launchId;
    private static final Set<String> COMPLETED = ConcurrentHashMap.newKeySet();
    private static final Executor WORKER = Executors.newSingleThreadExecutor(new ThreadFactory() { // from class: df.root.DFLaunchReporter.2
        @Override // java.util.concurrent.ThreadFactory
        public final Thread newThread(Runnable runnable) {
            return DFLaunchReporter.lambda$static$0(runnable);
        }
    });

    static /* synthetic */ Thread lambda$static$0(Runnable runnable) {
        Thread thread = new Thread(runnable, "DFLaunchReporter");
        thread.setDaemon(true);
        return thread;
    }

    private DFLaunchReporter() {
    }

    public static void report(Context context, String str) {
        report(context, str, null, null);
    }

    public static void report(Context context, String str, String str2) {
        report(context, str, str2, null);
    }

    public static void report(Context context, final String str, final String str2, final String str3) {
        if (COMPLETED.contains(str)) {
            return;
        }
        final Context contextCreateDeviceProtectedStorageContext = context.createDeviceProtectedStorageContext();
        final String strIdentity = identity(context);
        WORKER.execute(new Runnable() { // from class: df.root.DFLaunchReporter.0
            @Override // java.lang.Runnable
            public final void run() {
                DFLaunchReporter.lambda$report$0(str, contextCreateDeviceProtectedStorageContext, strIdentity, str2, str3);
            }
        });
    }

    static /* synthetic */ void lambda$report$0(String str, Context context, String str2, String str3, String str4) {
        String str5;
        if (COMPLETED.contains(str)) {
            return;
        }
        try {
            String strAsset = asset(context, "dfroot-app-id");
            if (strAsset.isEmpty()) {
                return;
            }
            str5 = str;
            try {
                String strPayload = payload(context, str2, strAsset, str5, str3, str4);
                File file = new File(context.getFilesDir(), "diagnostic-event-" + System.nanoTime() + ".json");
                writeAtomic(file, strPayload);
                if (!DFV2LaunchClient.report(context, strPayload)) {
                    Log.i("dfroot", "launch report queued event=" + str5 + " version=2026.11.17.1109");
                } else {
                    writeAtomic(new File(context.getFilesDir(), "diagnostic-complete-" + launchId + "-" + str5), "");
                    if (!file.delete()) {
                        Log.w("dfroot", "cannot remove delivered launch event=" + str5);
                    }
                    Log.i("dfroot", "launch report delivered event=" + str5 + " version=2026.11.17.1109");
                }
                COMPLETED.add(str5);
            } catch (Throwable th) {
                th = th;
                Log.w("dfroot", "launch report queue failed event=" + str5, th);
            }
        } catch (Throwable th2) {
            th = th2;
            str5 = str;
        }
    }

    public static IReporter privilegeReporter(final StringBuilder sb) {
        return new IReporter() { // from class: df.root.DFLaunchReporter.1
            @Override // df.root.IReporter
            public final void report(String str) {
                DFLaunchReporter.lambda$privilegeReporter$0(sb, str);
            }
        };
    }

    static /* synthetic */ void lambda$privilegeReporter$0(StringBuilder sb, String str) {
        Log.i("dfroot", str.trim());
        appendLog(sb, str);
    }

    public static String failureLog(StringBuilder sb, Throwable th) {
        String string;
        if (th != null) {
            appendLog(sb, Log.getStackTraceString(th));
        }
        synchronized (sb) {
            string = sb.length() == 0 ? null : sb.toString();
        }
        return string;
    }

    private static void appendLog(StringBuilder sb, String str) {
        if (str == null || str.isEmpty()) {
            return;
        }
        synchronized (sb) {
            int length = 32768 - LOG_TRUNCATED.length();
            if (sb.length() >= length) {
                return;
            }
            int length2 = length - sb.length();
            sb.append((CharSequence) str, 0, Math.min(length2, str.length()));
            if (str.length() > length2) {
                sb.append(LOG_TRUNCATED);
            }
        }
    }

    private static synchronized String identity(Context context) {
        if (deviceId != null) {
            return deviceId;
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences("df-diagnostic", 0);
        String strValidUuid = validUuid(sharedPreferences.getString("device_id", ""));
        File file = new File(context.getFilesDir(), "android-device-id");
        if (strValidUuid == null && file.isFile()) {
            try {
                strValidUuid = validUuid(new String(read(new FileInputStream(file)), StandardCharsets.US_ASCII).trim());
            } catch (IOException e) {
            }
        }
        if (strValidUuid == null) {
            try {
                strValidUuid = validUuid(new String(read(new FileInputStream("/data/local/tmp/.dfroot-device-id")), StandardCharsets.US_ASCII).trim());
            } catch (IOException e2) {
            }
        }
        if (strValidUuid == null) {
            strValidUuid = stableDeviceId();
        }
        if (strValidUuid == null) {
            strValidUuid = UUID.randomUUID().toString();
        }
        deviceId = strValidUuid;
        sharedPreferences.edit().putString("device_id", strValidUuid).apply();
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(context.getFilesDir(), "diagnostic-launch.lock"), true);
            try {
                FileChannel channel = fileOutputStream.getChannel();
                try {
                    FileLock fileLockLock = channel.lock();
                    try {
                        File file2 = new File(context.getFilesDir(), "diagnostic-launch-id");
                        String processName = Build.VERSION.SDK_INT >= 28 ? Application.getProcessName() : null;
                        if (processName == null) {
                            try {
                                String str = new String(read(new FileInputStream("/proc/self/cmdline")), StandardCharsets.UTF_8);
                                int iIndexOf = str.indexOf(0);
                                processName = iIndexOf >= 0 ? str.substring(0, iIndexOf) : str;
                            } catch (IOException e3) {
                            }
                        }
                        if (!context.getPackageName().equals(processName) && file2.isFile()) {
                            launchId = validUuid(new String(read(new FileInputStream(file2)), StandardCharsets.US_ASCII).trim());
                        }
                        if (launchId == null) {
                            launchId = UUID.randomUUID().toString();
                        }
                        writeAtomic(file, strValidUuid);
                        writeAtomic(file2, launchId);
                        writeAtomic(new File(context.getFilesDir(), "diagnostic-app-version"), APP_VERSION);
                        if (fileLockLock != null) {
                            fileLockLock.close();
                        }
                        if (channel != null) {
                            channel.close();
                        }
                        fileOutputStream.close();
                    } catch (Throwable th) {
                        if (fileLockLock != null) {
                            try {
                                fileLockLock.close();
                            } catch (Throwable th2) {
                                th.addSuppressed(th2);
                            }
                        }
                        throw th;
                    }
                } catch (Throwable th3) {
                    if (channel != null) {
                        try {
                            channel.close();
                        } catch (Throwable th4) {
                            th3.addSuppressed(th4);
                        }
                    }
                    throw th3;
                }
            } catch (Throwable th5) {
                try {
                    fileOutputStream.close();
                } catch (Throwable th6) {
                    th5.addSuppressed(th6);
                }
                throw th5;
            }
        } catch (IOException e4) {
            if (launchId == null) {
                launchId = UUID.randomUUID().toString();
            }
            Log.w("dfroot", "cannot stage diagnostic identity", e4);
        }
        return strValidUuid;
    }

    private static String stableDeviceId() {
        String str = Build.SERIAL;
        if (str == null || str.trim().isEmpty() || "unknown".equalsIgnoreCase(str.trim())) {
            return null;
        }
        try {
            byte[] bArrDigest = MessageDigest.getInstance(XMSSKeyParameters.SHA_256).digest(str.trim().getBytes(StandardCharsets.UTF_8));
            char[] cArr = new char[64];
            char[] charArray = "0123456789abcdef".toCharArray();
            for (int i = 0; i < bArrDigest.length; i++) {
                int i2 = bArrDigest[i] & 255;
                int i3 = i * 2;
                cArr[i3] = charArray[i2 >>> 4];
                cArr[i3 + 1] = charArray[i2 & 15];
            }
            cArr[12] = '5';
            cArr[16] = '8';
            return new String(cArr, 0, 8) + "-" + new String(cArr, 8, 4) + "-" + new String(cArr, 12, 4) + "-" + new String(cArr, 16, 4) + "-" + new String(cArr, 20, 12);
        } catch (Throwable th) {
            return null;
        }
    }

    private static String validUuid(String str) {
        if (str == null) {
            return null;
        }
        try {
            return UUID.fromString(str).toString();
        } catch (IllegalArgumentException e) {
            return null;
        }
    }

    private static void writeAtomic(File file, String str) throws IOException {
        if (file.isFile()) {
            try {
                if (str.equals(new String(read(new FileInputStream(file)), StandardCharsets.US_ASCII).trim())) {
                    return;
                }
            } catch (IOException e) {
            }
        }
        File file2 = new File(file.getParentFile(), file.getName() + ".tmp");
        FileOutputStream fileOutputStream = new FileOutputStream(file2);
        try {
            fileOutputStream.write(str.getBytes(StandardCharsets.US_ASCII));
            fileOutputStream.getFD().sync();
            fileOutputStream.close();
            if (!file2.renameTo(file)) {
                throw new IOException("cannot replace " + String.valueOf(file));
            }
        } catch (Throwable th) {
            try {
                fileOutputStream.close();
            } catch (Throwable th2) {
                th.addSuppressed(th2);
            }
            throw th;
        }
    }

    private static String payload(Context context, String str, String str2, String str3, String str4, String str5) {
        return "{\"launchId\":" + quote(launchId) + ",\"deviceId\":" + quote(str) + ",\"appId\":" + quote(str2) + ",\"eventType\":" + quote(str3) + ",\"rooted\":" + PRIVILEGE_SUCCESS.equals(str3) + ",\"appVersion\":" + quote(APP_VERSION) + ",\"failureReason\":" + nullableQuote(str4) + ",\"failureLog\":" + nullableQuote(str5) + ",\"packageName\":" + quote(context.getPackageName()) + ",\"manufacturer\":" + quote(value(Build.MANUFACTURER)) + ",\"brand\":" + quote(value(Build.BRAND)) + ",\"model\":" + quote(value(Build.MODEL)) + ",\"device\":" + quote(value(Build.DEVICE)) + ",\"hardware\":" + quote(value(Build.HARDWARE)) + ",\"androidVersion\":" + quote(value(Build.VERSION.RELEASE)) + ",\"sdkInt\":" + Build.VERSION.SDK_INT + ",\"kernelVersion\":" + quote(kernelVersion()) + ",\"fingerprint\":" + quote(value(Build.FINGERPRINT)) + "}";
    }

    private static String asset(Context context, String str) throws IOException {
        InputStream inputStreamOpen = context.getAssets().open(str);
        try {
            String strTrim = new String(read(inputStreamOpen), StandardCharsets.UTF_8).trim();
            if (inputStreamOpen != null) {
                inputStreamOpen.close();
            }
            return strTrim;
        } catch (Throwable th) {
            if (inputStreamOpen != null) {
                try {
                    inputStreamOpen.close();
                } catch (Throwable th2) {
                    th.addSuppressed(th2);
                }
            }
            throw th;
        }
    }

    private static String kernelVersion() {
        try {
            FileInputStream fileInputStream = new FileInputStream("/proc/version");
            try {
                String strTrim = new String(read(fileInputStream), StandardCharsets.UTF_8).trim();
                if (!strTrim.isEmpty()) {
                    if (strTrim.length() > 512) {
                        strTrim = strTrim.substring(0, 512);
                    }
                    fileInputStream.close();
                    return strTrim;
                }
                fileInputStream.close();
                return value(System.getProperty("os.version"));
            } catch (Throwable th) {
                try {
                    fileInputStream.close();
                } catch (Throwable th2) {
                    th.addSuppressed(th2);
                }
                throw th;
            }
        } catch (Throwable th3) {
        }
        return value(System.getProperty("os.version"));
    }

    private static byte[] read(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            byte[] bArr = new byte[PKIFailureInfo.certConfirmed];
            while (true) {
                int i = inputStream.read(bArr);
                if (i < 0) {
                    break;
                }
                if (i > 0) {
                    byteArrayOutputStream.write(bArr, 0, i);
                }
            }
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            if (inputStream != null) {
                inputStream.close();
            }
            return byteArray;
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Throwable th2) {
                    th.addSuppressed(th2);
                }
            }
            throw th;
        }
    }

    private static String value(String str) {
        return (str == null || str.trim().isEmpty()) ? "unknown" : str.trim();
    }

    private static String nullableQuote(String str) {
        return str == null ? "null" : quote(str);
    }

    private static String quote(String str) {
        StringBuilder sbAppend = new StringBuilder(str.length() + 2).append('\"');
        for (int i = 0; i < str.length(); i++) {
            char cCharAt = str.charAt(i);
            if (cCharAt == '\"' || cCharAt == '\\') {
                sbAppend.append('\\').append(cCharAt);
            } else if (cCharAt == '\n') {
                sbAppend.append("\\n");
            } else if (cCharAt == '\r') {
                sbAppend.append("\\r");
            } else if (cCharAt == '\t') {
                sbAppend.append("\\t");
            } else if (cCharAt < ' ') {
                sbAppend.append(String.format("\\u%04x", Integer.valueOf(cCharAt)));
            } else {
                sbAppend.append(cCharAt);
            }
        }
        return sbAppend.append('\"').toString();
    }
}
