package df.root;

import android.content.Context;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/* JADX INFO: loaded from: classes.dex */
final class DaemonClient {
    private DaemonClient() {
    }

    static String request(Context context, String str) throws IOException {
        if (!str.equals("STATUS") && !str.equals("STOP") && !str.equals("EXPORT") && !str.equals("UPDATE")) {
            throw new IllegalArgumentException("Unsupported daemon command");
        }
        File file = new File("/data/local/tmp/.dfroot-runtime/files/daemon.sock");
        if (!file.exists()) {
            file = new File(context.getFilesDir(), "daemon.sock");
        }
        LocalSocket localSocket = new LocalSocket();
        try {
            localSocket.connect(new LocalSocketAddress(file.getAbsolutePath(), LocalSocketAddress.Namespace.FILESYSTEM));
            localSocket.setSoTimeout(str.equals("EXPORT") ? 900000 : 3000);
            if (localSocket.getPeerCredentials().getUid() != 0) {
                throw new IOException("Daemon socket peer is not UID 0");
            }
            localSocket.getOutputStream().write((str + "\n").getBytes(StandardCharsets.US_ASCII));
            localSocket.shutdownOutput();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bArr = new byte[512];
            while (true) {
                int i = localSocket.getInputStream().read(bArr);
                if (i != -1) {
                    if (byteArrayOutputStream.size() + i > 8192) {
                        throw new IOException("Oversized daemon response");
                    }
                    byteArrayOutputStream.write(bArr, 0, i);
                } else {
                    String str2 = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
                    if (!str2.startsWith("DFROOT_DAEMON/1\n")) {
                        throw new IOException("Invalid daemon protocol response");
                    }
                    if (str.equals("STATUS") && (!str2.contains("\nuid=0\n") || !str2.contains("\neuid=0\n"))) {
                        throw new IOException("Daemon did not report UID/EUID 0");
                    }
                    localSocket.close();
                    return str2;
                }
            }
        } catch (Throwable th) {
            try {
                localSocket.close();
            } catch (Throwable th2) {
                th.addSuppressed(th2);
            }
            throw th;
        }
    }
}
