Skip to content

Commit

Permalink
DaedalusVpnService: listen network change and update upstream DNS
Browse files Browse the repository at this point in the history
  • Loading branch information
PeratX committed Oct 23, 2019
1 parent 000706a commit cb08d9d
Show file tree
Hide file tree
Showing 10 changed files with 123 additions and 87 deletions.
21 changes: 7 additions & 14 deletions app/src/main/java/org/itxtech/daedalus/Daedalus.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,14 @@
import com.google.gson.JsonParseException;
import com.google.gson.stream.JsonReader;
import org.itxtech.daedalus.activity.MainActivity;
import org.itxtech.daedalus.server.AbstractDnsServer;
import org.itxtech.daedalus.server.DnsServer;
import org.itxtech.daedalus.server.DnsServerHelper;
import org.itxtech.daedalus.service.DaedalusVpnService;
import org.itxtech.daedalus.util.*;
import org.itxtech.daedalus.util.Configurations;
import org.itxtech.daedalus.util.Logger;
import org.itxtech.daedalus.util.Rule;
import org.itxtech.daedalus.util.RuleResolver;

import java.io.File;
import java.util.ArrayList;
Expand Down Expand Up @@ -206,19 +210,8 @@ public static boolean prepareAndActivateService(Context context) {
}

public static void activateService(Context context) {
DaedalusVpnService.primaryServer = DnsServerHelper.getServerById(DnsServerHelper.getPrimary());
DaedalusVpnService.secondaryServer = DnsServerHelper.getServerById(DnsServerHelper.getSecondary());
if (getPrefs().getBoolean("settings_use_system_dns", false)) {
String[] servers = DnsServersDetector.getServers(context);
if (servers != null) {
if (servers.length >= 2) {
DaedalusVpnService.primaryServer = new DnsServer(servers[0], 0);
DaedalusVpnService.secondaryServer = new DnsServer(servers[1], 0);
} else {
DaedalusVpnService.primaryServer = DaedalusVpnService.secondaryServer = new DnsServer(servers[0]);
}
}
}
DaedalusVpnService.primaryServer = (AbstractDnsServer) DnsServerHelper.getServerById(DnsServerHelper.getPrimary()).clone();
DaedalusVpnService.secondaryServer = (AbstractDnsServer) DnsServerHelper.getServerById(DnsServerHelper.getSecondary()).clone();
if (getInstance().prefs.getBoolean("settings_foreground", false)
&& Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
Logger.info("Starting foreground service");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
add("secondary_server");
}}) {
ListPreference listPref = findPreference(k);
listPref.setVisible(visible);
listPref.setEntries(DnsServerHelper.getNames(Daedalus.getInstance()));
listPref.setEntryValues(DnsServerHelper.getIds());
listPref.setSummary(DnsServerHelper.getDescription(listPref.getValue(), Daedalus.getInstance()));
Expand Down Expand Up @@ -110,13 +109,6 @@ public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {

updateOptions(advanced.isChecked(), "settings_advanced");
updateOptions(appFilter.isChecked(), "settings_app_filter");

findPreference("settings_use_system_dns").setOnPreferenceChangeListener((preference, newValue) -> {
boolean vis = !(boolean) newValue;
findPreference("primary_server").setVisible(vis);
findPreference("secondary_server").setVisible(vis);
return true;
});
}

private void updateOptions(boolean checked, String pref) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.itxtech.daedalus.server;

import androidx.annotation.NonNull;

/**
* Daedalus Project
*
Expand All @@ -11,7 +13,7 @@
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*/
public class AbstractDnsServer {
public class AbstractDnsServer implements Cloneable {
public static final int DNS_SERVER_DEFAULT_PORT = 53;

protected String address;
Expand Down Expand Up @@ -63,4 +65,14 @@ public String getRealName() {
public boolean isHttpsServer() {
return address.contains("/");
}

@NonNull
@Override
public Object clone() {
try {
return super.clone();
} catch (Exception ignored) {
}
return new AbstractDnsServer("", 0);
}
}
116 changes: 81 additions & 35 deletions app/src/main/java/org/itxtech/daedalus/service/DaedalusVpnService.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,31 @@
import android.app.NotificationChannel;
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.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.VpnService;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.system.OsConstants;
import android.util.Log;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.NotificationCompat;
import org.itxtech.daedalus.Daedalus;
import org.itxtech.daedalus.R;
import org.itxtech.daedalus.activity.MainActivity;
import org.itxtech.daedalus.provider.Provider;
import org.itxtech.daedalus.provider.ProviderPicker;
import org.itxtech.daedalus.receiver.StatusBarBroadcastReceiver;
import org.itxtech.daedalus.util.Logger;
import org.itxtech.daedalus.util.RuleResolver;
import org.itxtech.daedalus.server.AbstractDnsServer;
import org.itxtech.daedalus.server.DnsServer;
import org.itxtech.daedalus.server.DnsServerHelper;
import org.itxtech.daedalus.util.DnsServersDetector;
import org.itxtech.daedalus.util.Logger;
import org.itxtech.daedalus.util.RuleResolver;

import java.net.Inet4Address;
import java.net.Inet6Address;
Expand Down Expand Up @@ -54,20 +60,19 @@ public class DaedalusVpnService extends VpnService implements Runnable {

public static AbstractDnsServer primaryServer;
public static AbstractDnsServer secondaryServer;
private static InetAddress aliasPrimary;
private static InetAddress aliasSecondary;

private NotificationCompat.Builder notification = null;

private boolean running = false;
private long lastUpdate = 0;
private boolean statisticQuery;
private Provider provider;
private ParcelFileDescriptor descriptor;

private Thread mThread = null;

public HashMap<String, AbstractDnsServer> dnsServers;

private static boolean activated = false;
private static BroadcastReceiver receiver;

public static boolean isActivated() {
return activated;
Expand All @@ -76,6 +81,44 @@ public static boolean isActivated() {
@Override
public void onCreate() {
super.onCreate();
if (Daedalus.getPrefs().getBoolean("settings_use_system_dns", false)) {
registerReceiver(receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateUpstreamServers(context);
}
}, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}

public static void updateUpstreamServers(Context context) {
String[] servers = DnsServersDetector.getServers(context);
if (servers != null) {
if (servers.length >= 2 && (aliasPrimary == null || !aliasPrimary.getHostAddress().equals(servers[0])) &&
(aliasSecondary == null || !aliasSecondary.getHostAddress().equals(servers[0])) &&
(aliasPrimary == null || !aliasPrimary.getHostAddress().equals(servers[1])) &&
(aliasSecondary == null || !aliasSecondary.getHostAddress().equals(servers[1]))) {
primaryServer.setAddress(servers[0]);
primaryServer.setPort(DnsServer.DNS_SERVER_DEFAULT_PORT);
secondaryServer.setAddress(servers[1]);
secondaryServer.setPort(DnsServer.DNS_SERVER_DEFAULT_PORT);
} else if ((aliasPrimary == null || !aliasPrimary.getHostAddress().equals(servers[0])) &&
(aliasSecondary == null || !aliasSecondary.getHostAddress().equals(servers[0]))) {
primaryServer.setAddress(servers[0]);
primaryServer.setPort(DnsServer.DNS_SERVER_DEFAULT_PORT);
secondaryServer.setAddress(servers[0]);
secondaryServer.setPort(DnsServer.DNS_SERVER_DEFAULT_PORT);
} else {
StringBuilder buf = new StringBuilder();
for (String server : servers) {
buf.append(server).append(" ");
}
Logger.error("Invalid upstream DNS " + buf);
}
Logger.info("Upstream DNS updated: " + primaryServer.getAddress() + " " + secondaryServer.getAddress());
} else {
Logger.error("Cannot obtain upstream DNS server!");
}
}

@Override
Expand All @@ -85,7 +128,6 @@ public int onStartCommand(Intent intent, int flags, int startId) {
case ACTION_ACTIVATE:
activated = true;
if (Daedalus.getPrefs().getBoolean("settings_notification", true)) {

NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

NotificationCompat.Builder builder;
Expand Down Expand Up @@ -127,12 +169,7 @@ public int onStartCommand(Intent intent, int flags, int startId) {
}

Daedalus.initRuleResolver();

if (this.mThread == null) {
this.mThread = new Thread(this, "DaedalusVpn");
this.running = true;
this.mThread.start();
}
startThread();
Daedalus.updateShortcut(getApplicationContext());
if (MainActivity.getInstance() != null) {
MainActivity.getInstance().startActivity(new Intent(getApplicationContext(), MainActivity.class)
Expand All @@ -147,9 +184,20 @@ public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}

private void startThread() {
if (this.mThread == null) {
this.mThread = new Thread(this, "DaedalusVpn");
this.running = true;
this.mThread.start();
}
}

@Override
public void onDestroy() {
stopThread();
if (receiver != null) {
unregisterReceiver(receiver);
}
}

private void stopThread() {
Expand Down Expand Up @@ -203,7 +251,8 @@ public void onRevoke() {
stopThread();
}

private InetAddress addDnsServer(Builder builder, String format, byte[] ipv6Template, AbstractDnsServer addr) throws UnknownHostException {
private InetAddress addDnsServer(Builder builder, String format, byte[] ipv6Template, AbstractDnsServer addr)
throws UnknownHostException {
int size = dnsServers.size();
size++;
if (addr.getAddress().contains("/")) {//https uri
Expand Down Expand Up @@ -241,7 +290,6 @@ public void run() {
new Intent(this, MainActivity.class).putExtra(MainActivity.LAUNCH_FRAGMENT, MainActivity.FRAGMENT_SETTINGS),
PendingIntent.FLAG_ONE_SHOT));

//Set App Filter
if (Daedalus.getPrefs().getBoolean("settings_app_filter_switch", false)) {
ArrayList<String> apps = Daedalus.configurations.getAppObjects();
if (apps.size() > 0) {
Expand Down Expand Up @@ -278,22 +326,16 @@ public void run() {
statisticQuery = Daedalus.getPrefs().getBoolean("settings_count_query_times", false);
byte[] ipv6Template = new byte[]{32, 1, 13, (byte) (184 & 0xFF), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

if (primaryServer.getAddress().contains(":") || secondaryServer.getAddress().contains(":")) {//IPv6
try {
InetAddress addr = Inet6Address.getByAddress(ipv6Template);
Log.d(TAG, "configure: Adding IPv6 address" + addr);
builder.addAddress(addr, 120);
} catch (Exception e) {
Logger.logException(e);
try {
InetAddress addr = Inet6Address.getByAddress(ipv6Template);
Log.d(TAG, "configure: Adding IPv6 address" + addr);
builder.addAddress(addr, 120);
} catch (Exception e) {
Logger.logException(e);

ipv6Template = null;
}
} else {
ipv6Template = null;
}

InetAddress aliasPrimary;
InetAddress aliasSecondary;
if (advanced) {
dnsServers = new HashMap<>();
aliasPrimary = addDnsServer(builder, format, ipv6Template, primaryServer);
Expand All @@ -303,8 +345,8 @@ public void run() {
aliasSecondary = InetAddress.getByName(secondaryServer.getAddress());
}

Logger.info("Daedalus VPN service is listening on " + primaryServer + " as " + aliasPrimary.getHostAddress());
Logger.info("Daedalus VPN service is listening on " + secondaryServer + " as " + aliasSecondary.getHostAddress());
Logger.info("Daedalus VPN service is listening on " + primaryServer.getAddress() + " as " + aliasPrimary.getHostAddress());
Logger.info("Daedalus VPN service is listening on " + secondaryServer.getAddress() + " as " + aliasSecondary.getHostAddress());
builder.addDnsServer(aliasPrimary).addDnsServer(aliasSecondary);

if (advanced) {
Expand All @@ -325,13 +367,17 @@ public void run() {
Thread.sleep(1000);
}
}
} catch (
InterruptedException ignored) {
} catch (
Exception e) {
} catch (InterruptedException ignored) {
} catch (Exception e) {
MainActivity.getInstance().runOnUiThread(() ->
new AlertDialog.Builder(MainActivity.getInstance())
.setTitle(R.string.error_occurred)
.setMessage(Logger.getExceptionMessage(e))
.setPositiveButton(android.R.string.ok, (d, id) -> {
})
.show());
Logger.logException(e);
} finally {
Log.d(TAG, "quit");
stopThread();
}
}
Expand All @@ -354,11 +400,11 @@ private void updateUserInterface() {
}
}


public static class VpnNetworkException extends Exception {
public VpnNetworkException(String s) {
super(s);
}

public VpnNetworkException(String s, Throwable t) {
super(s, t);
}
Expand Down
20 changes: 0 additions & 20 deletions app/src/main/res/values-v21/styles.xml

This file was deleted.

2 changes: 2 additions & 0 deletions app/src/main/res/values-zh-rCN/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,6 @@
<string name="test_test_domain">google.com</string>

<string name="nav_version">版本:</string>

<string name="error_occurred">启动时出现了一个错误</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values-zh-rTW/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,6 @@
<string name="test_test_domain">google.com</string>

<string name="nav_version">版本:</string>

<string name="error_occurred">啟動時出現了一個錯誤</string>
</resources>
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,6 @@
<string name="nav_version">Version:</string>
<string name="nav_git_commit">Git commit:</string>
<string name="nav_github">GitHub</string>

<string name="error_occurred">An error occurred at startup</string>
</resources>
Loading

0 comments on commit cb08d9d

Please sign in to comment.