NetGuard v2.328版本的 MD5 值为:4adaa6f0accf8a6a5ab62c36e5a5d3f8

以下内容为反编译后的 ServiceSinkhole.java 源代码,内容仅作参考


package eu.faircode.netguard;

import B.b;
import K0.r;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.TrafficStats;
import android.net.Uri;
import android.net.VpnService;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.PowerManager;
import android.os.Process;
import android.os.SystemClock;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.util.Pair;
import android.util.TypedValue;
import android.widget.RemoteViews;
import androidx.core.app.C;
import androidx.core.app.o;
import androidx.core.app.q;
import androidx.core.app.s;
import androidx.core.content.f;
import androidx.core.text.d;
import androidx.core.view.C0142h;
import eu.faircode.netguard.IPUtil;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import t.C0496d;
public class ServiceSinkhole extends VpnService implements SharedPreferences.OnSharedPreferenceChangeListener {
    private static long jni_context;
    private static Object jni_lock = new Object();
    private static volatile PowerManager.WakeLock wlInstance;
    private volatile CommandHandler commandHandler;
    private volatile Looper commandLooper;
    private volatile LogHandler logHandler;
    private volatile Looper logLooper;
    private volatile StatsHandler statsHandler;
    private volatile Looper statsLooper;
    private boolean registeredUser = false;
    private boolean registeredIdleState = false;
    private boolean registeredConnectivityChanged = false;
    private boolean registeredPackageChanged = false;
    private boolean phone_state = false;
    private Object networkCallback = null;
    private boolean registeredInteractiveState = false;
    private PhoneStateListener callStateListener = null;
    private State state = State.none;
    private boolean user_foreground = true;
    private boolean last_connected = false;
    private boolean last_metered = true;
    private boolean last_interactive = false;
    private int last_allowed = -1;
    private int last_blocked = -1;
    private int last_hosts = -1;
    private Thread tunnelThread = null;
    private Builder last_builder = null;
    private ParcelFileDescriptor vpn = null;
    private boolean temporarilyStopped = false;
    private long last_hosts_modified = 0;
    private long last_malware_modified = 0;
    private Map mapHostsBlocked = new HashMap();
    private Map mapMalware = new HashMap();
    private Map mapUidAllowed = new HashMap();
    private Map mapUidKnown = new HashMap();
    private final Map mapUidIPFilters = new HashMap();
    private Map mapForward = new HashMap();
    private Map mapNotify = new HashMap();
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
    private ExecutorService executor = Executors.newCachedThreadPool();
    private BroadcastReceiver interactiveStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            Log.i("NetGuard.Service", "Received " + intent);
            Util.logExtras(intent);
            ServiceSinkhole.this.executor.submit(new Runnable() {
                @Override
                public void run() {
                    int i2;
                    AlarmManager alarmManager = (AlarmManager) context.getSystemService("alarm");
                    Intent intent2 = new Intent("eu.faircode.netguard.SCREEN_OFF_DELAYED");
                    intent2.setPackage(context.getPackageName());
                    PendingIntent broadcast = PendingIntentCompat.getBroadcast(context, 0, intent2, 134217728);
                    alarmManager.cancel(broadcast);
                    try {
                        try {
                            i2 = Integer.parseInt(b.f(ServiceSinkhole.this).getString("screen_delay", "0"));
                        } catch (NumberFormatException unused) {
                            i2 = 0;
                        }
                        boolean equals = "android.intent.action.SCREEN_ON".equals(intent.getAction());
                        int i3 = 1;
                        if (equals || i2 == 0) {
                            ServiceSinkhole.this.last_interactive = equals;
                            ServiceSinkhole.reload("interactive state changed", ServiceSinkhole.this, true);
                        } else if ("eu.faircode.netguard.SCREEN_OFF_DELAYED".equals(intent.getAction())) {
                            ServiceSinkhole.this.last_interactive = equals;
                            ServiceSinkhole.reload("interactive state changed", ServiceSinkhole.this, true);
                        } else if (Build.VERSION.SDK_INT < 23) {
                            alarmManager.set(0, (i2 * 60 * 1000) + new Date().getTime(), broadcast);
                        } else {
                            alarmManager.setAndAllowWhileIdle(0, (i2 * 60 * 1000) + new Date().getTime(), broadcast);
                        }
                        StatsHandler statsHandler = ServiceSinkhole.this.statsHandler;
                        if (!Util.isInteractive(ServiceSinkhole.this)) {
                            i3 = 2;
                        }
                        statsHandler.sendEmptyMessage(i3);
                    } catch (Throwable th) {
                        r.h(th, new StringBuilder(), "\n", th, "NetGuard.Service");
                        if (Build.VERSION.SDK_INT < 23) {
                            alarmManager.set(0, new Date().getTime() + 15000, broadcast);
                        } else {
                            alarmManager.setAndAllowWhileIdle(0, new Date().getTime() + 15000, broadcast);
                        }
                    }
                }
            });
        }
    };
    private BroadcastReceiver userReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("NetGuard.Service", "Received " + intent);
            Util.logExtras(intent);
            ServiceSinkhole.this.user_foreground = "android.intent.action.USER_FOREGROUND".equals(intent.getAction());
            Log.i("NetGuard.Service", "User foreground=" + ServiceSinkhole.this.user_foreground + " user=" + (Process.myUid() / 100000));
            if (!ServiceSinkhole.this.user_foreground) {
                ServiceSinkhole.stop("background", ServiceSinkhole.this, true);
            } else if (b.f(ServiceSinkhole.this).getBoolean("enabled", false)) {
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException unused) {
                }
                ServiceSinkhole.start("foreground", ServiceSinkhole.this);
            }
        }
    };
    private BroadcastReceiver idleStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isDeviceIdleMode;
            boolean isDeviceIdleMode2;
            Log.i("NetGuard.Service", "Received " + intent);
            Util.logExtras(intent);
            PowerManager powerManager = (PowerManager) context.getSystemService("power");
            StringBuilder sb = new StringBuilder("device idle=");
            isDeviceIdleMode = powerManager.isDeviceIdleMode();
            sb.append(isDeviceIdleMode);
            Log.i("NetGuard.Service", sb.toString());
            isDeviceIdleMode2 = powerManager.isDeviceIdleMode();
            if (isDeviceIdleMode2) {
                return;
            }
            ServiceSinkhole.reload("idle state changed", ServiceSinkhole.this, false);
        }
    };
    private BroadcastReceiver connectivityChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getIntExtra("networkType", 8) == 17) {
                return;
            }
            Log.i("NetGuard.Service", "Received " + intent);
            Util.logExtras(intent);
            ServiceSinkhole.reload("connectivity changed", ServiceSinkhole.this, false);
        }
    };
    ConnectivityManager.NetworkCallback networkMonitorCallback = new ConnectivityManager.NetworkCallback() {
        private String TAG = "NetGuard.Monitor";
        private Map validated = new HashMap();

        private void checkConnectivity(Network network, NetworkInfo networkInfo, NetworkCapabilities networkCapabilities) {
            String str;
            StringBuilder sb;
            if (networkInfo == null || networkCapabilities == null || networkInfo.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED || networkInfo.getDetailedState() == NetworkInfo.DetailedState.BLOCKED || networkInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED || !networkCapabilities.hasCapability(15) || networkCapabilities.hasCapability(16)) {
                return;
            }
            synchronized (this.validated) {
                try {
                    if (this.validated.containsKey(network) && ((Long) this.validated.get(network)).longValue() + 20000 > new Date().getTime()) {
                        String str2 = this.TAG;
                        Log.i(str2, "Already validated " + network + " " + networkInfo);
                        return;
                    }
                    String string = b.f(ServiceSinkhole.this).getString("validate", "www.google.com");
                    String str3 = this.TAG;
                    Log.i(str3, "Validating " + network + " " + networkInfo + " host=" + string);
                    Socket socket = null;
                    try {
                        try {
                            Socket createSocket = network.getSocketFactory().createSocket();
                            createSocket.connect(new InetSocketAddress(string, 443), 10000);
                            String str4 = this.TAG;
                            Log.i(str4, "Validated " + network + " " + networkInfo + " host=" + string);
                            synchronized (this.validated) {
                                try {
                                    this.validated.put(network, Long.valueOf(new Date().getTime()));
                                } catch (Throwable th) {
                                    throw th;
                                }
                            }
                            if (Build.VERSION.SDK_INT >= 23) {
                                ((ConnectivityManager) ServiceSinkhole.this.getSystemService("connectivity")).reportNetworkConnectivity(network, true);
                                String str5 = this.TAG;
                                Log.i(str5, "Reported " + network + " " + networkInfo);
                            }
                            try {
                                createSocket.close();
                            } catch (IOException e2) {
                                e = e2;
                                str = this.TAG;
                                sb = new StringBuilder();
                                r.f(e, sb, "\n", e, str);
                            }
                        } catch (IOException e3) {
                            Log.e(this.TAG, e3.toString());
                            String str6 = this.TAG;
                            Log.i(str6, "No connectivity " + network + " " + networkInfo);
                            if (0 != 0) {
                                try {
                                    socket.close();
                                } catch (IOException e4) {
                                    e = e4;
                                    str = this.TAG;
                                    sb = new StringBuilder();
                                    r.f(e, sb, "\n", e, str);
                                }
                            }
                        }
                    } catch (Throwable th2) {
                        if (0 != 0) {
                            try {
                                socket.close();
                            } catch (IOException e5) {
                                r.f(e5, new StringBuilder(), "\n", e5, this.TAG);
                            }
                        }
                        throw th2;
                    }
                } catch (Throwable th3) {
                    throw th3;
                }
            }
        }

        @Override
        public void onAvailable(Network network) {
            ConnectivityManager connectivityManager = (ConnectivityManager) ServiceSinkhole.this.getSystemService("connectivity");
            NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
            NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
            String str = this.TAG;
            Log.i(str, "Available network " + network + " " + networkInfo);
            String str2 = this.TAG;
            StringBuilder sb = new StringBuilder("Capabilities=");
            sb.append(networkCapabilities);
            Log.i(str2, sb.toString());
            checkConnectivity(network, networkInfo, networkCapabilities);
        }

        @Override
        public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
            NetworkInfo networkInfo = ((ConnectivityManager) ServiceSinkhole.this.getSystemService("connectivity")).getNetworkInfo(network);
            String str = this.TAG;
            Log.i(str, "New capabilities network " + network + " " + networkInfo);
            String str2 = this.TAG;
            StringBuilder sb = new StringBuilder("Capabilities=");
            sb.append(networkCapabilities);
            Log.i(str2, sb.toString());
            checkConnectivity(network, networkInfo, networkCapabilities);
        }

        @Override
        public void onLosing(Network network, int i2) {
            NetworkInfo networkInfo = ((ConnectivityManager) ServiceSinkhole.this.getSystemService("connectivity")).getNetworkInfo(network);
            String str = this.TAG;
            Log.i(str, "Losing network " + network + " within " + i2 + " ms " + networkInfo);
        }

        @Override
        public void onLost(Network network) {
            NetworkInfo networkInfo = ((ConnectivityManager) ServiceSinkhole.this.getSystemService("connectivity")).getNetworkInfo(network);
            String str = this.TAG;
            Log.i(str, "Lost network " + network + " " + networkInfo);
            synchronized (this.validated) {
                try {
                    this.validated.remove(network);
                } catch (Throwable th) {
                    throw th;
                }
            }
        }

        @Override
        public void onUnavailable() {
            Log.i(this.TAG, "No networks available");
        }
    };
    private PhoneStateListener phoneStateListener = new PhoneStateListener() {
        private String last_generation = null;

        @Override
        public void onDataConnectionStateChanged(int i2, int i3) {
            if (i2 == 2) {
                String networkGeneration = Util.getNetworkGeneration(ServiceSinkhole.this);
                Log.i("NetGuard.Service", "Data connected generation=" + networkGeneration);
                String str = this.last_generation;
                if (str == null || !str.equals(networkGeneration)) {
                    Log.i("NetGuard.Service", "New network generation=" + networkGeneration);
                    this.last_generation = networkGeneration;
                    SharedPreferences f = b.f(ServiceSinkhole.this);
                    if (f.getBoolean("unmetered_2g", false) || f.getBoolean("unmetered_3g", false) || f.getBoolean("unmetered_4g", false)) {
                        ServiceSinkhole.reload("data connection state changed", ServiceSinkhole.this, false);
                    }
                }
            }
        }
    };
    private BroadcastReceiver packageChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("NetGuard.Service", "Received " + intent);
            Util.logExtras(intent);
            try {
                if ("android.intent.action.PACKAGE_ADDED".equals(intent.getAction())) {
                    Rule.clearCache(context);
                    if (!intent.getBooleanExtra("android.intent.extra.REPLACING", false)) {
                        SharedPreferences f = b.f(context);
                        if (IAB.isPurchased("notify", context) && f.getBoolean("install", true)) {
                            ServiceSinkhole.this.notifyNewApplication(intent.getIntExtra("android.intent.extra.UID", -1), false);
                        }
                    }
                    ServiceSinkhole.reload("package added", context, false);
                } else if ("android.intent.action.PACKAGE_REMOVED".equals(intent.getAction())) {
                    Rule.clearCache(context);
                    if (intent.getBooleanExtra("android.intent.extra.DATA_REMOVED", false)) {
                        String schemeSpecificPart = intent.getData().getSchemeSpecificPart();
                        Log.i("NetGuard.Service", "Deleting settings package=" + schemeSpecificPart);
                        context.getSharedPreferences("wifi", 0).edit().remove(schemeSpecificPart).apply();
                        context.getSharedPreferences("other", 0).edit().remove(schemeSpecificPart).apply();
                        context.getSharedPreferences("screen_wifi", 0).edit().remove(schemeSpecificPart).apply();
                        context.getSharedPreferences("screen_other", 0).edit().remove(schemeSpecificPart).apply();
                        context.getSharedPreferences("roaming", 0).edit().remove(schemeSpecificPart).apply();
                        context.getSharedPreferences("lockdown", 0).edit().remove(schemeSpecificPart).apply();
                        context.getSharedPreferences("apply", 0).edit().remove(schemeSpecificPart).apply();
                        context.getSharedPreferences("notify", 0).edit().remove(schemeSpecificPart).apply();
                        int intExtra = intent.getIntExtra("android.intent.extra.UID", 0);
                        if (intExtra > 0) {
                            DatabaseHelper databaseHelper = DatabaseHelper.getInstance(context);
                            databaseHelper.clearLog(intExtra);
                            databaseHelper.clearAccess(intExtra, false);
                            C.c(context).b(intExtra);
                            C.c(context).b(intExtra + 10000);
                        }
                    }
                    ServiceSinkhole.reload("package deleted", context, false);
                }
            } catch (Throwable th) {
                r.h(th, new StringBuilder(), "\n", th, "NetGuard.Service");
            }
        }
    };

    public class AnonymousClass10 {
        static final int[] $SwitchMap$eu$faircode$netguard$ServiceSinkhole$Command;

        static {
            int[] iArr = new int[Command.values().length];
            $SwitchMap$eu$faircode$netguard$ServiceSinkhole$Command = iArr;
            try {
                iArr[Command.run.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$eu$faircode$netguard$ServiceSinkhole$Command[Command.start.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
            try {
                $SwitchMap$eu$faircode$netguard$ServiceSinkhole$Command[Command.reload.ordinal()] = 3;
            } catch (NoSuchFieldError unused3) {
            }
            try {
                $SwitchMap$eu$faircode$netguard$ServiceSinkhole$Command[Command.stop.ordinal()] = 4;
            } catch (NoSuchFieldError unused4) {
            }
            try {
                $SwitchMap$eu$faircode$netguard$ServiceSinkhole$Command[Command.stats.ordinal()] = 5;
            } catch (NoSuchFieldError unused5) {
            }
            try {
                $SwitchMap$eu$faircode$netguard$ServiceSinkhole$Command[Command.householding.ordinal()] = 6;
            } catch (NoSuchFieldError unused6) {
            }
            try {
                $SwitchMap$eu$faircode$netguard$ServiceSinkhole$Command[Command.watchdog.ordinal()] = 7;
            } catch (NoSuchFieldError unused7) {
            }
        }
    }

    public class Builder extends VpnService.Builder {
        private Network activeNetwork;
        private List listAddress;
        private List listAllowed;
        private List listDisallowed;
        private List listDns;
        private List listRoute;
        private int mtu;
        private NetworkInfo networkInfo;

        private Builder() {
            super(ServiceSinkhole.this);
            this.listAddress = new ArrayList();
            this.listRoute = new ArrayList();
            this.listDns = new ArrayList();
            this.listAllowed = new ArrayList();
            this.listDisallowed = new ArrayList();
            ConnectivityManager connectivityManager = (ConnectivityManager) ServiceSinkhole.this.getSystemService("connectivity");
            this.activeNetwork = Build.VERSION.SDK_INT < 23 ? null : connectivityManager.getActiveNetwork();
            this.networkInfo = connectivityManager.getActiveNetworkInfo();
        }

        @Override
        public Builder addAddress(String str, int i2) {
            List list = this.listAddress;
            list.add(str + "/" + i2);
            super.addAddress(str, i2);
            return this;
        }

        @Override
        public VpnService.Builder addAllowedApplication(String str) {
            this.listAllowed.add(str);
            return super.addAllowedApplication(str);
        }

        @Override
        public Builder addDisallowedApplication(String str) {
            this.listDisallowed.add(str);
            super.addDisallowedApplication(str);
            return this;
        }

        @Override
        public Builder addDnsServer(InetAddress inetAddress) {
            this.listDns.add(inetAddress);
            super.addDnsServer(inetAddress);
            return this;
        }

        @Override
        public Builder addRoute(String str, int i2) {
            List list = this.listRoute;
            list.add(str + "/" + i2);
            super.addRoute(str, i2);
            return this;
        }

        @Override
        public Builder addRoute(InetAddress inetAddress, int i2) {
            List list = this.listRoute;
            list.add(inetAddress.getHostAddress() + "/" + i2);
            super.addRoute(inetAddress, i2);
            return this;
        }

        public boolean equals(Object obj) {
            NetworkInfo networkInfo;
            Builder builder = (Builder) obj;
            if (builder != null && Objects.equals(this.activeNetwork, builder.activeNetwork) && (networkInfo = this.networkInfo) != null && builder.networkInfo != null && networkInfo.getType() == builder.networkInfo.getType() && this.mtu == builder.mtu && this.listAddress.size() == builder.listAddress.size() && this.listRoute.size() == builder.listRoute.size() && this.listDns.size() == builder.listDns.size() && this.listAllowed.size() == builder.listAllowed.size() && this.listDisallowed.size() == builder.listDisallowed.size()) {
                for (String str : this.listAddress) {
                    if (!builder.listAddress.contains(str)) {
                        return false;
                    }
                }
                for (String str2 : this.listRoute) {
                    if (!builder.listRoute.contains(str2)) {
                        return false;
                    }
                }
                for (InetAddress inetAddress : this.listDns) {
                    if (!builder.listDns.contains(inetAddress)) {
                        return false;
                    }
                }
                for (String str3 : this.listAllowed) {
                    if (!builder.listAllowed.contains(str3)) {
                        return false;
                    }
                }
                for (String str4 : this.listDisallowed) {
                    if (!builder.listDisallowed.contains(str4)) {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }

        @Override
        public VpnService.Builder setMtu(int i2) {
            this.mtu = i2;
            super.setMtu(i2);
            return this;
        }
    }

    public enum Command {
        run,
        start,
        reload,
        stop,
        stats,
        set,
        householding,
        watchdog
    }

    final class CommandHandler extends Handler {
        public int queue;

        public class StartFailedException extends IllegalStateException {
            public StartFailedException(String str) {
                super(str);
            }
        }

        public CommandHandler(Looper looper) {
            super(looper);
            this.queue = 0;
        }

        private void checkUpdate() {
            HttpsURLConnection httpsURLConnection;
            Throwable th;
            StringBuilder sb = new StringBuilder();
            try {
                httpsURLConnection = (HttpsURLConnection) new URL("https://api.github.com/repos/M66B/NetGuard/releases/latest").openConnection();
                try {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
                    while (true) {
                        String readLine = bufferedReader.readLine();
                        if (readLine == null) {
                            break;
                        }
                        sb.append(readLine);
                    }
                } catch (Throwable th2) {
                    th = th2;
                    try {
                        Log.e("NetGuard.Service", th.toString() + "\n" + Log.getStackTraceString(th));
                    } catch (Throwable th3) {
                        if (httpsURLConnection != null) {
                            httpsURLConnection.disconnect();
                        }
                        throw th3;
                    }
                }
            } catch (Throwable th4) {
                httpsURLConnection = null;
                th = th4;
            }
            httpsURLConnection.disconnect();
            try {
                JSONObject jSONObject = new JSONObject(sb.toString());
                if (jSONObject.has("tag_name") && jSONObject.has("html_url") && jSONObject.has("assets")) {
                    String string = jSONObject.getString("html_url");
                    JSONArray jSONArray = jSONObject.getJSONArray("assets");
                    if (jSONArray.length() > 0) {
                        JSONObject jSONObject2 = jSONArray.getJSONObject(0);
                        if (jSONObject2.has("name")) {
                            String string2 = jSONObject.getString("tag_name");
                            String string3 = jSONObject2.getString("name");
                            Log.i("NetGuard.Service", "Tag " + string2 + " name " + string3 + " url " + string);
                            Version version = new Version(Util.getSelfVersionName(ServiceSinkhole.this));
                            Version version2 = new Version(string2);
                            if (version.compareTo(version2) >= 0) {
                                Log.i("NetGuard.Service", "Up-to-date current version " + version);
                                return;
                            }
                            Log.i("NetGuard.Service", "Update available from " + version + " to " + version2);
                            ServiceSinkhole.this.showUpdateNotification(string3, string);
                        }
                    }
                }
            } catch (JSONException e2) {
                Log.e("NetGuard.Service", e2.toString() + "\n" + Log.getStackTraceString(e2));
            }
        }

        private void handleIntent(Intent intent) {
            int parseInt;
            Command command;
            Command command2;
            boolean isLockdownEnabled;
            final SharedPreferences f = b.f(ServiceSinkhole.this);
            Command command3 = (Command) intent.getSerializableExtra("Command");
            String stringExtra = intent.getStringExtra("Reason");
            StringBuilder sb = new StringBuilder("Executing intent=");
            sb.append(intent);
            sb.append(" command=");
            sb.append(command3);
            sb.append(" reason=");
            sb.append(stringExtra);
            sb.append(" vpn=");
            sb.append(ServiceSinkhole.this.vpn != null);
            sb.append(" user=");
            sb.append(Process.myUid() / 100000);
            Log.i("NetGuard.Service", sb.toString());
            Command command4 = Command.stop;
            if (command3 != command4 && !ServiceSinkhole.this.user_foreground) {
                Log.i("NetGuard.Service", "Command " + command3 + " ignored for background user");
                return;
            }
            if (command3 == command4) {
                ServiceSinkhole.this.temporarilyStopped = intent.getBooleanExtra("Temporary", false);
            } else if (command3 == Command.start) {
                ServiceSinkhole.this.temporarilyStopped = false;
            } else if (command3 == Command.reload && ServiceSinkhole.this.temporarilyStopped) {
                Log.i("NetGuard.Service", "Command " + command3 + " ignored because of temporary stop");
                return;
            }
            if (f.getBoolean("screen_on", true)) {
                if (!ServiceSinkhole.this.registeredInteractiveState) {
                    Log.i("NetGuard.Service", "Starting listening for interactive state changes");
                    ServiceSinkhole serviceSinkhole = ServiceSinkhole.this;
                    serviceSinkhole.last_interactive = Util.isInteractive(serviceSinkhole);
                    IntentFilter intentFilter = new IntentFilter();
                    intentFilter.addAction("android.intent.action.SCREEN_ON");
                    intentFilter.addAction("android.intent.action.SCREEN_OFF");
                    intentFilter.addAction("eu.faircode.netguard.SCREEN_OFF_DELAYED");
                    ServiceSinkhole serviceSinkhole2 = ServiceSinkhole.this;
                    f.e(serviceSinkhole2, serviceSinkhole2.interactiveStateReceiver, intentFilter);
                    ServiceSinkhole.this.registeredInteractiveState = true;
                }
            } else if (ServiceSinkhole.this.registeredInteractiveState) {
                Log.i("NetGuard.Service", "Stopping listening for interactive state changes");
                ServiceSinkhole serviceSinkhole3 = ServiceSinkhole.this;
                serviceSinkhole3.unregisterReceiver(serviceSinkhole3.interactiveStateReceiver);
                ServiceSinkhole.this.registeredInteractiveState = false;
                ServiceSinkhole.this.last_interactive = false;
            }
            TelephonyManager telephonyManager = (TelephonyManager) ServiceSinkhole.this.getSystemService("phone");
            if (f.getBoolean("disable_on_call", false)) {
                if (telephonyManager != null && ServiceSinkhole.this.callStateListener == null && Util.hasPhoneStatePermission(ServiceSinkhole.this)) {
                    Log.i("NetGuard.Service", "Starting listening for call states");
                    PhoneStateListener phoneStateListener = new PhoneStateListener() {
                        @Override
                        public void onCallStateChanged(int i2, String str) {
                            Log.i("NetGuard.Service", "New call state=" + i2);
                            int i3 = 7 << 0;
                            if (f.getBoolean("enabled", false)) {
                                if (i2 == 0) {
                                    ServiceSinkhole.start("call state", ServiceSinkhole.this);
                                } else {
                                    ServiceSinkhole.stop("call state", ServiceSinkhole.this, true);
                                }
                            }
                        }
                    };
                    telephonyManager.listen(phoneStateListener, 32);
                    ServiceSinkhole.this.callStateListener = phoneStateListener;
                }
            } else if (telephonyManager != null && ServiceSinkhole.this.callStateListener != null) {
                Log.i("NetGuard.Service", "Stopping listening for call states");
                telephonyManager.listen(ServiceSinkhole.this.callStateListener, 0);
                ServiceSinkhole.this.callStateListener = null;
            }
            Command command5 = Command.start;
            try {
                if (command3 == command5 || command3 == Command.reload || command3 == command4) {
                    Intent intent2 = new Intent(ServiceSinkhole.this, ServiceSinkhole.class);
                    intent2.setAction("eu.faircode.netguard.WATCHDOG");
                    PendingIntent foregroundService = Build.VERSION.SDK_INT >= 26 ? PendingIntentCompat.getForegroundService(ServiceSinkhole.this, 1, intent2, 134217728) : PendingIntentCompat.getService(ServiceSinkhole.this, 1, intent2, 134217728);
                    AlarmManager alarmManager = (AlarmManager) ServiceSinkhole.this.getSystemService("alarm");
                    alarmManager.cancel(foregroundService);
                    if (command3 != command4 && (parseInt = Integer.parseInt(f.getString("watchdog", "0"))) > 0) {
                        Log.i("NetGuard.Service", "Watchdog " + parseInt + " minutes");
                        command = command5;
                        long j2 = (long) (parseInt * 60 * 1000);
                        alarmManager.setInexactRepeating(1, SystemClock.elapsedRealtime() + j2, j2, foregroundService);
                        switch (AnonymousClass10.$SwitchMap$eu$faircode$netguard$ServiceSinkhole$Command[command3.ordinal()]) {
                            case 1:
                                break;
                            case 2:
                                start();
                                break;
                            case 3:
                                reload(intent.getBooleanExtra("Interactive", false));
                                break;
                            case 4:
                                stop(ServiceSinkhole.this.temporarilyStopped);
                                break;
                            case 5:
                                ServiceSinkhole.this.statsHandler.sendEmptyMessage(2);
                                ServiceSinkhole.this.statsHandler.sendEmptyMessage(1);
                                break;
                            case 6:
                                householding(intent);
                                break;
                            case 7:
                                watchdog(intent);
                                break;
                            default:
                                Log.e("NetGuard.Service", "Unknown command=" + command3);
                                break;
                        }
                        command2 = command;
                        if ((command3 != command2 || command3 == Command.reload) && Build.VERSION.SDK_INT >= 29) {
                            if (f.getBoolean("filter", false)) {
                                isLockdownEnabled = ServiceSinkhole.this.isLockdownEnabled();
                                if (isLockdownEnabled) {
                                    ServiceSinkhole.this.showLockdownNotification();
                                }
                            }
                            ServiceSinkhole.this.removeLockdownNotification();
                        }
                        if (command3 != command2 || command3 == Command.reload || command3 == command4) {
                            Intent intent3 = new Intent("eu.faircode.netguard.ACTION_RULES_CHANGED");
                            intent3.putExtra("Connected", command3 != command4 ? false : ServiceSinkhole.this.last_connected);
                            intent3.putExtra("Metered", command3 != command4 ? false : ServiceSinkhole.this.last_metered);
                            C0496d.b(ServiceSinkhole.this).d(intent3);
                            WidgetMain.updateWidgets(ServiceSinkhole.this);
                        }
                        if (!ServiceSinkhole.this.commandHandler.hasMessages(command2.ordinal()) && !ServiceSinkhole.this.commandHandler.hasMessages(Command.reload.ordinal()) && !f.getBoolean("enabled", false) && !f.getBoolean("show_stats", false)) {
                            ServiceSinkhole.this.stopForeground(true);
                        }
                        System.gc();
                        return;
                    }
                }
                switch (AnonymousClass10.$SwitchMap$eu$faircode$netguard$ServiceSinkhole$Command[command3.ordinal()]) {
                }
                command2 = command;
                if (command3 != command2) {
                }
                if (f.getBoolean("filter", false)) {
                }
                ServiceSinkhole.this.removeLockdownNotification();
                if (command3 != command2) {
                }
                Intent intent32 = new Intent("eu.faircode.netguard.ACTION_RULES_CHANGED");
                intent32.putExtra("Connected", command3 != command4 ? false : ServiceSinkhole.this.last_connected);
                intent32.putExtra("Metered", command3 != command4 ? false : ServiceSinkhole.this.last_metered);
                C0496d.b(ServiceSinkhole.this).d(intent32);
                WidgetMain.updateWidgets(ServiceSinkhole.this);
                if (!ServiceSinkhole.this.commandHandler.hasMessages(command2.ordinal())) {
                    ServiceSinkhole.this.stopForeground(true);
                }
                System.gc();
                return;
            } catch (Throwable th) {
                r.h(th, new StringBuilder(), "\n", th, "NetGuard.Service");
                if (command3 != Command.start && command3 != Command.reload) {
                    ServiceSinkhole.this.showErrorNotification(th.toString());
                    return;
                } else if (VpnService.prepare(ServiceSinkhole.this) != null) {
                    ServiceSinkhole.this.showErrorNotification(th.toString());
                    if (th instanceof StartFailedException) {
                        return;
                    }
                    d.d(f, "enabled", false);
                    WidgetMain.updateWidgets(ServiceSinkhole.this);
                    return;
                } else {
                    Log.w("NetGuard.Service", "VPN prepared connected=" + ServiceSinkhole.this.last_connected);
                    if (!ServiceSinkhole.this.last_connected || (th instanceof StartFailedException) || Util.isPlayStoreInstall(ServiceSinkhole.this)) {
                        return;
                    }
                    ServiceSinkhole.this.showErrorNotification(th.toString());
                    return;
                }
            }
            command = command5;
        }

        private void householding(Intent intent) {
            DatabaseHelper.getInstance(ServiceSinkhole.this).cleanupLog(new Date().getTime() - 259200000);
            DatabaseHelper.getInstance(ServiceSinkhole.this).cleanupDns();
            SharedPreferences f = b.f(ServiceSinkhole.this);
            if (!Util.isPlayStoreInstall(ServiceSinkhole.this) && Util.hasValidFingerprint(ServiceSinkhole.this) && f.getBoolean("update_check", true)) {
                checkUpdate();
            }
        }

        private void reload(boolean z2) {
            boolean z3;
            List rules = Rule.getRules(true, ServiceSinkhole.this);
            boolean z4 = false;
            if (z2) {
                Iterator it = rules.iterator();
                while (true) {
                    if (!it.hasNext()) {
                        z3 = false;
                        break;
                    }
                    Rule rule = (Rule) it.next();
                    boolean z5 = ServiceSinkhole.this.last_metered ? rule.other_blocked : rule.wifi_blocked;
                    boolean z6 = ServiceSinkhole.this.last_metered ? rule.screen_other : rule.screen_wifi;
                    if (z5 && z6) {
                        z3 = true;
                        break;
                    }
                }
                if (!z3) {
                    Log.i("NetGuard.Service", "No changed rules on interactive state change");
                    return;
                }
            }
            SharedPreferences f = b.f(ServiceSinkhole.this);
            State state = ServiceSinkhole.this.state;
            State state2 = State.enforcing;
            if (state != state2) {
                if (ServiceSinkhole.this.state != State.none) {
                    Log.d("NetGuard.Service", "Stop foreground state=" + ServiceSinkhole.this.state.toString());
                    ServiceSinkhole.this.stopForeground(true);
                }
                ServiceSinkhole serviceSinkhole = ServiceSinkhole.this;
                serviceSinkhole.startForeground(1, serviceSinkhole.getEnforcingNotification(-1, -1, -1));
                ServiceSinkhole.this.state = state2;
                Log.d("NetGuard.Service", "Start foreground state=" + ServiceSinkhole.this.state.toString());
            }
            List allowedRules = ServiceSinkhole.this.getAllowedRules(rules);
            Builder builder = ServiceSinkhole.this.getBuilder(allowedRules, rules);
            int i2 = Build.VERSION.SDK_INT;
            if (ServiceSinkhole.this.vpn != null && f.getBoolean("filter", false) && builder.equals(ServiceSinkhole.this.last_builder)) {
                Log.i("NetGuard.Service", "Native restart");
                ServiceSinkhole serviceSinkhole2 = ServiceSinkhole.this;
                serviceSinkhole2.stopNative(serviceSinkhole2.vpn);
            } else {
                ServiceSinkhole.this.last_builder = builder;
                boolean z7 = f.getBoolean("handover", false);
                if (i2 < 30) {
                    z4 = z7;
                }
                Log.i("NetGuard.Service", "VPN restart handover=" + z4);
                if (z4) {
                    ParcelFileDescriptor parcelFileDescriptor = ServiceSinkhole.this.vpn;
                    ServiceSinkhole serviceSinkhole3 = ServiceSinkhole.this;
                    serviceSinkhole3.vpn = serviceSinkhole3.startVPN(builder);
                    if (parcelFileDescriptor != null && ServiceSinkhole.this.vpn == null) {
                        Log.w("NetGuard.Service", "Handover failed");
                        ServiceSinkhole.this.stopNative(parcelFileDescriptor);
                        ServiceSinkhole.this.stopVPN(parcelFileDescriptor);
                        try {
                            Thread.sleep(3000L);
                        } catch (InterruptedException unused) {
                        }
                        ServiceSinkhole serviceSinkhole4 = ServiceSinkhole.this;
                        serviceSinkhole4.vpn = serviceSinkhole4.startVPN(serviceSinkhole4.last_builder);
                        if (ServiceSinkhole.this.vpn == null) {
                            throw new IllegalStateException("Handover failed");
                        }
                        parcelFileDescriptor = null;
                    }
                    if (parcelFileDescriptor != null) {
                        ServiceSinkhole.this.stopNative(parcelFileDescriptor);
                        ServiceSinkhole.this.stopVPN(parcelFileDescriptor);
                    }
                } else {
                    if (ServiceSinkhole.this.vpn != null) {
                        ServiceSinkhole serviceSinkhole5 = ServiceSinkhole.this;
                        serviceSinkhole5.stopNative(serviceSinkhole5.vpn);
                        ServiceSinkhole serviceSinkhole6 = ServiceSinkhole.this;
                        serviceSinkhole6.stopVPN(serviceSinkhole6.vpn);
                    }
                    ServiceSinkhole serviceSinkhole7 = ServiceSinkhole.this;
                    serviceSinkhole7.vpn = serviceSinkhole7.startVPN(builder);
                }
            }
            if (ServiceSinkhole.this.vpn == null) {
                throw new StartFailedException(ServiceSinkhole.this.getString(R.string.msg_start_failed));
            }
            ServiceSinkhole serviceSinkhole8 = ServiceSinkhole.this;
            serviceSinkhole8.startNative(serviceSinkhole8.vpn, allowedRules, rules);
            ServiceSinkhole.this.removeWarningNotifications();
            ServiceSinkhole.this.updateEnforcingNotification(allowedRules.size(), rules.size());
        }

        private void reportQueueSize() {
            Intent intent = new Intent("eu.faircode.netguard.ACTION_QUEUE_CHANGED");
            intent.putExtra("Size", this.queue);
            C0496d.b(ServiceSinkhole.this).d(intent);
        }

        private void start() {
            if (ServiceSinkhole.this.vpn == null) {
                if (ServiceSinkhole.this.state != State.none) {
                    Log.d("NetGuard.Service", "Stop foreground state=" + ServiceSinkhole.this.state.toString());
                    ServiceSinkhole.this.stopForeground(true);
                }
                ServiceSinkhole serviceSinkhole = ServiceSinkhole.this;
                serviceSinkhole.startForeground(1, serviceSinkhole.getEnforcingNotification(-1, -1, -1));
                ServiceSinkhole.this.state = State.enforcing;
                Log.d("NetGuard.Service", "Start foreground state=" + ServiceSinkhole.this.state.toString());
                List rules = Rule.getRules(true, ServiceSinkhole.this);
                List allowedRules = ServiceSinkhole.this.getAllowedRules(rules);
                ServiceSinkhole serviceSinkhole2 = ServiceSinkhole.this;
                serviceSinkhole2.last_builder = serviceSinkhole2.getBuilder(allowedRules, rules);
                ServiceSinkhole serviceSinkhole3 = ServiceSinkhole.this;
                serviceSinkhole3.vpn = serviceSinkhole3.startVPN(serviceSinkhole3.last_builder);
                if (ServiceSinkhole.this.vpn == null) {
                    throw new StartFailedException(ServiceSinkhole.this.getString(R.string.msg_start_failed));
                }
                ServiceSinkhole serviceSinkhole4 = ServiceSinkhole.this;
                serviceSinkhole4.startNative(serviceSinkhole4.vpn, allowedRules, rules);
                ServiceSinkhole.this.removeWarningNotifications();
                ServiceSinkhole.this.updateEnforcingNotification(allowedRules.size(), rules.size());
            }
        }

        private void stop(boolean z2) {
            if (ServiceSinkhole.this.vpn != null) {
                ServiceSinkhole serviceSinkhole = ServiceSinkhole.this;
                serviceSinkhole.stopNative(serviceSinkhole.vpn);
                ServiceSinkhole serviceSinkhole2 = ServiceSinkhole.this;
                serviceSinkhole2.stopVPN(serviceSinkhole2.vpn);
                ServiceSinkhole.this.vpn = null;
                ServiceSinkhole.this.unprepare();
            }
            if (ServiceSinkhole.this.state == State.enforcing && !z2) {
                Log.d("NetGuard.Service", "Stop foreground state=" + ServiceSinkhole.this.state.toString());
                boolean z3 = false | true;
                ServiceSinkhole.this.last_allowed = -1;
                ServiceSinkhole.this.last_blocked = -1;
                ServiceSinkhole.this.last_hosts = -1;
                ServiceSinkhole.this.stopForeground(true);
                boolean z4 = true | false;
                if (b.f(ServiceSinkhole.this).getBoolean("show_stats", false)) {
                    ServiceSinkhole serviceSinkhole3 = ServiceSinkhole.this;
                    serviceSinkhole3.startForeground(2, serviceSinkhole3.getWaitingNotification());
                    ServiceSinkhole.this.state = State.waiting;
                    Log.d("NetGuard.Service", "Start foreground state=" + ServiceSinkhole.this.state.toString());
                } else {
                    ServiceSinkhole.this.state = State.none;
                    ServiceSinkhole.this.stopSelf();
                }
            }
        }

        private void watchdog(Intent intent) {
            if (ServiceSinkhole.this.vpn == null && b.f(ServiceSinkhole.this).getBoolean("enabled", false)) {
                Log.e("NetGuard.Service", "Service was killed");
                start();
            }
        }

        @Override
        public void handleMessage(Message message) {
            String str;
            StringBuilder sb;
            try {
                synchronized (ServiceSinkhole.this) {
                    handleIntent((Intent) message.obj);
                }
                synchronized (this) {
                    try {
                        this.queue--;
                        reportQueueSize();
                    } catch (Throwable th) {
                        throw th;
                    }
                }
                try {
                    PowerManager.WakeLock lock = ServiceSinkhole.getLock(ServiceSinkhole.this);
                    if (lock.isHeld()) {
                        lock.release();
                    } else {
                        Log.w("NetGuard.Service", "Wakelock under-locked");
                    }
                    Log.i("NetGuard.Service", "Messages=" + hasMessages(0) + " wakelock=" + ServiceSinkhole.wlInstance.isHeld());
                } catch (Throwable th2) {
                    th = th2;
                    str = "NetGuard.Service";
                    sb = new StringBuilder();
                    r.h(th, sb, "\n", th, str);
                }
            } catch (Throwable th3) {
                try {
                    Log.e("NetGuard.Service", th3.toString() + "\n" + Log.getStackTraceString(th3));
                    synchronized (this) {
                        try {
                            this.queue--;
                            reportQueueSize();
                            try {
                                PowerManager.WakeLock lock2 = ServiceSinkhole.getLock(ServiceSinkhole.this);
                                if (lock2.isHeld()) {
                                    lock2.release();
                                } else {
                                    Log.w("NetGuard.Service", "Wakelock under-locked");
                                }
                                Log.i("NetGuard.Service", "Messages=" + hasMessages(0) + " wakelock=" + ServiceSinkhole.wlInstance.isHeld());
                            } catch (Throwable th4) {
                                th = th4;
                                str = "NetGuard.Service";
                                sb = new StringBuilder();
                                r.h(th, sb, "\n", th, str);
                            }
                        } catch (Throwable th5) {
                            throw th5;
                        }
                    }
                } catch (Throwable th6) {
                    synchronized (this) {
                        try {
                            this.queue--;
                            reportQueueSize();
                            try {
                                PowerManager.WakeLock lock3 = ServiceSinkhole.getLock(ServiceSinkhole.this);
                                if (lock3.isHeld()) {
                                    lock3.release();
                                } else {
                                    Log.w("NetGuard.Service", "Wakelock under-locked");
                                }
                                Log.i("NetGuard.Service", "Messages=" + hasMessages(0) + " wakelock=" + ServiceSinkhole.wlInstance.isHeld());
                            } catch (Throwable th7) {
                                r.h(th7, new StringBuilder(), "\n", th7, "NetGuard.Service");
                            }
                            throw th6;
                        } catch (Throwable th8) {
                            throw th8;
                        }
                    }
                }
            }
        }

        public void queue(Intent intent) {
            synchronized (this) {
                try {
                    this.queue++;
                    reportQueueSize();
                } catch (Throwable th) {
                    throw th;
                }
            }
            Message obtainMessage = ServiceSinkhole.this.commandHandler.obtainMessage();
            obtainMessage.obj = intent;
            obtainMessage.what = ((Command) intent.getSerializableExtra("Command")).ordinal();
            ServiceSinkhole.this.commandHandler.sendMessage(obtainMessage);
        }
    }

    public class IPKey {
        int dport;
        int protocol;
        int uid;
        int version;

        public IPKey(int i2, int i3, int i4, int i5) {
            this.version = i2;
            this.protocol = i3;
            if (i3 != 6 && i3 != 17) {
                i4 = 0;
            }
            this.dport = i4;
            this.uid = i5;
        }

        public boolean equals(Object obj) {
            if (obj instanceof IPKey) {
                IPKey iPKey = (IPKey) obj;
                if (this.version == iPKey.version && this.protocol == iPKey.protocol && this.dport == iPKey.dport && this.uid == iPKey.uid) {
                    boolean z2 = !true;
                    return true;
                }
                return false;
            }
            return false;
        }

        public int hashCode() {
            return (this.version << 40) | (this.protocol << 32) | (this.dport << 16) | this.uid;
        }

        public String toString() {
            return "v" + this.version + " p" + this.protocol + " port=" + this.dport + " uid=" + this.uid;
        }
    }

    public class IPRule {
        private boolean block;
        private IPKey key;
        private String name;
        private long time;
        private long ttl;

        public IPRule(IPKey iPKey, String str, boolean z2, long j2, long j3) {
            this.key = iPKey;
            this.name = str;
            this.block = z2;
            this.time = j2;
            this.ttl = j3;
        }

        public boolean equals(Object obj) {
            IPRule iPRule = (IPRule) obj;
            return this.block == iPRule.block && this.time == iPRule.time && this.ttl == iPRule.ttl;
        }

        public boolean isBlocked() {
            return this.block;
        }

        public boolean isExpired() {
            return System.currentTimeMillis() > (this.ttl * 2) + this.time;
        }

        public String toString() {
            return this.key + " " + this.name;
        }

        public void updateExpires(long j2, long j3) {
            this.time = j2;
            this.ttl = j3;
        }
    }

    public final class LogHandler extends Handler {
        public int queue;

        public LogHandler(Looper looper) {
            super(looper);
            this.queue = 0;
        }

        private void log(Packet packet, int i2, boolean z2) {
            int i3;
            int i4;
            SharedPreferences f = b.f(ServiceSinkhole.this);
            boolean z3 = f.getBoolean("log", false);
            boolean z4 = f.getBoolean("log_app", false);
            DatabaseHelper databaseHelper = DatabaseHelper.getInstance(ServiceSinkhole.this);
            String qName = databaseHelper.getQName(packet.uid, packet.daddr);
            if (z3) {
                databaseHelper.insertLog(packet, qName, i2, z2);
            }
            if (!z4 || (i3 = packet.uid) < 0) {
                return;
            }
            if (i3 == 0 && (((i4 = packet.protocol) == 6 || i4 == 17) && packet.dport == 53)) {
                return;
            }
            int i5 = packet.protocol;
            if (i5 != 6 && i5 != 17) {
                packet.dport = 0;
            }
            if (databaseHelper.updateAccess(packet, qName, -1)) {
                ServiceSinkhole.this.lock.readLock().lock();
                if (!ServiceSinkhole.this.mapNotify.containsKey(Integer.valueOf(packet.uid)) || ((Boolean) ServiceSinkhole.this.mapNotify.get(Integer.valueOf(packet.uid))).booleanValue()) {
                    ServiceSinkhole.this.showAccessNotification(packet.uid);
                }
                ServiceSinkhole.this.lock.readLock().unlock();
            }
        }

        private void usage(Usage usage) {
            int i2 = usage.Uid;
            if (i2 >= 0 && (i2 != 0 || usage.Protocol != 17 || usage.DPort != 53)) {
                SharedPreferences f = b.f(ServiceSinkhole.this);
                boolean z2 = f.getBoolean("filter", false);
                boolean z3 = f.getBoolean("log_app", false);
                boolean z4 = f.getBoolean("track_usage", false);
                if (z2 && z3 && z4) {
                    DatabaseHelper databaseHelper = DatabaseHelper.getInstance(ServiceSinkhole.this);
                    String qName = databaseHelper.getQName(usage.Uid, usage.DAddr);
                    Log.i("NetGuard.Service", "Usage account " + usage + " dname=" + qName);
                    databaseHelper.updateUsage(usage, qName);
                }
            }
        }

        public void account(Usage usage) {
            Message obtainMessage = obtainMessage();
            obtainMessage.obj = usage;
            obtainMessage.what = 5;
            synchronized (this) {
                try {
                    if (this.queue > 250) {
                        Log.w("NetGuard.Service", "Log queue full");
                        return;
                    }
                    sendMessage(obtainMessage);
                    this.queue++;
                } catch (Throwable th) {
                    throw th;
                }
            }
        }

        @Override
        public void handleMessage(Message message) {
            try {
                int i2 = message.what;
                if (i2 == 4) {
                    log((Packet) message.obj, message.arg1, message.arg2 > 0);
                } else if (i2 != 5) {
                    Log.e("NetGuard.Service", "Unknown log message=" + message.what);
                } else {
                    usage((Usage) message.obj);
                }
                synchronized (this) {
                    this.queue--;
                }
            } catch (Throwable th) {
                r.h(th, new StringBuilder(), "\n", th, "NetGuard.Service");
            }
        }

        public void queue(Packet packet) {
            Message obtainMessage = obtainMessage();
            obtainMessage.obj = packet;
            obtainMessage.what = 4;
            obtainMessage.arg1 = ServiceSinkhole.this.last_connected ? ServiceSinkhole.this.last_metered ? 2 : 1 : 0;
            obtainMessage.arg2 = ServiceSinkhole.this.last_interactive ? 1 : 0;
            synchronized (this) {
                try {
                    if (this.queue > 250) {
                        Log.w("NetGuard.Service", "Log queue full");
                        return;
                    }
                    sendMessage(obtainMessage);
                    this.queue++;
                } catch (Throwable th) {
                    throw th;
                }
            }
        }
    }

    public enum State {
        none,
        waiting,
        enforcing,
        stats
    }

    public final class StatsHandler extends Handler {
        private List grx;
        private List gt;
        private List gtx;
        private HashMap mapUidBytes;
        private long rx;
        private boolean stats;
        private long f3532t;
        private long tx;
        private long when;

        public StatsHandler(Looper looper) {
            super(looper);
            this.stats = false;
            this.f3532t = -1L;
            this.tx = -1L;
            this.rx = -1L;
            this.gt = new ArrayList();
            this.gtx = new ArrayList();
            this.grx = new ArrayList();
            this.mapUidBytes = new HashMap();
        }

        private void startStats() {
            SharedPreferences f = b.f(ServiceSinkhole.this);
            boolean z2 = false;
            if (!this.stats && f.getBoolean("show_stats", false)) {
                z2 = true;
            }
            Log.i("NetGuard.Service", "Stats start enabled=" + z2);
            if (z2) {
                this.when = new Date().getTime();
                this.f3532t = -1L;
                this.tx = -1L;
                this.rx = -1L;
                this.gt.clear();
                this.gtx.clear();
                this.grx.clear();
                this.mapUidBytes.clear();
                this.stats = true;
                updateStats();
            }
        }

        private void stopStats() {
            Log.i("NetGuard.Service", "Stats stop");
            this.stats = false;
            removeMessages(3);
            if (ServiceSinkhole.this.state == State.stats) {
                Log.d("NetGuard.Service", "Stop foreground state=" + ServiceSinkhole.this.state.toString());
                boolean z2 = true | true;
                ServiceSinkhole.this.stopForeground(true);
                ServiceSinkhole.this.state = State.none;
            } else {
                C.c(ServiceSinkhole.this).b(7);
            }
        }

        private void updateStats() {
            boolean z2;
            long j2;
            float f;
            long j3;
            float f2;
            float f3;
            int i2;
            int i3;
            float f4;
            float f5;
            char c2;
            androidx.core.app.r rVar;
            State state;
            State state2;
            RemoteViews remoteViews = new RemoteViews(ServiceSinkhole.this.getPackageName(), (int) R.layout.traffic);
            SharedPreferences f6 = b.f(ServiceSinkhole.this);
            long parseLong = Long.parseLong(f6.getString("stats_frequency", "1000"));
            long parseLong2 = Long.parseLong(f6.getString("stats_samples", "90"));
            boolean z3 = f6.getBoolean("filter", false);
            boolean z4 = f6.getBoolean("show_top", false);
            Integer.parseInt(f6.getString("loglevel", Integer.toString(5)));
            sendEmptyMessageDelayed(3, parseLong);
            long elapsedRealtime = SystemClock.elapsedRealtime();
            while (this.gt.size() > 0 && elapsedRealtime - ((Long) this.gt.get(0)).longValue() > 1000 * parseLong2) {
                this.gt.remove(0);
                this.gtx.remove(0);
                this.grx.remove(0);
            }
            long totalTxBytes = TrafficStats.getTotalTxBytes();
            long totalRxBytes = TrafficStats.getTotalRxBytes();
            if (z3) {
                totalTxBytes -= TrafficStats.getUidTxBytes(Process.myUid());
                totalRxBytes -= TrafficStats.getUidRxBytes(Process.myUid());
                if (totalTxBytes < 0) {
                    totalTxBytes = 0;
                }
                if (totalRxBytes < 0) {
                    z2 = z4;
                    totalRxBytes = 0;
                    j2 = this.f3532t;
                    f = 0.0f;
                    if (j2 > 0) {
                        long j4 = this.tx;
                        if (j4 > 0) {
                            long j5 = this.rx;
                            if (j5 > 0) {
                                j3 = parseLong2;
                                float f7 = ((float) (elapsedRealtime - j2)) / 1000.0f;
                                f2 = ((float) (totalTxBytes - j4)) / f7;
                                f3 = ((float) (totalRxBytes - j5)) / f7;
                                this.gt.add(Long.valueOf(elapsedRealtime));
                                this.gtx.add(Float.valueOf(f2));
                                this.grx.add(Float.valueOf(f3));
                                float f8 = 1000000.0f;
                                if (z2) {
                                    if (this.mapUidBytes.size() == 0) {
                                        for (ApplicationInfo applicationInfo : ServiceSinkhole.this.getPackageManager().getInstalledApplications(0)) {
                                            if (applicationInfo.uid != Process.myUid()) {
                                                this.mapUidBytes.put(Integer.valueOf(applicationInfo.uid), Long.valueOf(TrafficStats.getUidRxBytes(applicationInfo.uid) + TrafficStats.getUidTxBytes(applicationInfo.uid)));
                                            }
                                        }
                                    } else if (this.f3532t > 0) {
                                        TreeMap treeMap = new TreeMap(new Comparator() {
                                            @Override
                                            public int compare(Float f9, Float f10) {
                                                return -f9.compareTo(f10);
                                            }
                                        });
                                        float f9 = ((float) (elapsedRealtime - this.f3532t)) / 1000.0f;
                                        for (Integer num : this.mapUidBytes.keySet()) {
                                            int intValue = num.intValue();
                                            long uidRxBytes = TrafficStats.getUidRxBytes(intValue) + TrafficStats.getUidTxBytes(intValue);
                                            float longValue = ((float) (uidRxBytes - ((Long) this.mapUidBytes.get(Integer.valueOf(intValue))).longValue())) / f9;
                                            if (longValue > 0.0f) {
                                                treeMap.put(Float.valueOf(longValue), Integer.valueOf(intValue));
                                                this.mapUidBytes.put(Integer.valueOf(intValue), Long.valueOf(uidRxBytes));
                                            }
                                        }
                                        StringBuilder sb = new StringBuilder();
                                        int i4 = 0;
                                        for (Float f10 : treeMap.keySet()) {
                                            float floatValue = f10.floatValue();
                                            int i5 = i4 + 1;
                                            if (i4 >= 3) {
                                                break;
                                            }
                                            if (floatValue < f8) {
                                                sb.append(ServiceSinkhole.this.getString(R.string.msg_kbsec, Float.valueOf(floatValue / 1000.0f)));
                                            } else {
                                                sb.append(ServiceSinkhole.this.getString(R.string.msg_mbsec, Float.valueOf((floatValue / 1000.0f) / 1000.0f)));
                                            }
                                            sb.append(' ');
                                            List applicationNames = Util.getApplicationNames(((Integer) treeMap.get(Float.valueOf(floatValue))).intValue(), ServiceSinkhole.this);
                                            sb.append(applicationNames.size() > 0 ? (String) applicationNames.get(0) : "?");
                                            sb.append("\r\n");
                                            i4 = i5;
                                            f8 = 1000000.0f;
                                        }
                                        if (sb.length() > 0) {
                                            sb.setLength(sb.length() - 2);
                                        }
                                        remoteViews.setTextViewText(R.id.tvTop, sb.toString());
                                    }
                                }
                                this.f3532t = elapsedRealtime;
                                this.tx = totalTxBytes;
                                this.rx = totalRxBytes;
                                int dips2pixels = Util.dips2pixels(96, ServiceSinkhole.this);
                                int dips2pixels2 = Util.dips2pixels(480, ServiceSinkhole.this);
                                Bitmap createBitmap = Bitmap.createBitmap(dips2pixels2, dips2pixels, Bitmap.Config.ARGB_8888);
                                Canvas canvas = new Canvas(createBitmap);
                                canvas.drawColor(0);
                                float f11 = 0.0f;
                                long j6 = 0;
                                for (i2 = 0; i2 < this.gt.size(); i2++) {
                                    long longValue2 = ((Long) this.gt.get(i2)).longValue();
                                    float floatValue2 = ((Float) this.gtx.get(i2)).floatValue();
                                    float floatValue3 = ((Float) this.grx.get(i2)).floatValue();
                                    if (longValue2 > j6) {
                                        j6 = longValue2;
                                    }
                                    if (floatValue2 > f) {
                                        f = floatValue2;
                                    }
                                    if (floatValue3 > f) {
                                        f = floatValue3;
                                    }
                                    if (floatValue2 > f11) {
                                        f11 = floatValue2;
                                    }
                                    if (floatValue3 > f11) {
                                        f11 = floatValue3;
                                    }
                                }
                                Path path = new Path();
                                Path path2 = new Path();
                                i3 = 0;
                                while (i3 < this.gtx.size()) {
                                    float f12 = f2;
                                    float f13 = f3;
                                    long j7 = j6;
                                    long j8 = j3;
                                    float longValue3 = dips2pixels2 - ((((float) (dips2pixels2 * (j6 - ((Long) this.gt.get(i3)).longValue()))) / 1000.0f) / ((float) j8));
                                    float f14 = dips2pixels;
                                    float floatValue4 = f14 - ((((Float) this.gtx.get(i3)).floatValue() * f14) / f11);
                                    float floatValue5 = f14 - ((((Float) this.grx.get(i3)).floatValue() * f14) / f11);
                                    if (i3 == 0) {
                                        path.moveTo(longValue3, floatValue4);
                                        path2.moveTo(longValue3, floatValue5);
                                    } else {
                                        path.lineTo(longValue3, floatValue4);
                                        path2.lineTo(longValue3, floatValue5);
                                    }
                                    i3++;
                                    j3 = j8;
                                    f2 = f12;
                                    f3 = f13;
                                    j6 = j7;
                                }
                                f4 = f2;
                                f5 = f3;
                                Paint paint = new Paint(1);
                                paint.setStyle(Paint.Style.STROKE);
                                paint.setStrokeWidth(Util.dips2pixels(1, ServiceSinkhole.this));
                                paint.setColor(f.b(ServiceSinkhole.this, R.color.colorGrayed));
                                float f15 = dips2pixels / 2;
                                canvas.drawLine(0.0f, f15, dips2pixels2, f15, paint);
                                paint.setStrokeWidth(Util.dips2pixels(2, ServiceSinkhole.this));
                                paint.setColor(f.b(ServiceSinkhole.this, R.color.colorSend));
                                canvas.drawPath(path, paint);
                                paint.setColor(f.b(ServiceSinkhole.this, R.color.colorReceive));
                                canvas.drawPath(path2, paint);
                                remoteViews.setImageViewBitmap(R.id.ivTraffic, createBitmap);
                                if (f4 < 1000000.0f) {
                                    c2 = 0;
                                    remoteViews.setTextViewText(R.id.tvTx, ServiceSinkhole.this.getString(R.string.msg_kbsec, Float.valueOf(f4 / 1000.0f)));
                                } else {
                                    c2 = 0;
                                    remoteViews.setTextViewText(R.id.tvTx, ServiceSinkhole.this.getString(R.string.msg_mbsec, Float.valueOf((f4 / 1000.0f) / 1000.0f)));
                                }
                                if (f5 < 1000000.0f) {
                                    ServiceSinkhole serviceSinkhole = ServiceSinkhole.this;
                                    Object[] objArr = new Object[1];
                                    objArr[c2] = Float.valueOf(f5 / 1000.0f);
                                    remoteViews.setTextViewText(R.id.tvRx, serviceSinkhole.getString(R.string.msg_kbsec, objArr));
                                } else {
                                    ServiceSinkhole serviceSinkhole2 = ServiceSinkhole.this;
                                    Object[] objArr2 = new Object[1];
                                    objArr2[c2] = Float.valueOf((f5 / 1000.0f) / 1000.0f);
                                    remoteViews.setTextViewText(R.id.tvRx, serviceSinkhole2.getString(R.string.msg_mbsec, objArr2));
                                }
                                if (f < 1000000.0f) {
                                    remoteViews.setTextViewText(R.id.tvMax, ServiceSinkhole.this.getString(R.string.msg_kbsec, Float.valueOf((f / 2.0f) / 1000.0f)));
                                } else {
                                    remoteViews.setTextViewText(R.id.tvMax, ServiceSinkhole.this.getString(R.string.msg_mbsec, Float.valueOf(((f / 2.0f) / 1000.0f) / 1000.0f)));
                                }
                                remoteViews.setTextViewText(R.id.tvSessions, "");
                                remoteViews.setTextViewText(R.id.tvFiles, "");
                                PendingIntent activity = PendingIntentCompat.getActivity(ServiceSinkhole.this, 0, new Intent(ServiceSinkhole.this, ActivityMain.class), 134217728);
                                TypedValue typedValue = new TypedValue();
                                ServiceSinkhole.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
                                rVar = new androidx.core.app.r(ServiceSinkhole.this, "notify");
                                rVar.p(this.when);
                                rVar.n(R.drawable.ic_equalizer_white_24dp);
                                rVar.f(remoteViews);
                                rVar.g(activity);
                                rVar.e(typedValue.data);
                                rVar.k(true);
                                rVar.c(false);
                                rVar.d();
                                rVar.o(1);
                                state = ServiceSinkhole.this.state;
                                state2 = State.none;
                                if (state == state2 && ServiceSinkhole.this.state != State.waiting) {
                                    if (Util.canNotify(ServiceSinkhole.this)) {
                                        C.c(ServiceSinkhole.this).e(7, rVar.a());
                                        return;
                                    }
                                    return;
                                }
                                if (ServiceSinkhole.this.state != state2) {
                                    Log.d("NetGuard.Service", "Stop foreground state=" + ServiceSinkhole.this.state.toString());
                                    ServiceSinkhole.this.stopForeground(true);
                                }
                                ServiceSinkhole.this.startForeground(7, rVar.a());
                                ServiceSinkhole.this.state = State.stats;
                                Log.d("NetGuard.Service", "Start foreground state=" + ServiceSinkhole.this.state.toString());
                            }
                        }
                    }
                    j3 = parseLong2;
                    f2 = 0.0f;
                    f3 = 0.0f;
                    float f82 = 1000000.0f;
                    if (z2) {
                    }
                    this.f3532t = elapsedRealtime;
                    this.tx = totalTxBytes;
                    this.rx = totalRxBytes;
                    int dips2pixels3 = Util.dips2pixels(96, ServiceSinkhole.this);
                    int dips2pixels22 = Util.dips2pixels(480, ServiceSinkhole.this);
                    Bitmap createBitmap2 = Bitmap.createBitmap(dips2pixels22, dips2pixels3, Bitmap.Config.ARGB_8888);
                    Canvas canvas2 = new Canvas(createBitmap2);
                    canvas2.drawColor(0);
                    float f112 = 0.0f;
                    long j62 = 0;
                    while (i2 < this.gt.size()) {
                    }
                    Path path3 = new Path();
                    Path path22 = new Path();
                    i3 = 0;
                    while (i3 < this.gtx.size()) {
                    }
                    f4 = f2;
                    f5 = f3;
                    Paint paint2 = new Paint(1);
                    paint2.setStyle(Paint.Style.STROKE);
                    paint2.setStrokeWidth(Util.dips2pixels(1, ServiceSinkhole.this));
                    paint2.setColor(f.b(ServiceSinkhole.this, R.color.colorGrayed));
                    float f152 = dips2pixels3 / 2;
                    canvas2.drawLine(0.0f, f152, dips2pixels22, f152, paint2);
                    paint2.setStrokeWidth(Util.dips2pixels(2, ServiceSinkhole.this));
                    paint2.setColor(f.b(ServiceSinkhole.this, R.color.colorSend));
                    canvas2.drawPath(path3, paint2);
                    paint2.setColor(f.b(ServiceSinkhole.this, R.color.colorReceive));
                    canvas2.drawPath(path22, paint2);
                    remoteViews.setImageViewBitmap(R.id.ivTraffic, createBitmap2);
                    if (f4 < 1000000.0f) {
                    }
                    if (f5 < 1000000.0f) {
                    }
                    if (f < 1000000.0f) {
                    }
                    remoteViews.setTextViewText(R.id.tvSessions, "");
                    remoteViews.setTextViewText(R.id.tvFiles, "");
                    PendingIntent activity2 = PendingIntentCompat.getActivity(ServiceSinkhole.this, 0, new Intent(ServiceSinkhole.this, ActivityMain.class), 134217728);
                    TypedValue typedValue2 = new TypedValue();
                    ServiceSinkhole.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue2, true);
                    rVar = new androidx.core.app.r(ServiceSinkhole.this, "notify");
                    rVar.p(this.when);
                    rVar.n(R.drawable.ic_equalizer_white_24dp);
                    rVar.f(remoteViews);
                    rVar.g(activity2);
                    rVar.e(typedValue2.data);
                    rVar.k(true);
                    rVar.c(false);
                    rVar.d();
                    rVar.o(1);
                    state = ServiceSinkhole.this.state;
                    state2 = State.none;
                    if (state == state2) {
                    }
                    if (ServiceSinkhole.this.state != state2) {
                    }
                    ServiceSinkhole.this.startForeground(7, rVar.a());
                    ServiceSinkhole.this.state = State.stats;
                    Log.d("NetGuard.Service", "Start foreground state=" + ServiceSinkhole.this.state.toString());
                }
            }
            z2 = z4;
            j2 = this.f3532t;
            f = 0.0f;
            if (j2 > 0) {
            }
            j3 = parseLong2;
            f2 = 0.0f;
            f3 = 0.0f;
            float f822 = 1000000.0f;
            if (z2) {
            }
            this.f3532t = elapsedRealtime;
            this.tx = totalTxBytes;
            this.rx = totalRxBytes;
            int dips2pixels32 = Util.dips2pixels(96, ServiceSinkhole.this);
            int dips2pixels222 = Util.dips2pixels(480, ServiceSinkhole.this);
            Bitmap createBitmap22 = Bitmap.createBitmap(dips2pixels222, dips2pixels32, Bitmap.Config.ARGB_8888);
            Canvas canvas22 = new Canvas(createBitmap22);
            canvas22.drawColor(0);
            float f1122 = 0.0f;
            long j622 = 0;
            while (i2 < this.gt.size()) {
            }
            Path path32 = new Path();
            Path path222 = new Path();
            i3 = 0;
            while (i3 < this.gtx.size()) {
            }
            f4 = f2;
            f5 = f3;
            Paint paint22 = new Paint(1);
            paint22.setStyle(Paint.Style.STROKE);
            paint22.setStrokeWidth(Util.dips2pixels(1, ServiceSinkhole.this));
            paint22.setColor(f.b(ServiceSinkhole.this, R.color.colorGrayed));
            float f1522 = dips2pixels32 / 2;
            canvas22.drawLine(0.0f, f1522, dips2pixels222, f1522, paint22);
            paint22.setStrokeWidth(Util.dips2pixels(2, ServiceSinkhole.this));
            paint22.setColor(f.b(ServiceSinkhole.this, R.color.colorSend));
            canvas22.drawPath(path32, paint22);
            paint22.setColor(f.b(ServiceSinkhole.this, R.color.colorReceive));
            canvas22.drawPath(path222, paint22);
            remoteViews.setImageViewBitmap(R.id.ivTraffic, createBitmap22);
            if (f4 < 1000000.0f) {
            }
            if (f5 < 1000000.0f) {
            }
            if (f < 1000000.0f) {
            }
            remoteViews.setTextViewText(R.id.tvSessions, "");
            remoteViews.setTextViewText(R.id.tvFiles, "");
            PendingIntent activity22 = PendingIntentCompat.getActivity(ServiceSinkhole.this, 0, new Intent(ServiceSinkhole.this, ActivityMain.class), 134217728);
            TypedValue typedValue22 = new TypedValue();
            ServiceSinkhole.this.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue22, true);
            rVar = new androidx.core.app.r(ServiceSinkhole.this, "notify");
            rVar.p(this.when);
            rVar.n(R.drawable.ic_equalizer_white_24dp);
            rVar.f(remoteViews);
            rVar.g(activity22);
            rVar.e(typedValue22.data);
            rVar.k(true);
            rVar.c(false);
            rVar.d();
            rVar.o(1);
            state = ServiceSinkhole.this.state;
            state2 = State.none;
            if (state == state2) {
            }
            if (ServiceSinkhole.this.state != state2) {
            }
            ServiceSinkhole.this.startForeground(7, rVar.a());
            ServiceSinkhole.this.state = State.stats;
            Log.d("NetGuard.Service", "Start foreground state=" + ServiceSinkhole.this.state.toString());
        }

        @Override
        public void handleMessage(Message message) {
            try {
                int i2 = message.what;
                if (i2 == 1) {
                    startStats();
                } else if (i2 == 2) {
                    stopStats();
                } else if (i2 != 3) {
                    Log.e("NetGuard.Service", "Unknown stats message=" + message.what);
                } else {
                    updateStats();
                }
            } catch (Throwable th) {
                r.h(th, new StringBuilder(), "\n", th, "NetGuard.Service");
            }
        }
    }

    private void accountUsage(Usage usage) {
        this.logHandler.account(usage);
    }

    private void dnsResolved(ResourceRecord resourceRecord) {
        if (DatabaseHelper.getInstance(this).insertDns(resourceRecord)) {
            Log.i("NetGuard.Service", "New IP " + resourceRecord);
            prepareUidIPFilters(resourceRecord.QName);
        }
        if (resourceRecord.uid <= 0 || TextUtils.isEmpty(resourceRecord.AName)) {
            return;
        }
        this.lock.readLock().lock();
        boolean z2 = this.mapMalware.containsKey(resourceRecord.AName) && ((Boolean) this.mapMalware.get(resourceRecord.AName)).booleanValue();
        this.lock.readLock().unlock();
        if (z2) {
            SharedPreferences f = b.f(this);
            if (f.getBoolean("malware." + resourceRecord.uid, false)) {
                return;
            }
            SharedPreferences.Editor edit = f.edit();
            edit.putBoolean("malware." + resourceRecord.uid, true).apply();
            notifyNewApplication(resourceRecord.uid, true);
        }
    }

    public List getAllowedRules(List list) {
        boolean z2;
        boolean z3;
        boolean z4;
        boolean z5;
        ArrayList arrayList;
        ArrayList arrayList2 = new ArrayList();
        SharedPreferences f = b.f(this);
        boolean isWifiActive = Util.isWifiActive(this);
        boolean isMeteredNetwork = Util.isMeteredNetwork(this);
        boolean z6 = f.getBoolean("use_metered", false);
        Set<String> stringSet = f.getStringSet("wifi_homes", new HashSet());
        String wifiSSID = Util.getWifiSSID(this);
        String networkGeneration = Util.getNetworkGeneration(this);
        boolean z7 = f.getBoolean("unmetered_2g", false);
        boolean z8 = f.getBoolean("unmetered_3g", false);
        boolean z9 = f.getBoolean("unmetered_4g", false);
        boolean isRoaming = Util.isRoaming(this);
        boolean z10 = f.getBoolean("national_roaming", false);
        boolean z11 = f.getBoolean("eu_roaming", false);
        ArrayList arrayList3 = arrayList2;
        boolean z12 = f.getBoolean("tethering", false);
        boolean z13 = f.getBoolean("filter", false);
        this.last_connected = Util.isConnected(this);
        if (Build.VERSION.SDK_INT >= 27) {
            stringSet.clear();
        }
        boolean z14 = (!isWifiActive || z6) ? isMeteredNetwork : false;
        if (!isWifiActive || stringSet.size() <= 0 || stringSet.contains(wifiSSID)) {
            z2 = z13;
            z3 = z14;
        } else {
            z3 = z14;
            z2 = z13;
            if (!stringSet.contains("\"" + wifiSSID + '\"')) {
                Log.i("NetGuard.Service", "!@home=" + wifiSSID + " homes=" + TextUtils.join(",", stringSet));
                z4 = true;
                if (z7 && "2G".equals(networkGeneration)) {
                    z4 = false;
                }
                if (z8 && "3G".equals(networkGeneration)) {
                    z4 = false;
                }
                if (z9 && "4G".equals(networkGeneration)) {
                    z4 = false;
                }
                this.last_metered = z4;
                boolean isLockedDown = isLockedDown(z4);
                z5 = (isRoaming || !z11) ? isRoaming : !Util.isEU(this);
                if (z5 && z10) {
                    z5 = !Util.isNational(this);
                }
                Log.i("NetGuard.Service", "Get allowed connected=" + this.last_connected + " wifi=" + isWifiActive + " home=" + TextUtils.join(",", stringSet) + " network=" + wifiSSID + " metered=" + z4 + "/" + isMeteredNetwork + " generation=" + networkGeneration + " roaming=" + z5 + "/" + isRoaming + " interactive=" + this.last_interactive + " tethering=" + z12 + " filter=" + z2 + " lockdown=" + isLockedDown);
                if (this.last_connected) {
                    Iterator it = list.iterator();
                    while (it.hasNext()) {
                        Rule rule = (Rule) it.next();
                        boolean z15 = z4 ? rule.other_blocked : rule.wifi_blocked;
                        boolean z16 = z4 ? rule.screen_other : rule.screen_wifi;
                        if ((!z15 || (z16 && this.last_interactive)) && (!(z4 && rule.roaming && z5) && (!isLockedDown || rule.lockdown))) {
                            arrayList = arrayList3;
                            arrayList.add(rule);
                        } else {
                            arrayList = arrayList3;
                        }
                        arrayList3 = arrayList;
                    }
                }
                ArrayList arrayList4 = arrayList3;
                Log.i("NetGuard.Service", "Allowed " + arrayList4.size() + " of " + list.size());
                return arrayList4;
            }
        }
        z4 = z3;
        if (z7) {
            z4 = false;
        }
        if (z8) {
            z4 = false;
        }
        if (z9) {
            z4 = false;
        }
        this.last_metered = z4;
        boolean isLockedDown2 = isLockedDown(z4);
        if (isRoaming) {
        }
        if (z5) {
            z5 = !Util.isNational(this);
        }
        Log.i("NetGuard.Service", "Get allowed connected=" + this.last_connected + " wifi=" + isWifiActive + " home=" + TextUtils.join(",", stringSet) + " network=" + wifiSSID + " metered=" + z4 + "/" + isMeteredNetwork + " generation=" + networkGeneration + " roaming=" + z5 + "/" + isRoaming + " interactive=" + this.last_interactive + " tethering=" + z12 + " filter=" + z2 + " lockdown=" + isLockedDown2);
        if (this.last_connected) {
        }
        ArrayList arrayList42 = arrayList3;
        Log.i("NetGuard.Service", "Allowed " + arrayList42.size() + " of " + list.size());
        return arrayList42;
    }

    public Builder getBuilder(List list, List list2) {
        int i2;
        int i3;
        int i4;
        InetAddress[] allByName;
        SharedPreferences f = b.f(this);
        boolean z2 = f.getBoolean("subnet", false);
        boolean z3 = f.getBoolean("tethering", false);
        boolean z4 = f.getBoolean("lan", false);
        boolean z5 = f.getBoolean("ip6", true);
        boolean z6 = f.getBoolean("filter", false);
        boolean z7 = f.getBoolean("manage_system", false);
        String str = null;
        Builder builder = new Builder();
        builder.setSession(getString(R.string.app_name));
        if (Build.VERSION.SDK_INT >= 29) {
            builder.setMetered(Util.isMeteredNetwork(this));
        }
        String string = f.getString("vpn4", "10.1.10.1");
        Log.i("NetGuard.Service", "Using VPN4=" + string);
        builder.addAddress(string, 32);
        if (z5) {
            String string2 = f.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1");
            Log.i("NetGuard.Service", "Using VPN6=" + string2);
            builder.addAddress(string2, 128);
        }
        if (z6) {
            for (InetAddress inetAddress : getDns(this)) {
                if (z5 || (inetAddress instanceof Inet4Address)) {
                    Log.i("NetGuard.Service", "Using DNS=" + inetAddress);
                    builder.addDnsServer(inetAddress);
                }
            }
        }
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService("connectivity");
                Network activeNetwork = connectivityManager == null ? null : connectivityManager.getActiveNetwork();
                LinkProperties linkProperties = activeNetwork == null ? null : connectivityManager.getLinkProperties(activeNetwork);
                if (linkProperties != null) {
                    str = linkProperties.getDomains();
                }
                if (str != null) {
                    Log.i("NetGuard.Service", "Using search domain=" + str);
                    builder.addSearchDomain(str);
                }
            } catch (Throwable th) {
                r.h(th, new StringBuilder(), "\n", th, "NetGuard.Service");
            }
        }
        if (z2) {
            ArrayList arrayList = new ArrayList();
            arrayList.add(new IPUtil.CIDR("127.0.0.0", 8));
            if (z3 && !z4) {
                arrayList.add(new IPUtil.CIDR("192.168.42.0", 23));
                arrayList.add(new IPUtil.CIDR("192.168.44.0", 24));
                arrayList.add(new IPUtil.CIDR("192.168.49.0", 24));
            }
            if (z4) {
                arrayList.add(new IPUtil.CIDR("10.0.0.0", 8));
                arrayList.add(new IPUtil.CIDR("172.16.0.0", 12));
                arrayList.add(new IPUtil.CIDR("192.168.0.0", 16));
            }
            if (!z6) {
                for (InetAddress inetAddress2 : getDns(this)) {
                    if (inetAddress2 instanceof Inet4Address) {
                        arrayList.add(new IPUtil.CIDR(inetAddress2.getHostAddress(), 32));
                    }
                }
                String privateDnsSpecifier = Util.getPrivateDnsSpecifier(this);
                if (!TextUtils.isEmpty(privateDnsSpecifier)) {
                    try {
                        Log.i("NetGuard.Service", "Resolving private dns=" + privateDnsSpecifier);
                        for (InetAddress inetAddress3 : InetAddress.getAllByName(privateDnsSpecifier)) {
                            if (inetAddress3 instanceof Inet4Address) {
                                arrayList.add(new IPUtil.CIDR(inetAddress3.getHostAddress(), 32));
                            }
                        }
                    } catch (Throwable th2) {
                        Log.e("NetGuard.Service", th2.toString());
                    }
                }
            }
            Configuration configuration = getResources().getConfiguration();
            if (configuration.mcc == 310 && ((i4 = configuration.mnc) == 160 || i4 == 200 || i4 == 210 || i4 == 220 || i4 == 230 || i4 == 240 || i4 == 250 || i4 == 260 || i4 == 270 || i4 == 310 || i4 == 490 || i4 == 660 || i4 == 800)) {
                arrayList.add(new IPUtil.CIDR("66.94.2.0", 24));
                arrayList.add(new IPUtil.CIDR("66.94.6.0", 23));
                arrayList.add(new IPUtil.CIDR("66.94.8.0", 22));
                arrayList.add(new IPUtil.CIDR("208.54.0.0", 16));
            }
            int i5 = configuration.mcc;
            if ((i5 == 310 && ((i3 = configuration.mnc) == 4 || i3 == 5 || i3 == 6 || i3 == 10 || i3 == 12 || i3 == 13 || i3 == 350 || i3 == 590 || i3 == 820 || i3 == 890 || i3 == 910)) || ((i5 == 311 && ((i2 = configuration.mnc) == 12 || i2 == 110 || ((i2 >= 270 && i2 <= 289) || i2 == 390 || ((i2 >= 480 && i2 <= 489) || i2 == 590)))) || (i5 == 312 && configuration.mnc == 770))) {
                arrayList.add(new IPUtil.CIDR("66.174.0.0", 16));
                arrayList.add(new IPUtil.CIDR("66.82.0.0", 15));
                arrayList.add(new IPUtil.CIDR("69.96.0.0", 13));
                arrayList.add(new IPUtil.CIDR("70.192.0.0", 11));
                arrayList.add(new IPUtil.CIDR("97.128.0.0", 9));
                arrayList.add(new IPUtil.CIDR("174.192.0.0", 9));
                arrayList.add(new IPUtil.CIDR("72.96.0.0", 9));
                arrayList.add(new IPUtil.CIDR("75.192.0.0", 9));
                arrayList.add(new IPUtil.CIDR("97.0.0.0", 10));
            }
            if (configuration.mnc == 10 && configuration.mcc == 208) {
                arrayList.add(new IPUtil.CIDR("10.151.0.0", 24));
            }
            arrayList.add(new IPUtil.CIDR("224.0.0.0", 3));
            Collections.sort(arrayList);
            try {
                InetAddress byName = InetAddress.getByName("0.0.0.0");
                Iterator it = arrayList.iterator();
                while (it.hasNext()) {
                    IPUtil.CIDR cidr = (IPUtil.CIDR) it.next();
                    Log.i("NetGuard.Service", "Exclude " + cidr.getStart().getHostAddress() + "..." + cidr.getEnd().getHostAddress());
                    for (IPUtil.CIDR cidr2 : IPUtil.toCIDR(byName, IPUtil.minus1(cidr.getStart()))) {
                        builder.addRoute(cidr2.address, cidr2.prefix);
                    }
                    byName = IPUtil.plus1(cidr.getEnd());
                }
                for (IPUtil.CIDR cidr3 : IPUtil.toCIDR("224.0.0.0", z4 ? "255.255.255.254" : "255.255.255.255")) {
                    builder.addRoute(cidr3.address, cidr3.prefix);
                }
            } catch (UnknownHostException e2) {
                Log.e("NetGuard.Service", e2.toString() + "\n" + Log.getStackTraceString(e2));
            }
        } else {
            builder.addRoute("0.0.0.0", 0);
        }
        Log.i("NetGuard.Service", "IPv6=" + z5);
        if (z5) {
            builder.addRoute("2000::", 3);
        }
        int jni_get_mtu = jni_get_mtu();
        Log.i("NetGuard.Service", "MTU=" + jni_get_mtu);
        builder.setMtu(jni_get_mtu);
        if (this.last_connected && !z6) {
            HashMap hashMap = new HashMap();
            Iterator it2 = list2.iterator();
            while (it2.hasNext()) {
                Rule rule = (Rule) it2.next();
                hashMap.put(rule.packageName, rule);
            }
            Iterator it3 = list.iterator();
            while (it3.hasNext()) {
                hashMap.remove(((Rule) it3.next()).packageName);
            }
            for (String str2 : hashMap.keySet()) {
                try {
                    builder.addAllowedApplication(str2);
                    Log.i("NetGuard.Service", "Sinkhole " + str2);
                } catch (PackageManager.NameNotFoundException e3) {
                    Log.e("NetGuard.Service", e3.toString() + "\n" + Log.getStackTraceString(e3));
                }
            }
            if (hashMap.size() == 0) {
                try {
                    builder.addAllowedApplication(getPackageName());
                } catch (PackageManager.NameNotFoundException e4) {
                    Log.e("NetGuard.Service", e4.toString() + "\n" + Log.getStackTraceString(e4));
                }
            }
        } else if (z6) {
            try {
                builder.addDisallowedApplication(getPackageName());
            } catch (PackageManager.NameNotFoundException e5) {
                Log.e("NetGuard.Service", e5.toString() + "\n" + Log.getStackTraceString(e5));
            }
            Iterator it4 = list2.iterator();
            while (it4.hasNext()) {
                Rule rule2 = (Rule) it4.next();
                if (!rule2.apply || (!z7 && rule2.system)) {
                    try {
                        Log.i("NetGuard.Service", "Not routing " + rule2.packageName);
                        builder.addDisallowedApplication(rule2.packageName);
                    } catch (PackageManager.NameNotFoundException e6) {
                        Log.e("NetGuard.Service", e6.toString() + "\n" + Log.getStackTraceString(e6));
                    }
                }
            }
        }
        builder.setConfigureIntent(PendingIntentCompat.getActivity(this, 0, new Intent(this, ActivityMain.class), 134217728));
        return builder;
    }

    public static List getDns(Context context) {
        ArrayList arrayList = new ArrayList();
        List<String> defaultDNS = Util.getDefaultDNS(context);
        SharedPreferences f = b.f(context);
        boolean z2 = f.getBoolean("ip6", true);
        boolean z3 = f.getBoolean("filter", false);
        String string = f.getString("dns", null);
        String string2 = f.getString("dns2", null);
        Log.i("NetGuard.Service", "DNS system=" + TextUtils.join(",", defaultDNS) + " config=" + string + "," + string2);
        if (string != null) {
            try {
                InetAddress byName = InetAddress.getByName(string);
                if (!byName.isLoopbackAddress() && !byName.isAnyLocalAddress() && (z2 || (byName instanceof Inet4Address))) {
                    arrayList.add(byName);
                }
            } catch (Throwable unused) {
            }
        }
        if (string2 != null) {
            try {
                InetAddress byName2 = InetAddress.getByName(string2);
                if (!byName2.isLoopbackAddress() && !byName2.isAnyLocalAddress() && (z2 || (byName2 instanceof Inet4Address))) {
                    arrayList.add(byName2);
                }
            } catch (Throwable th) {
                r.h(th, new StringBuilder(), "\n", th, "NetGuard.Service");
            }
        }
        if (arrayList.size() == 2) {
            return arrayList;
        }
        for (String str : defaultDNS) {
            try {
                InetAddress byName3 = InetAddress.getByName(str);
                if (!arrayList.contains(byName3) && !byName3.isLoopbackAddress() && !byName3.isAnyLocalAddress() && (z2 || (byName3 instanceof Inet4Address))) {
                    arrayList.add(byName3);
                }
            } catch (Throwable th2) {
                r.h(th2, new StringBuilder(), "\n", th2, "NetGuard.Service");
            }
        }
        int size = arrayList.size();
        boolean z4 = f.getBoolean("lan", false);
        boolean z5 = f.getBoolean("use_hosts", false);
        if (z4 && z5 && z3) {
            try {
                ArrayList arrayList2 = new ArrayList();
                arrayList2.add(new Pair(InetAddress.getByName("10.0.0.0"), 8));
                arrayList2.add(new Pair(InetAddress.getByName("172.16.0.0"), 12));
                arrayList2.add(new Pair(InetAddress.getByName("192.168.0.0"), 16));
                Iterator it = arrayList2.iterator();
                while (it.hasNext()) {
                    Pair pair = (Pair) it.next();
                    InetAddress inetAddress = (InetAddress) pair.first;
                    BigInteger bigInteger = new BigInteger(1, inetAddress.getAddress());
                    int intValue = ((Integer) pair.second).intValue();
                    BigInteger shiftLeft = BigInteger.valueOf(-1L).shiftLeft((inetAddress.getAddress().length * 8) - intValue);
                    Iterator it2 = new ArrayList(arrayList).iterator();
                    while (it2.hasNext()) {
                        InetAddress inetAddress2 = (InetAddress) it2.next();
                        if (inetAddress.getAddress().length == inetAddress2.getAddress().length) {
                            if (bigInteger.and(shiftLeft).equals(new BigInteger(1, inetAddress2.getAddress()).and(shiftLeft))) {
                                Log.i("NetGuard.Service", "Local DNS server host=" + inetAddress + "/" + intValue + " dns=" + inetAddress2);
                                arrayList.remove(inetAddress2);
                            }
                        }
                    }
                }
            } catch (Throwable th3) {
                r.h(th3, new StringBuilder(), "\n", th3, "NetGuard.Service");
            }
        }
        if (arrayList.size() == 0 || arrayList.size() < size) {
            try {
                arrayList.add(InetAddress.getByName("8.8.8.8"));
                arrayList.add(InetAddress.getByName("8.8.4.4"));
                if (z2) {
                    arrayList.add(InetAddress.getByName("2001:4860:4860::8888"));
                    arrayList.add(InetAddress.getByName("2001:4860:4860::8844"));
                }
            } catch (Throwable th4) {
                r.h(th4, new StringBuilder(), "\n", th4, "NetGuard.Service");
            }
        }
        Log.i("NetGuard.Service", "Get DNS=" + TextUtils.join(",", arrayList));
        return arrayList;
    }

    public Notification getEnforcingNotification(int i2, int i3, int i4) {
        PendingIntent activity = PendingIntentCompat.getActivity(this, 0, new Intent(this, ActivityMain.class), 134217728);
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
        androidx.core.app.r rVar = new androidx.core.app.r(this, "foreground");
        rVar.n(isLockedDown(this.last_metered) ? R.drawable.ic_lock_outline_white_24dp : R.drawable.ic_security_white_24dp);
        rVar.g(activity);
        rVar.e(typedValue.data);
        rVar.k(true);
        rVar.c(false);
        int i5 = Build.VERSION.SDK_INT;
        if (i5 >= 24) {
            rVar.i(getString(R.string.msg_started));
        } else {
            rVar.i(getString(R.string.app_name));
            rVar.h(getString(R.string.msg_started));
        }
        rVar.d();
        rVar.o(-1);
        rVar.l(-2);
        if (i2 >= 0) {
            this.last_allowed = i2;
        } else {
            i2 = this.last_allowed;
        }
        if (i3 >= 0) {
            this.last_blocked = i3;
        } else {
            i3 = this.last_blocked;
        }
        if (i4 >= 0) {
            this.last_hosts = i4;
        } else {
            i4 = this.last_hosts;
        }
        if (i2 >= 0 || i3 >= 0 || i4 >= 0) {
            if (i5 >= 24) {
                if (Util.isPlayStoreInstall(this)) {
                    rVar.h(getString(R.string.msg_packages, Integer.valueOf(i2), Integer.valueOf(i3)));
                } else {
                    rVar.h(getString(R.string.msg_hosts, Integer.valueOf(i2), Integer.valueOf(i3), Integer.valueOf(i4)));
                }
                return rVar.a();
            }
            q qVar = new q(rVar);
            qVar.f(getString(R.string.msg_started));
            if (Util.isPlayStoreInstall(this)) {
                qVar.g(getString(R.string.msg_packages, Integer.valueOf(i2), Integer.valueOf(i3)));
            } else {
                qVar.g(getString(R.string.msg_hosts, Integer.valueOf(i2), Integer.valueOf(i3), Integer.valueOf(i4)));
            }
            return qVar.c();
        }
        return rVar.a();
    }

    public static synchronized PowerManager.WakeLock getLock(Context context) {
        PowerManager.WakeLock wakeLock;
        synchronized (ServiceSinkhole.class) {
            try {
                if (wlInstance == null) {
                    wlInstance = ((PowerManager) context.getSystemService("power")).newWakeLock(1, context.getString(R.string.app_name) + " wakelock");
                    wlInstance.setReferenceCounted(true);
                }
                wakeLock = wlInstance;
            } catch (Throwable th) {
                throw th;
            }
        }
        return wakeLock;
    }

    private int getUidQ(int i2, int i3, String str, int i4, String str2, int i5) {
        ConnectivityManager connectivityManager;
        int connectionOwnerUid;
        if ((i3 == 6 || i3 == 17) && (connectivityManager = (ConnectivityManager) getSystemService("connectivity")) != null) {
            InetSocketAddress inetSocketAddress = new InetSocketAddress(str, i4);
            InetSocketAddress inetSocketAddress2 = new InetSocketAddress(str2, i5);
            Log.i("NetGuard.Service", "Get uid local=" + inetSocketAddress + " remote=" + inetSocketAddress2);
            connectionOwnerUid = connectivityManager.getConnectionOwnerUid(i3, inetSocketAddress, inetSocketAddress2);
            StringBuilder sb = new StringBuilder("Get uid=");
            sb.append(connectionOwnerUid);
            Log.i("NetGuard.Service", sb.toString());
            return connectionOwnerUid;
        }
        return -1;
    }

    public Notification getWaitingNotification() {
        PendingIntent activity = PendingIntentCompat.getActivity(this, 0, new Intent(this, ActivityMain.class), 134217728);
        TypedValue typedValue = new TypedValue();
        boolean z2 = true & true;
        getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
        androidx.core.app.r rVar = new androidx.core.app.r(this, "foreground");
        rVar.n(R.drawable.ic_security_white_24dp);
        rVar.g(activity);
        rVar.e(typedValue.data);
        rVar.k(true);
        rVar.c(false);
        if (Build.VERSION.SDK_INT >= 24) {
            rVar.i(getString(R.string.msg_waiting));
        } else {
            rVar.i(getString(R.string.app_name));
            rVar.h(getString(R.string.msg_waiting));
        }
        rVar.d();
        rVar.o(-1);
        rVar.l(-2);
        return rVar.a();
    }

    private Allowed isAddressAllowed(Packet packet) {
        Allowed allowed;
        InetAddress byName;
        Map map;
        SharedPreferences f = b.f(this);
        this.lock.readLock().lock();
        packet.allowed = false;
        if (f.getBoolean("filter", false)) {
            boolean z2 = true;
            if (packet.protocol != 17 || f.getBoolean("filter_udp", false)) {
                if (packet.uid < 2000 && !this.last_connected) {
                    isSupported(packet.protocol);
                }
                int i2 = packet.uid;
                if (i2 < 2000 && !this.mapUidKnown.containsKey(Integer.valueOf(i2)) && isSupported(packet.protocol)) {
                    packet.allowed = true;
                    Log.w("NetGuard.Service", "Allowing unknown system " + packet);
                } else if (packet.uid == Process.myUid()) {
                    packet.allowed = true;
                    Log.w("NetGuard.Service", "Allowing self " + packet);
                } else {
                    IPKey iPKey = new IPKey(packet.version, packet.protocol, packet.dport, packet.uid);
                    if (this.mapUidIPFilters.containsKey(iPKey)) {
                        try {
                            byName = InetAddress.getByName(packet.daddr);
                            map = (Map) this.mapUidIPFilters.get(iPKey);
                        } catch (UnknownHostException e2) {
                            e = e2;
                            z2 = false;
                        }
                        if (map != null && map.containsKey(byName)) {
                            IPRule iPRule = (IPRule) map.get(byName);
                            if (iPRule.isExpired()) {
                                Log.i("NetGuard.Service", "DNS expired " + packet + " rule " + iPRule);
                            } else {
                                try {
                                    packet.allowed = !iPRule.isBlocked();
                                    Log.i("NetGuard.Service", "Filtering " + packet + " allowed=" + packet.allowed + " rule " + iPRule);
                                } catch (UnknownHostException e3) {
                                    e = e3;
                                    Log.w("NetGuard.Service", "Allowed " + e.toString() + "\n" + Log.getStackTraceString(e));
                                    if (!z2) {
                                    }
                                    if (packet.allowed) {
                                    }
                                    this.lock.readLock().unlock();
                                    if (!f.getBoolean("log", false)) {
                                    }
                                    logPacket(packet);
                                    return allowed;
                                }
                                if (!z2) {
                                    if (this.mapUidAllowed.containsKey(Integer.valueOf(packet.uid))) {
                                        packet.allowed = ((Boolean) this.mapUidAllowed.get(Integer.valueOf(packet.uid))).booleanValue();
                                    } else {
                                        Log.w("NetGuard.Service", "No rules for " + packet);
                                    }
                                }
                            }
                        }
                    }
                    z2 = false;
                    if (!z2) {
                    }
                }
            } else {
                packet.allowed = true;
                Log.i("NetGuard.Service", "Allowing UDP " + packet);
            }
        }
        if (packet.allowed) {
            allowed = null;
        } else if (this.mapForward.containsKey(Integer.valueOf(packet.dport))) {
            Forward forward = (Forward) this.mapForward.get(Integer.valueOf(packet.dport));
            if (forward.ruid == packet.uid) {
                allowed = new Allowed();
            } else {
                Allowed allowed2 = new Allowed(forward.raddr, forward.rport);
                packet.data = "> " + forward.raddr + "/" + forward.rport;
                allowed = allowed2;
            }
        } else {
            allowed = new Allowed();
        }
        this.lock.readLock().unlock();
        if ((!f.getBoolean("log", false) || f.getBoolean("log_app", false)) && ((packet.protocol != 6 || !"".equals(packet.flags)) && packet.uid != Process.myUid())) {
            logPacket(packet);
        }
        return allowed;
    }

    private boolean isDomainBlocked(String str) {
        this.lock.readLock().lock();
        boolean z2 = this.mapHostsBlocked.containsKey(str) && ((Boolean) this.mapHostsBlocked.get(str)).booleanValue();
        this.lock.readLock().unlock();
        return z2;
    }

    private boolean isLockedDown(boolean z2) {
        SharedPreferences f = b.f(this);
        boolean z3 = false;
        boolean z4 = f.getBoolean("lockdown", false);
        boolean z5 = f.getBoolean("lockdown_wifi", true);
        boolean z6 = f.getBoolean("lockdown_other", true);
        if (z2) {
            if (!z6) {
            }
            z3 = z4;
        } else {
            if (!z5) {
            }
            z3 = z4;
        }
        return z3;
    }

    private boolean isSupported(int i2) {
        boolean z2 = true;
        if (i2 != 1 && i2 != 58 && i2 != 6 && i2 != 17) {
            z2 = false;
        }
        return z2;
    }

    private native void jni_clear(long j2);

    private native void jni_done(long j2);

    private native int jni_get_mtu();

    private native long jni_init(int i2);

    private static native void jni_pcap(String str, int i2, int i3);

    public native void jni_run(long j2, int i2, boolean z2, int i3);

    private native void jni_socks5(String str, int i2, String str2, String str3);

    private native void jni_start(long j2, int i2);

    private native void jni_stop(long j2);

    private void listenConnectivityChanges() {
        Log.i("NetGuard.Service", "Starting listening to connectivity changes");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        f.e(this, this.connectivityChangedReceiver, intentFilter);
        this.registeredConnectivityChanged = true;
        Log.i("NetGuard.Service", "Starting listening to service state changes");
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService("phone");
        if (telephonyManager != null) {
            telephonyManager.listen(this.phoneStateListener, 64);
            this.phone_state = true;
        }
    }

    private void listenNetworkChanges() {
        Log.i("NetGuard.Service", "Starting listening to network changes");
        NetworkRequest.Builder builder = new NetworkRequest.Builder();
        builder.addCapability(12);
        builder.addCapability(16);
        ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
            private Boolean last_connected = null;
            private Boolean last_metered = null;
            private String last_generation = null;
            private List last_dns = null;

            @Override
            public void onAvailable(Network network) {
                Log.i("NetGuard.Service", "Available network=" + network);
                this.last_connected = Boolean.valueOf(Util.isConnected(ServiceSinkhole.this));
                this.last_metered = Boolean.valueOf(Util.isMeteredNetwork(ServiceSinkhole.this));
                ServiceSinkhole.reload("network available", ServiceSinkhole.this, false);
            }

            @Override
            public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
                String str;
                Boolean bool;
                Log.i("NetGuard.Service", "Changed capabilities=" + network + " caps=" + networkCapabilities);
                boolean isConnected = Util.isConnected(ServiceSinkhole.this);
                boolean isMeteredNetwork = Util.isMeteredNetwork(ServiceSinkhole.this);
                String networkGeneration = Util.getNetworkGeneration(ServiceSinkhole.this);
                Log.i("NetGuard.Service", "Connected=" + isConnected + "/" + this.last_connected + " unmetered=" + isMeteredNetwork + "/" + this.last_metered + " generation=" + networkGeneration + "/" + this.last_generation);
                Boolean bool2 = this.last_connected;
                String str2 = (bool2 == null || bool2.equals(Boolean.valueOf(isConnected))) ? null : "Connected state changed";
                if (str2 == null && (bool = this.last_metered) != null && !bool.equals(Boolean.valueOf(isMeteredNetwork))) {
                    str2 = "Unmetered state changed";
                }
                if (str2 == null && (str = this.last_generation) != null && !str.equals(networkGeneration)) {
                    SharedPreferences f = b.f(ServiceSinkhole.this);
                    if (f.getBoolean("unmetered_2g", false) || f.getBoolean("unmetered_3g", false) || f.getBoolean("unmetered_4g", false)) {
                        str2 = "Generation changed";
                    }
                }
                if (str2 != null) {
                    ServiceSinkhole.reload(str2, ServiceSinkhole.this, false);
                }
                this.last_connected = Boolean.valueOf(isConnected);
                this.last_metered = Boolean.valueOf(isMeteredNetwork);
                this.last_generation = networkGeneration;
            }

            @Override
            public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {
                String join;
                Log.i("NetGuard.Service", "Changed properties=" + network + " props=" + linkProperties);
                List<InetAddress> dnsServers = linkProperties.getDnsServers();
                SharedPreferences f = b.f(ServiceSinkhole.this);
                if (Build.VERSION.SDK_INT >= 26) {
                    if (same(this.last_dns, dnsServers)) {
                        return;
                    }
                } else if (!f.getBoolean("reload_onconnectivity", false)) {
                    return;
                }
                StringBuilder sb = new StringBuilder("Changed link properties=");
                sb.append(linkProperties);
                sb.append("DNS cur=");
                sb.append(TextUtils.join(",", dnsServers));
                sb.append("DNS prv=");
                List list = this.last_dns;
                if (list == null) {
                    join = null;
                    boolean z2 = true & false;
                } else {
                    join = TextUtils.join(",", list);
                }
                sb.append(join);
                Log.i("NetGuard.Service", sb.toString());
                this.last_dns = dnsServers;
                ServiceSinkhole.reload("link properties changed", ServiceSinkhole.this, false);
            }

            @Override
            public void onLost(Network network) {
                Log.i("NetGuard.Service", "Lost network=" + network);
                this.last_connected = Boolean.valueOf(Util.isConnected(ServiceSinkhole.this));
                ServiceSinkhole.reload("network lost", ServiceSinkhole.this, false);
            }

            boolean same(List list, List list2) {
                if (list == null || list2 == null) {
                    return false;
                }
                if (list.size() != list2.size()) {
                    return false;
                }
                for (int i2 = 0; i2 < list2.size(); i2++) {
                    if (!((InetAddress) list.get(i2)).equals(list2.get(i2))) {
                        return false;
                    }
                }
                return true;
            }
        };
        ((ConnectivityManager) getSystemService("connectivity")).registerNetworkCallback(builder.build(), networkCallback);
        this.networkCallback = networkCallback;
    }

    private void logPacket(Packet packet) {
        this.logHandler.queue(packet);
    }

    private void nativeError(int i2, String str) {
        Log.w("NetGuard.Service", "Native error " + i2 + ": " + str);
        showErrorNotification(str);
    }

    private void nativeExit(String str) {
        Log.w("NetGuard.Service", "Native exit reason=" + str);
        if (str != null) {
            showErrorNotification(str);
            b.f(this).edit().putBoolean("enabled", false).apply();
            WidgetMain.updateWidgets(this);
        }
    }

    private void prepareForwarding() {
        this.lock.writeLock().lock();
        this.mapForward.clear();
        if (b.f(this).getBoolean("filter", false)) {
            Cursor forwarding = DatabaseHelper.getInstance(this).getForwarding();
            try {
                int columnIndex = forwarding.getColumnIndex("protocol");
                int columnIndex2 = forwarding.getColumnIndex("dport");
                int columnIndex3 = forwarding.getColumnIndex("raddr");
                int columnIndex4 = forwarding.getColumnIndex("rport");
                int columnIndex5 = forwarding.getColumnIndex("ruid");
                while (forwarding.moveToNext()) {
                    Forward forward = new Forward();
                    forward.protocol = forwarding.getInt(columnIndex);
                    forward.dport = forwarding.getInt(columnIndex2);
                    forward.raddr = forwarding.getString(columnIndex3);
                    forward.rport = forwarding.getInt(columnIndex4);
                    forward.ruid = forwarding.getInt(columnIndex5);
                    this.mapForward.put(Integer.valueOf(forward.dport), forward);
                    Log.i("NetGuard.Service", "Forward " + forward);
                }
                forwarding.close();
            } catch (Throwable th) {
                if (forwarding != null) {
                    try {
                        forwarding.close();
                    } catch (Throwable th2) {
                        th.addSuppressed(th2);
                    }
                }
                throw th;
            }
        }
        this.lock.writeLock().unlock();
    }

    private void prepareHostsBlocked() {
        BufferedReader bufferedReader;
        IOException e2;
        StringBuilder sb;
        SharedPreferences f = b.f(this);
        boolean z2 = f.getBoolean("filter", false) && f.getBoolean("use_hosts", false);
        File file = new File(getFilesDir(), "hosts.txt");
        if (z2 && file.exists() && file.canRead()) {
            if (!(file.lastModified() != this.last_hosts_modified) && this.mapHostsBlocked.size() > 0) {
                Log.i("NetGuard.Service", "Hosts file unchanged");
                return;
            }
            this.last_hosts_modified = file.lastModified();
            this.lock.writeLock().lock();
            this.mapHostsBlocked.clear();
            BufferedReader bufferedReader2 = null;
            try {
                bufferedReader = new BufferedReader(new FileReader(file));
                int i2 = 0;
                while (true) {
                    try {
                        try {
                            String readLine = bufferedReader.readLine();
                            if (readLine == null) {
                                break;
                            }
                            int indexOf = readLine.indexOf(35);
                            if (indexOf >= 0) {
                                readLine = readLine.substring(0, indexOf);
                            }
                            String trim = readLine.trim();
                            if (trim.length() > 0) {
                                String[] split = trim.split("\\s+");
                                if (split.length == 2) {
                                    i2++;
                                    this.mapHostsBlocked.put(split[1], Boolean.TRUE);
                                } else {
                                    Log.i("NetGuard.Service", "Invalid hosts file line: " + trim);
                                }
                            }
                        } catch (IOException e3) {
                            e2 = e3;
                            Log.e("NetGuard.Service", e2.toString() + "\n" + Log.getStackTraceString(e2));
                            if (bufferedReader != null) {
                                try {
                                    bufferedReader.close();
                                } catch (IOException e4) {
                                    e = e4;
                                    sb = new StringBuilder();
                                    r.f(e, sb, "\n", e, "NetGuard.Service");
                                    this.lock.writeLock().unlock();
                                    return;
                                }
                            }
                            this.lock.writeLock().unlock();
                            return;
                        }
                    } catch (Throwable th) {
                        th = th;
                        bufferedReader2 = bufferedReader;
                        if (bufferedReader2 != null) {
                            try {
                                bufferedReader2.close();
                            } catch (IOException e5) {
                                r.f(e5, new StringBuilder(), "\n", e5, "NetGuard.Service");
                            }
                        }
                        throw th;
                    }
                }
                this.mapHostsBlocked.put("test.netguard.me", Boolean.TRUE);
                Log.i("NetGuard.Service", i2 + " hosts read");
                try {
                    bufferedReader.close();
                } catch (IOException e6) {
                    e = e6;
                    sb = new StringBuilder();
                    r.f(e, sb, "\n", e, "NetGuard.Service");
                    this.lock.writeLock().unlock();
                    return;
                }
            } catch (IOException e7) {
                bufferedReader = null;
                e2 = e7;
            } catch (Throwable th2) {
                th = th2;
                if (bufferedReader2 != null) {
                }
                throw th;
            }
            this.lock.writeLock().unlock();
            return;
        }
        Log.i("NetGuard.Service", "Hosts file use=" + z2 + " exists=" + file.exists());
        this.lock.writeLock().lock();
        this.mapHostsBlocked.clear();
        this.lock.writeLock().unlock();
    }

    private void prepareMalwareList() {
        BufferedReader bufferedReader;
        IOException e2;
        StringBuilder sb;
        SharedPreferences f = b.f(this);
        boolean z2 = f.getBoolean("filter", false) && f.getBoolean("malware", false);
        File file = new File(getFilesDir(), "malware.txt");
        if (!z2 || !file.exists() || !file.canRead()) {
            Log.i("NetGuard.Service", "Malware use=" + z2 + " exists=" + file.exists());
            this.lock.writeLock().lock();
            this.mapMalware.clear();
            this.lock.writeLock().unlock();
            return;
        }
        if (!(file.lastModified() != this.last_malware_modified) && this.mapMalware.size() > 0) {
            Log.i("NetGuard.Service", "Malware unchanged");
            return;
        }
        ?? lastModified = file.lastModified();
        this.last_malware_modified = lastModified;
        this.lock.writeLock().lock();
        this.mapMalware.clear();
        BufferedReader bufferedReader2 = null;
        try {
            try {
                bufferedReader = new BufferedReader(new FileReader(file));
                int i2 = 0;
                while (true) {
                    try {
                        String readLine = bufferedReader.readLine();
                        if (readLine == null) {
                            break;
                        }
                        int indexOf = readLine.indexOf(35);
                        if (indexOf >= 0) {
                            readLine = readLine.substring(0, indexOf);
                        }
                        String trim = readLine.trim();
                        if (trim.length() > 0) {
                            String[] split = trim.split("\\s+");
                            if (split.length > 1) {
                                i2++;
                                this.mapMalware.put(split[1], Boolean.TRUE);
                            } else {
                                Log.i("NetGuard.Service", "Invalid malware file line: " + trim);
                            }
                        }
                    } catch (IOException e3) {
                        e2 = e3;
                        Log.e("NetGuard.Service", e2.toString() + "\n" + Log.getStackTraceString(e2));
                        if (bufferedReader != null) {
                            try {
                                bufferedReader.close();
                            } catch (IOException e4) {
                                e = e4;
                                sb = new StringBuilder();
                                r.f(e, sb, "\n", e, "NetGuard.Service");
                                this.lock.writeLock().unlock();
                            }
                        }
                        this.lock.writeLock().unlock();
                    }
                }
                Log.i("NetGuard.Service", i2 + " malware read");
                try {
                    bufferedReader.close();
                } catch (IOException e5) {
                    e = e5;
                    sb = new StringBuilder();
                    r.f(e, sb, "\n", e, "NetGuard.Service");
                    this.lock.writeLock().unlock();
                }
            } catch (Throwable th) {
                th = th;
                bufferedReader2 = lastModified;
                if (bufferedReader2 != null) {
                    try {
                        bufferedReader2.close();
                    } catch (IOException e6) {
                        r.f(e6, new StringBuilder(), "\n", e6, "NetGuard.Service");
                    }
                }
                throw th;
            }
        } catch (IOException e7) {
            bufferedReader = null;
            e2 = e7;
        } catch (Throwable th2) {
            th = th2;
            if (bufferedReader2 != null) {
            }
            throw th;
        }
        this.lock.writeLock().unlock();
    }

    private void prepareNotify(List list) {
        SharedPreferences f = b.f(this);
        boolean z2 = f.getBoolean("notify_access", false);
        boolean z3 = f.getBoolean("manage_system", false);
        this.lock.writeLock().lock();
        this.mapNotify.clear();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Rule rule = (Rule) it.next();
            this.mapNotify.put(Integer.valueOf(rule.uid), Boolean.valueOf(z2 && rule.notify && (z3 || !rule.system)));
        }
        this.lock.writeLock().unlock();
    }

    private void prepareUidAllowed(List list, List list2) {
        this.lock.writeLock().lock();
        this.mapUidAllowed.clear();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            this.mapUidAllowed.put(Integer.valueOf(((Rule) it.next()).uid), Boolean.TRUE);
        }
        this.mapUidKnown.clear();
        Iterator it2 = list2.iterator();
        while (it2.hasNext()) {
            Rule rule = (Rule) it2.next();
            this.mapUidKnown.put(Integer.valueOf(rule.uid), Integer.valueOf(rule.uid));
        }
        this.lock.writeLock().unlock();
    }

    private void prepareUidIPFilters(String str) {
        Cursor cursor;
        Throwable th;
        int i2;
        boolean z2;
        long time;
        int i3;
        Map map;
        Map map2;
        SharedPreferences sharedPreferences;
        String[] packagesForUid;
        SharedPreferences sharedPreferences2 = getSharedPreferences("lockdown", 0);
        this.lock.writeLock().lock();
        if (str == null) {
            this.mapUidIPFilters.clear();
            if (!IAB.isPurchased("filter", this)) {
                this.lock.writeLock().unlock();
                return;
            }
        }
        Cursor accessDns = DatabaseHelper.getInstance(this).getAccessDns(str);
        try {
            int columnIndex = accessDns.getColumnIndex("uid");
            int columnIndex2 = accessDns.getColumnIndex("version");
            int columnIndex3 = accessDns.getColumnIndex("protocol");
            int columnIndex4 = accessDns.getColumnIndex("daddr");
            int columnIndex5 = accessDns.getColumnIndex("resource");
            int columnIndex6 = accessDns.getColumnIndex("dport");
            int columnIndex7 = accessDns.getColumnIndex("block");
            int columnIndex8 = accessDns.getColumnIndex("time");
            int columnIndex9 = accessDns.getColumnIndex("ttl");
            while (accessDns.moveToNext()) {
                int i4 = accessDns.getInt(columnIndex);
                int i5 = accessDns.getInt(columnIndex2);
                int i6 = accessDns.getInt(columnIndex3);
                String string = accessDns.getString(columnIndex4);
                int i7 = columnIndex;
                String string2 = accessDns.isNull(columnIndex5) ? null : accessDns.getString(columnIndex5);
                int i8 = accessDns.getInt(columnIndex6);
                if (accessDns.getInt(columnIndex7) > 0) {
                    i2 = columnIndex4;
                    z2 = true;
                } else {
                    i2 = columnIndex4;
                    z2 = false;
                }
                if (accessDns.isNull(columnIndex8)) {
                    try {
                        time = new Date().getTime();
                    } catch (Throwable th2) {
                        th = th2;
                        cursor = accessDns;
                        if (cursor != null) {
                        }
                        throw th;
                    }
                } else {
                    time = accessDns.getLong(columnIndex8);
                }
                int i9 = columnIndex2;
                int i10 = columnIndex3;
                long j2 = time;
                long j3 = accessDns.isNull(columnIndex9) ? 604800000L : accessDns.getLong(columnIndex9);
                if (!isLockedDown(this.last_metered) || (packagesForUid = getPackageManager().getPackagesForUid(i4)) == null) {
                    i3 = columnIndex9;
                } else {
                    i3 = columnIndex9;
                    if (packagesForUid.length > 0) {
                        if (!sharedPreferences2.getBoolean(packagesForUid[0], false)) {
                            columnIndex = i7;
                            columnIndex4 = i2;
                            columnIndex9 = i3;
                            columnIndex2 = i9;
                            columnIndex3 = i10;
                        }
                        int i11 = columnIndex8;
                        int i12 = columnIndex7;
                        int i13 = columnIndex6;
                        int i14 = columnIndex5;
                        IPKey iPKey = new IPKey(i5, i6, i8, i4);
                        map = this.mapUidIPFilters;
                        synchronized (map) {
                            try {
                                if (!this.mapUidIPFilters.containsKey(iPKey)) {
                                    this.mapUidIPFilters.put(iPKey, new HashMap());
                                }
                                String str2 = string2 == null ? string : string2;
                                try {
                                    if (Util.isNumericAddress(str2)) {
                                        InetAddress byName = InetAddress.getByName(str2);
                                        if (i5 != 4 || (byName instanceof Inet4Address)) {
                                            if (i5 != 6 || (byName instanceof Inet6Address)) {
                                                boolean containsKey = ((Map) this.mapUidIPFilters.get(iPKey)).containsKey(byName);
                                                if (containsKey && ((IPRule) ((Map) this.mapUidIPFilters.get(iPKey)).get(byName)).isBlocked()) {
                                                    if (containsKey) {
                                                        ((IPRule) ((Map) this.mapUidIPFilters.get(iPKey)).get(byName)).updateExpires(j2, j3);
                                                        if (str != null && j3 > 60000) {
                                                            Log.w("NetGuard.Service", "Address updated " + iPKey + " " + string + "/" + string2);
                                                        }
                                                    } else if (str != null) {
                                                        Log.i("NetGuard.Service", "Ignored " + iPKey + " " + string + "/" + string2 + "=" + z2);
                                                    }
                                                    map2 = map;
                                                    sharedPreferences = sharedPreferences2;
                                                    cursor = accessDns;
                                                }
                                                sharedPreferences = sharedPreferences2;
                                                cursor = accessDns;
                                                map2 = map;
                                                try {
                                                    try {
                                                        ((Map) this.mapUidIPFilters.get(iPKey)).put(byName, new IPRule(iPKey, str2 + "/" + byName, z2, j2, j3));
                                                        if (containsKey) {
                                                            Log.w("NetGuard.Service", "Address conflict " + iPKey + " " + string + "/" + string2);
                                                        }
                                                    } catch (Throwable th3) {
                                                        th = th3;
                                                        try {
                                                            throw th;
                                                        } catch (Throwable th4) {
                                                            th = th4;
                                                            th = th;
                                                            if (cursor != null) {
                                                                try {
                                                                    cursor.close();
                                                                } catch (Throwable th5) {
                                                                    th.addSuppressed(th5);
                                                                }
                                                            }
                                                            throw th;
                                                        }
                                                    }
                                                } catch (UnknownHostException e2) {
                                                    e = e2;
                                                    Log.e("NetGuard.Service", e.toString() + "\n" + Log.getStackTraceString(e));
                                                    columnIndex6 = i13;
                                                    columnIndex5 = i14;
                                                    columnIndex = i7;
                                                    columnIndex4 = i2;
                                                    sharedPreferences2 = sharedPreferences;
                                                    columnIndex9 = i3;
                                                    columnIndex2 = i9;
                                                    columnIndex3 = i10;
                                                    accessDns = cursor;
                                                    columnIndex8 = i11;
                                                    columnIndex7 = i12;
                                                }
                                            }
                                        }
                                    } else {
                                        map2 = map;
                                        sharedPreferences = sharedPreferences2;
                                        cursor = accessDns;
                                        Log.w("NetGuard.Service", "Address not numeric " + str2);
                                    }
                                } catch (UnknownHostException e3) {
                                    e = e3;
                                    map2 = map;
                                    sharedPreferences = sharedPreferences2;
                                    cursor = accessDns;
                                }
                                columnIndex6 = i13;
                                columnIndex5 = i14;
                                columnIndex = i7;
                                columnIndex4 = i2;
                                sharedPreferences2 = sharedPreferences;
                                columnIndex9 = i3;
                                columnIndex2 = i9;
                                columnIndex3 = i10;
                                accessDns = cursor;
                                columnIndex8 = i11;
                                columnIndex7 = i12;
                            } catch (Throwable th6) {
                                th = th6;
                                map2 = map;
                                cursor = accessDns;
                                throw th;
                            }
                        }
                        columnIndex6 = i13;
                        columnIndex5 = i14;
                        columnIndex = i7;
                        columnIndex4 = i2;
                        columnIndex9 = i3;
                        columnIndex2 = i9;
                        columnIndex3 = i10;
                        columnIndex8 = i11;
                        columnIndex7 = i12;
                    }
                }
                int i112 = columnIndex8;
                int i122 = columnIndex7;
                int i132 = columnIndex6;
                int i142 = columnIndex5;
                IPKey iPKey2 = new IPKey(i5, i6, i8, i4);
                map = this.mapUidIPFilters;
                synchronized (map) {
                }
            }
            accessDns.close();
            this.lock.writeLock().unlock();
        } catch (Throwable th7) {
            th = th7;
            cursor = accessDns;
        }
    }

    private static synchronized void releaseLock(Context context) {
        synchronized (ServiceSinkhole.class) {
            try {
                if (wlInstance != null) {
                    while (wlInstance.isHeld()) {
                        wlInstance.release();
                    }
                    wlInstance = null;
                }
            } catch (Throwable th) {
                throw th;
            }
        }
    }

    public static void reload(String str, Context context, boolean z2) {
        if (b.f(context).getBoolean("enabled", false)) {
            Intent intent = new Intent(context, ServiceSinkhole.class);
            intent.putExtra("Command", Command.reload);
            intent.putExtra("Reason", str);
            intent.putExtra("Interactive", z2);
            try {
                f.g(context, intent);
            } catch (Throwable th) {
                if (Build.VERSION.SDK_INT >= 31 && C0142h.e(th)) {
                    try {
                        context.startService(intent);
                    } catch (Throwable th2) {
                        Log.e("NetGuard.Service", th2 + "\n" + Log.getStackTraceString(th2));
                    }
                }
            }
        }
    }

    public static void reloadStats(String str, Context context) {
        Intent intent = new Intent(context, ServiceSinkhole.class);
        intent.putExtra("Command", Command.stats);
        intent.putExtra("Reason", str);
        try {
            f.g(context, intent);
        } catch (Throwable th) {
            if (Build.VERSION.SDK_INT < 31 || !C0142h.e(th)) {
                return;
            }
            try {
                context.startService(intent);
            } catch (Throwable th2) {
                Log.e("NetGuard.Service", th2 + "\n" + Log.getStackTraceString(th2));
            }
        }
    }

    public void removeLockdownNotification() {
        C.c(this).b(4);
    }

    public void removeWarningNotifications() {
        C.c(this).b(3);
        C.c(this).b(5);
        C.c(this).b(6);
    }

    public static void run(String str, Context context) {
        Intent intent = new Intent(context, ServiceSinkhole.class);
        intent.putExtra("Command", Command.run);
        intent.putExtra("Reason", str);
        try {
            f.g(context, intent);
        } catch (Throwable th) {
            if (Build.VERSION.SDK_INT >= 31 && C0142h.e(th)) {
                try {
                    context.startService(intent);
                } catch (Throwable th2) {
                    Log.e("NetGuard.Service", th2 + "\n" + Log.getStackTraceString(th2));
                }
            }
        }
    }

    private void set(Intent intent) {
        int intExtra = intent.getIntExtra("UID", 0);
        String stringExtra = intent.getStringExtra("Network");
        String stringExtra2 = intent.getStringExtra("Package");
        boolean booleanExtra = intent.getBooleanExtra("Blocked", false);
        Log.i("NetGuard.Service", "Set " + stringExtra2 + " " + stringExtra + "=" + booleanExtra);
        SharedPreferences f = b.f(this);
        boolean z2 = f.getBoolean("whitelist_wifi", true);
        boolean z3 = f.getBoolean("whitelist_other", true);
        SharedPreferences sharedPreferences = getSharedPreferences(stringExtra, 0);
        if (!"wifi".equals(stringExtra)) {
            z2 = z3;
        }
        if (booleanExtra == z2) {
            sharedPreferences.edit().remove(stringExtra2).apply();
        } else {
            d.d(sharedPreferences, stringExtra2, booleanExtra);
        }
        reload("notification", this, false);
        notifyNewApplication(intExtra, false);
        C0496d.b(this).d(new Intent("eu.faircode.netguard.ACTION_RULES_CHANGED"));
    }

    public static void setPcap(boolean z2, Context context) {
        int i2;
        int i3;
        SharedPreferences f = b.f(context);
        try {
            String string = f.getString("pcap_record_size", null);
            if (TextUtils.isEmpty(string)) {
                string = "64";
            }
            i2 = Integer.parseInt(string);
        } catch (Throwable th) {
            r.h(th, new StringBuilder(), "\n", th, "NetGuard.Service");
            i2 = 64;
        }
        try {
            String string2 = f.getString("pcap_file_size", null);
            if (TextUtils.isEmpty(string2)) {
                string2 = "2";
            }
            i3 = Integer.parseInt(string2) * 1024 * 1024;
        } catch (Throwable th2) {
            r.h(th2, new StringBuilder(), "\n", th2, "NetGuard.Service");
            i3 = 2097152;
        }
        File file = z2 ? new File(context.getDir("data", 0), "netguard.pcap") : null;
        jni_pcap(file != null ? file.getAbsolutePath() : null, i2, i3);
    }

    public void showAccessNotification(int i2) {
        long j2;
        Cursor accessUnset;
        List applicationNames = Util.getApplicationNames(i2, this);
        if (applicationNames.size() == 0) {
            return;
        }
        String join = TextUtils.join(", ", applicationNames);
        Intent intent = new Intent(this, ActivityMain.class);
        intent.putExtra("Search", Integer.toString(i2));
        int i3 = i2 + 10000;
        PendingIntent activity = PendingIntentCompat.getActivity(this, i3, intent, 134217728);
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorOn, typedValue, true);
        int i4 = typedValue.data;
        getTheme().resolveAttribute(R.attr.colorOff, typedValue, true);
        int i5 = typedValue.data;
        androidx.core.app.r rVar = new androidx.core.app.r(this, "access");
        rVar.n(R.drawable.ic_cloud_upload_white_24dp);
        rVar.j();
        rVar.g(activity);
        rVar.e(i5);
        rVar.k(false);
        rVar.c(true);
        int i6 = Build.VERSION.SDK_INT;
        if (i6 >= 24) {
            rVar.i(join);
            rVar.h(getString(R.string.msg_access_n));
        } else {
            rVar.i(getString(R.string.app_name));
            rVar.h(getString(R.string.msg_access, join));
        }
        rVar.d();
        rVar.o(-1);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd HH:mm");
        s sVar = new s(rVar);
        if (i6 >= 24) {
            sVar.f(getString(R.string.msg_access_n));
        } else {
            String string = getString(R.string.msg_access, join);
            int indexOf = string.indexOf(join);
            SpannableString spannableString = new SpannableString(string);
            spannableString.setSpan(new StyleSpan(1), indexOf, join.length() + indexOf, 33);
            sVar.f(spannableString);
        }
        PackageManager packageManager = getPackageManager();
        String[] packagesForUid = packageManager.getPackagesForUid(i2);
        try {
            if (packagesForUid != null && packagesForUid.length > 0) {
                try {
                    j2 = packageManager.getPackageInfo(packagesForUid[0], 0).firstInstallTime;
                } catch (PackageManager.NameNotFoundException unused) {
                }
                accessUnset = DatabaseHelper.getInstance(this).getAccessUnset(i2, 7, j2);
                int columnIndex = accessUnset.getColumnIndex("daddr");
                int columnIndex2 = accessUnset.getColumnIndex("time");
                int columnIndex3 = accessUnset.getColumnIndex("allowed");
                while (accessUnset.moveToNext()) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(simpleDateFormat.format(Long.valueOf(accessUnset.getLong(columnIndex2))));
                    sb.append(' ');
                    String string2 = accessUnset.getString(columnIndex);
                    if (Util.isNumericAddress(string2)) {
                        try {
                            string2 = InetAddress.getByName(string2).getHostName();
                        } catch (UnknownHostException unused2) {
                        }
                    }
                    sb.append(string2);
                    int i7 = accessUnset.getInt(columnIndex3);
                    if (i7 >= 0) {
                        int indexOf2 = sb.indexOf(string2);
                        SpannableString spannableString2 = new SpannableString(sb);
                        spannableString2.setSpan(new ForegroundColorSpan(i7 > 0 ? i4 : i5), indexOf2, string2.length() + indexOf2, 33);
                        sVar.f(spannableString2);
                    } else {
                        sVar.f(sb);
                    }
                }
                accessUnset.close();
                if (Util.canNotify(this)) {
                    return;
                }
                C.c(this).e(i3, sVar.c());
                return;
            }
            int columnIndex4 = accessUnset.getColumnIndex("daddr");
            int columnIndex22 = accessUnset.getColumnIndex("time");
            int columnIndex32 = accessUnset.getColumnIndex("allowed");
            while (accessUnset.moveToNext()) {
            }
            accessUnset.close();
            if (Util.canNotify(this)) {
            }
        } catch (Throwable th) {
            if (accessUnset != null) {
                try {
                    accessUnset.close();
                } catch (Throwable th2) {
                    th.addSuppressed(th2);
                }
            }
            throw th;
        }
        j2 = 0;
        accessUnset = DatabaseHelper.getInstance(this).getAccessUnset(i2, 7, j2);
    }

    private void showDisabledNotification() {
        PendingIntent activity = PendingIntentCompat.getActivity(this, 0, new Intent(this, ActivityMain.class), 134217728);
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorOff, typedValue, true);
        androidx.core.app.r rVar = new androidx.core.app.r(this, "notify");
        rVar.n(R.drawable.ic_error_white_24dp);
        rVar.i(getString(R.string.app_name));
        rVar.h(getString(R.string.msg_revoked));
        rVar.g(activity);
        rVar.e(typedValue.data);
        rVar.k(false);
        rVar.c(true);
        rVar.d();
        rVar.o(-1);
        q qVar = new q(rVar);
        qVar.f(getString(R.string.msg_revoked));
        if (Util.canNotify(this)) {
            C.c(this).e(3, qVar.c());
        }
    }

    public void showErrorNotification(String str) {
        PendingIntent activity = PendingIntentCompat.getActivity(this, 0, new Intent(this, ActivityMain.class), 134217728);
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorOff, typedValue, true);
        androidx.core.app.r rVar = new androidx.core.app.r(this, "notify");
        rVar.n(R.drawable.ic_error_white_24dp);
        rVar.i(getString(R.string.app_name));
        rVar.h(getString(R.string.msg_error, str));
        rVar.g(activity);
        rVar.e(typedValue.data);
        rVar.k(false);
        rVar.c(true);
        rVar.d();
        rVar.o(-1);
        q qVar = new q(rVar);
        qVar.f(getString(R.string.msg_error, str));
        qVar.g(str);
        if (Util.canNotify(this)) {
            C.c(this).e(6, qVar.c());
        }
    }

    public void showLockdownNotification() {
        PendingIntent activity = PendingIntentCompat.getActivity(this, 4, new Intent("android.settings.VPN_SETTINGS"), 134217728);
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorOff, typedValue, true);
        androidx.core.app.r rVar = new androidx.core.app.r(this, "notify");
        rVar.n(R.drawable.ic_error_white_24dp);
        rVar.i(getString(R.string.app_name));
        rVar.h(getString(R.string.msg_always_on_lockdown));
        rVar.g(activity);
        rVar.l(1);
        rVar.e(typedValue.data);
        rVar.k(false);
        rVar.c(true);
        rVar.d();
        rVar.o(-1);
        q qVar = new q(rVar);
        qVar.f(getString(R.string.msg_always_on_lockdown));
        if (Util.canNotify(this)) {
            C.c(this).e(4, qVar.c());
        }
    }

    public void showUpdateNotification(String str, String str2) {
        PendingIntent activity = PendingIntentCompat.getActivity(this, 0, new Intent("android.intent.action.VIEW", Uri.parse(str2)), 134217728);
        TypedValue typedValue = new TypedValue();
        getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
        androidx.core.app.r rVar = new androidx.core.app.r(this, "notify");
        rVar.n(R.drawable.ic_security_white_24dp);
        rVar.i(str);
        rVar.h(getString(R.string.msg_update));
        rVar.g(activity);
        rVar.e(typedValue.data);
        rVar.k(false);
        rVar.c(true);
        rVar.d();
        rVar.o(-1);
        if (Util.canNotify(this)) {
            C.c(this).e(8, rVar.a());
        }
    }

    public static void start(String str, Context context) {
        Intent intent = new Intent(context, ServiceSinkhole.class);
        intent.putExtra("Command", Command.start);
        intent.putExtra("Reason", str);
        try {
            f.g(context, intent);
        } catch (Throwable th) {
            if (Build.VERSION.SDK_INT < 31 || !C0142h.e(th)) {
                return;
            }
            try {
                context.startService(intent);
            } catch (Throwable th2) {
                Log.e("NetGuard.Service", th2 + "\n" + Log.getStackTraceString(th2));
            }
        }
    }

    public void startNative(final ParcelFileDescriptor parcelFileDescriptor, List list, List list2) {
        SharedPreferences f = b.f(this);
        boolean z2 = f.getBoolean("log", false);
        boolean z3 = f.getBoolean("log_app", false);
        boolean z4 = f.getBoolean("filter", false);
        Log.i("NetGuard.Service", "Start native log=" + z2 + "/" + z3 + " filter=" + z4);
        if (z4) {
            prepareUidAllowed(list, list2);
            prepareHostsBlocked();
            prepareMalwareList();
            prepareUidIPFilters(null);
            prepareForwarding();
        } else {
            this.lock.writeLock().lock();
            this.mapUidAllowed.clear();
            this.mapUidKnown.clear();
            this.mapHostsBlocked.clear();
            this.mapMalware.clear();
            this.mapUidIPFilters.clear();
            this.mapForward.clear();
            this.lock.writeLock().unlock();
        }
        if (z3) {
            prepareNotify(list2);
        } else {
            this.lock.writeLock().lock();
            this.mapNotify.clear();
            this.lock.writeLock().unlock();
        }
        if (z2 || z3 || z4) {
            int parseInt = Integer.parseInt(f.getString("loglevel", Integer.toString(5)));
            final int parseInt2 = Integer.parseInt(f.getString("rcode", "3"));
            if (f.getBoolean("socks5_enabled", false)) {
                jni_socks5(f.getString("socks5_addr", ""), Integer.parseInt(f.getString("socks5_port", "0")), f.getString("socks5_username", ""), f.getString("socks5_password", ""));
            } else {
                jni_socks5("", 0, "", "");
            }
            if (this.tunnelThread == null) {
                Log.i("NetGuard.Service", "Starting tunnel thread context=" + jni_context);
                jni_start(jni_context, parseInt);
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("NetGuard.Service", "Running tunnel context=" + ServiceSinkhole.jni_context);
                        ServiceSinkhole.this.jni_run(ServiceSinkhole.jni_context, parcelFileDescriptor.getFd(), ServiceSinkhole.this.mapForward.containsKey(53), parseInt2);
                        Log.i("NetGuard.Service", "Tunnel exited");
                        ServiceSinkhole.this.tunnelThread = null;
                    }
                });
                this.tunnelThread = thread;
                thread.start();
                Log.i("NetGuard.Service", "Started tunnel thread");
            }
        }
    }

    public ParcelFileDescriptor startVPN(Builder builder) {
        try {
            ParcelFileDescriptor establish = builder.establish();
            if (Build.VERSION.SDK_INT >= 23) {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService("connectivity");
                Network activeNetwork = connectivityManager == null ? null : connectivityManager.getActiveNetwork();
                if (activeNetwork != null) {
                    Log.i("NetGuard.Service", "Setting underlying network=" + connectivityManager.getNetworkInfo(activeNetwork));
                    setUnderlyingNetworks(new Network[]{activeNetwork});
                }
            }
            return establish;
        } catch (SecurityException e2) {
            throw e2;
        } catch (Throwable th) {
            r.h(th, new StringBuilder(), "\n", th, "NetGuard.Service");
            return null;
        }
    }

    public static void stop(String str, Context context, boolean z2) {
        Intent intent = new Intent(context, ServiceSinkhole.class);
        intent.putExtra("Command", Command.stop);
        intent.putExtra("Reason", str);
        intent.putExtra("Temporary", z2);
        try {
            f.g(context, intent);
        } catch (Throwable th) {
            if (Build.VERSION.SDK_INT < 31 || !C0142h.e(th)) {
                return;
            }
            try {
                context.startService(intent);
            } catch (Throwable th2) {
                Log.e("NetGuard.Service", th2 + "\n" + Log.getStackTraceString(th2));
            }
        }
    }

    public void stopNative(ParcelFileDescriptor parcelFileDescriptor) {
        Log.i("NetGuard.Service", "Stop native");
        if (this.tunnelThread != null) {
            Log.i("NetGuard.Service", "Stopping tunnel thread");
            jni_stop(jni_context);
            Thread thread = this.tunnelThread;
            while (thread != null && thread.isAlive()) {
                try {
                    Log.i("NetGuard.Service", "Joining tunnel thread context=" + jni_context);
                    thread.join();
                } catch (InterruptedException unused) {
                    Log.i("NetGuard.Service", "Joined tunnel interrupted");
                }
                thread = this.tunnelThread;
            }
            this.tunnelThread = null;
            jni_clear(jni_context);
            Log.i("NetGuard.Service", "Stopped tunnel thread");
        }
    }

    public void stopVPN(ParcelFileDescriptor parcelFileDescriptor) {
        Log.i("NetGuard.Service", "Stopping");
        try {
            parcelFileDescriptor.close();
        } catch (IOException e2) {
            r.f(e2, new StringBuilder(), "\n", e2, "NetGuard.Service");
        }
    }

    private void unlistenNetworkChanges() {
        ((ConnectivityManager) getSystemService("connectivity")).unregisterNetworkCallback((ConnectivityManager.NetworkCallback) this.networkCallback);
    }

    public void unprepare() {
        this.lock.writeLock().lock();
        this.mapUidAllowed.clear();
        this.mapUidKnown.clear();
        this.mapHostsBlocked.clear();
        this.mapMalware.clear();
        this.mapUidIPFilters.clear();
        this.mapForward.clear();
        this.mapNotify.clear();
        this.lock.writeLock().unlock();
    }

    public void updateEnforcingNotification(int i2, int i3) {
        Notification enforcingNotification = getEnforcingNotification(i2, i3 - i2, this.mapHostsBlocked.size());
        NotificationManager notificationManager = (NotificationManager) getSystemService("notification");
        if (Util.canNotify(this)) {
            notificationManager.notify(1, enforcingNotification);
        }
    }

    public void notifyNewApplication(int i2, boolean z2) {
        String str;
        int i3;
        if (i2 >= 0 && i2 != Process.myUid()) {
            SharedPreferences f = b.f(this);
            try {
                List applicationNames = Util.getApplicationNames(i2, this);
                if (applicationNames.size() == 0) {
                    return;
                }
                String join = TextUtils.join(", ", applicationNames);
                String[] packagesForUid = getPackageManager().getPackagesForUid(i2);
                if (packagesForUid == null || packagesForUid.length < 1) {
                    throw new PackageManager.NameNotFoundException(Integer.toString(i2));
                }
                boolean hasInternet = Util.hasInternet(i2, this);
                Intent intent = new Intent(this, ActivityMain.class);
                intent.putExtra("Refresh", true);
                intent.putExtra("Search", Integer.toString(i2));
                PendingIntent activity = PendingIntentCompat.getActivity(this, i2, intent, 134217728);
                TypedValue typedValue = new TypedValue();
                getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
                androidx.core.app.r rVar = new androidx.core.app.r(this, z2 ? "malware" : "notify");
                rVar.n(R.drawable.ic_security_white_24dp);
                rVar.g(activity);
                rVar.e(typedValue.data);
                rVar.c(true);
                if (z2) {
                    rVar.i(join);
                    rVar.h(getString(R.string.msg_malware, join));
                } else if (Build.VERSION.SDK_INT >= 24) {
                    rVar.i(join);
                    rVar.h(getString(R.string.msg_installed_n));
                } else {
                    rVar.i(getString(R.string.app_name));
                    rVar.h(getString(R.string.msg_installed, join));
                }
                int i4 = Build.VERSION.SDK_INT;
                rVar.d();
                rVar.o(-1);
                SharedPreferences sharedPreferences = getSharedPreferences("wifi", 0);
                SharedPreferences sharedPreferences2 = getSharedPreferences("other", 0);
                boolean z3 = sharedPreferences.getBoolean(packagesForUid[0], f.getBoolean("whitelist_wifi", true));
                boolean z4 = sharedPreferences2.getBoolean(packagesForUid[0], f.getBoolean("whitelist_other", true));
                Intent intent2 = new Intent(this, ServiceSinkhole.class);
                Command command = Command.set;
                intent2.putExtra("Command", command);
                intent2.putExtra("Network", "wifi");
                intent2.putExtra("UID", i2);
                intent2.putExtra("Package", packagesForUid[0]);
                intent2.putExtra("Blocked", !z3);
                PendingIntent service = PendingIntentCompat.getService(this, i2, intent2, 134217728);
                if (z3) {
                    str = "Blocked";
                    i3 = R.drawable.wifi_on;
                } else {
                    str = "Blocked";
                    i3 = R.drawable.wifi_off;
                }
                rVar.f1321b.add(new o(i3, getString(z3 ? R.string.title_allow_wifi : R.string.title_block_wifi), service).a());
                Intent intent3 = new Intent(this, ServiceSinkhole.class);
                intent3.putExtra("Command", command);
                intent3.putExtra("Network", "other");
                intent3.putExtra("UID", i2);
                intent3.putExtra("Package", packagesForUid[0]);
                intent3.putExtra(str, !z4);
                rVar.f1321b.add(new o(z4 ? R.drawable.other_on : R.drawable.other_off, getString(z4 ? R.string.title_allow_other : R.string.title_block_other), PendingIntentCompat.getService(this, i2 + 10000, intent3, 134217728)).a());
                if (hasInternet) {
                    if (Util.canNotify(this)) {
                        C.c(this).e(i2, rVar.a());
                        return;
                    }
                    return;
                }
                q qVar = new q(rVar);
                if (i4 >= 24) {
                    qVar.f(getString(R.string.msg_installed_n));
                } else {
                    qVar.f(getString(R.string.msg_installed, join));
                }
                qVar.g(getString(R.string.title_internet));
                if (Util.canNotify(this)) {
                    C.c(this).e(i2, qVar.c());
                }
            } catch (PackageManager.NameNotFoundException e2) {
                Log.e("NetGuard.Service", e2.toString() + "\n" + Log.getStackTraceString(e2));
            }
        }
    }

    @Override
    public void onCreate() {
        Log.i("NetGuard.Service", "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));
        startForeground(2, getWaitingNotification());
        SharedPreferences f = b.f(this);
        if (jni_context != 0) {
            Log.w("NetGuard.Service", "Create with context=" + jni_context);
            jni_stop(jni_context);
            synchronized (jni_lock) {
                try {
                    jni_done(jni_context);
                    jni_context = 0L;
                } catch (Throwable th) {
                    throw th;
                }
            }
        }
        int i2 = Build.VERSION.SDK_INT;
        jni_context = jni_init(i2);
        Log.i("NetGuard.Service", "Created context=" + jni_context);
        setPcap(f.getBoolean("pcap", false), this);
        f.registerOnSharedPreferenceChangeListener(this);
        Util.setTheme(this);
        super.onCreate();
        HandlerThread handlerThread = new HandlerThread(getString(R.string.app_name) + " command", -2);
        HandlerThread handlerThread2 = new HandlerThread(getString(R.string.app_name) + " log", 10);
        HandlerThread handlerThread3 = new HandlerThread(getString(R.string.app_name) + " stats", 10);
        handlerThread.start();
        handlerThread2.start();
        handlerThread3.start();
        this.commandLooper = handlerThread.getLooper();
        this.logLooper = handlerThread2.getLooper();
        this.statsLooper = handlerThread3.getLooper();
        this.commandHandler = new CommandHandler(this.commandLooper);
        this.logHandler = new LogHandler(this.logLooper);
        this.statsHandler = new StatsHandler(this.statsLooper);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.USER_BACKGROUND");
        intentFilter.addAction("android.intent.action.USER_FOREGROUND");
        f.e(this, this.userReceiver, intentFilter);
        this.registeredUser = true;
        if (i2 >= 23) {
            IntentFilter intentFilter2 = new IntentFilter();
            intentFilter2.addAction("android.os.action.DEVICE_IDLE_MODE_CHANGED");
            f.e(this, this.idleStateReceiver, intentFilter2);
            this.registeredIdleState = true;
        }
        IntentFilter intentFilter3 = new IntentFilter();
        intentFilter3.addAction("android.intent.action.PACKAGE_ADDED");
        intentFilter3.addAction("android.intent.action.PACKAGE_REMOVED");
        intentFilter3.addDataScheme("package");
        f.e(this, this.packageChangedReceiver, intentFilter3);
        this.registeredPackageChanged = true;
        if (i2 >= 23) {
            try {
                listenNetworkChanges();
            } catch (Throwable th2) {
                Log.w("NetGuard.Service", th2.toString() + "\n" + Log.getStackTraceString(th2));
                listenConnectivityChanges();
            }
        } else {
            listenConnectivityChanges();
        }
        ((ConnectivityManager) getSystemService("connectivity")).registerNetworkCallback(new NetworkRequest.Builder().addCapability(12).build(), this.networkMonitorCallback);
        Intent intent = new Intent(this, ServiceSinkhole.class);
        intent.setAction("eu.faircode.netguard.HOUSE_HOLDING");
        ((AlarmManager) getSystemService("alarm")).setInexactRepeating(1, SystemClock.elapsedRealtime() + 60000, 43200000L, Build.VERSION.SDK_INT >= 26 ? PendingIntentCompat.getForegroundService(this, 0, intent, 134217728) : PendingIntentCompat.getService(this, 0, intent, 134217728));
    }

    @Override
    public void onDestroy() {
        synchronized (this) {
            try {
                Log.i("NetGuard.Service", "Destroy");
                this.commandLooper.quit();
                this.logLooper.quit();
                this.statsLooper.quit();
                boolean z2 = true;
                for (Command command : Command.values()) {
                    this.commandHandler.removeMessages(command.ordinal());
                }
                releaseLock(this);
                if (this.registeredInteractiveState) {
                    unregisterReceiver(this.interactiveStateReceiver);
                    this.registeredInteractiveState = false;
                }
                if (this.callStateListener != null) {
                    ((TelephonyManager) getSystemService("phone")).listen(this.callStateListener, 0);
                    this.callStateListener = null;
                }
                if (this.registeredUser) {
                    unregisterReceiver(this.userReceiver);
                    this.registeredUser = false;
                }
                if (this.registeredIdleState) {
                    unregisterReceiver(this.idleStateReceiver);
                    this.registeredIdleState = false;
                }
                if (this.registeredPackageChanged) {
                    unregisterReceiver(this.packageChangedReceiver);
                    this.registeredPackageChanged = false;
                }
                if (this.networkCallback != null) {
                    unlistenNetworkChanges();
                    this.networkCallback = null;
                }
                if (this.registeredConnectivityChanged) {
                    unregisterReceiver(this.connectivityChangedReceiver);
                    this.registeredConnectivityChanged = false;
                }
                ((ConnectivityManager) getSystemService("connectivity")).unregisterNetworkCallback(this.networkMonitorCallback);
                if (this.phone_state) {
                    ((TelephonyManager) getSystemService("phone")).listen(this.phoneStateListener, 0);
                    this.phone_state = false;
                }
                ParcelFileDescriptor parcelFileDescriptor = this.vpn;
                if (parcelFileDescriptor != null) {
                    stopNative(parcelFileDescriptor);
                    stopVPN(this.vpn);
                    this.vpn = null;
                    unprepare();
                }
                Log.i("NetGuard.Service", "Destroy context=" + jni_context);
                synchronized (jni_lock) {
                    jni_done(jni_context);
                    jni_context = 0L;
                }
                b.f(this).unregisterOnSharedPreferenceChangeListener(this);
            } catch (Throwable th) {
                throw th;
            }
        }
        super.onDestroy();
    }

    @Override
    public void onRevoke() {
        Log.i("NetGuard.Service", "Revoke");
        b.f(this).edit().putBoolean("enabled", false).apply();
        showDisabledNotification();
        WidgetMain.updateWidgets(this);
        super.onRevoke();
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String str) {
        if ("theme".equals(str)) {
            Log.i("NetGuard.Service", "Theme changed");
            Util.setTheme(this);
            State state = this.state;
            State state2 = State.none;
            if (state != state2) {
                Log.d("NetGuard.Service", "Stop foreground state=" + this.state.toString());
                stopForeground(true);
            }
            State state3 = this.state;
            if (state3 == State.enforcing) {
                startForeground(1, getEnforcingNotification(-1, -1, -1));
            } else if (state3 != state2) {
                startForeground(2, getWaitingNotification());
            }
            Log.d("NetGuard.Service", "Start foreground state=" + this.state.toString());
        }
    }

    @Override
    public int onStartCommand(Intent intent, int i2, int i3) {
        if (this.state == State.enforcing) {
            startForeground(1, getEnforcingNotification(-1, -1, -1));
        } else {
            startForeground(2, getWaitingNotification());
        }
        Log.i("NetGuard.Service", "Received " + intent);
        Util.logExtras(intent);
        if (intent != null && intent.hasExtra("Command") && intent.getSerializableExtra("Command") == Command.set) {
            set(intent);
            return 1;
        }
        getLock(this).acquire();
        boolean z2 = b.f(this).getBoolean("enabled", false);
        if (intent == null) {
            Log.i("NetGuard.Service", "Restart");
            intent = new Intent(this, ServiceSinkhole.class);
            intent.putExtra("Command", z2 ? Command.start : Command.stop);
        }
        if ("eu.faircode.netguard.HOUSE_HOLDING".equals(intent.getAction())) {
            intent.putExtra("Command", Command.householding);
        }
        if ("eu.faircode.netguard.WATCHDOG".equals(intent.getAction())) {
            intent.putExtra("Command", Command.watchdog);
        }
        Command command = (Command) intent.getSerializableExtra("Command");
        if (command == null) {
            intent.putExtra("Command", z2 ? Command.start : Command.stop);
        }
        String stringExtra = intent.getStringExtra("Reason");
        StringBuilder sb = new StringBuilder("Start intent=");
        sb.append(intent);
        sb.append(" command=");
        sb.append(command);
        sb.append(" reason=");
        sb.append(stringExtra);
        sb.append(" vpn=");
        sb.append(this.vpn != null);
        sb.append(" user=");
        sb.append(Process.myUid() / 100000);
        Log.i("NetGuard.Service", sb.toString());
        this.commandHandler.queue(intent);
        return 1;
    }
}