-
Notifications
You must be signed in to change notification settings - Fork 203
/
DaedalusVpnService.java
417 lines (375 loc) · 17.9 KB
/
DaedalusVpnService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package org.itxtech.daedalus.service;
import android.app.Notification;
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.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;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Daedalus Project
*
* @author iTX Technologies
* @link https://itxtech.org
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*/
public class DaedalusVpnService extends VpnService implements Runnable {
public static final String ACTION_ACTIVATE = "org.itxtech.daedalus.service.DaedalusVpnService.ACTION_ACTIVATE";
public static final String ACTION_DEACTIVATE = "org.itxtech.daedalus.service.DaedalusVpnService.ACTION_DEACTIVATE";
private static final int NOTIFICATION_ACTIVATED = 0;
private static final String TAG = "DaedalusVpnService";
private static final String CHANNEL_ID = "daedalus_channel_1";
private static final String CHANNEL_NAME = "daedalus_channel";
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;
}
private static int getPendingIntent(int flag) {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_IMMUTABLE | flag : flag;
}
@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));
}
}
private 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
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
switch (intent.getAction()) {
case ACTION_ACTIVATE:
activated = true;
if (Daedalus.getPrefs().getBoolean("settings_notification", true)) {
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
manager.createNotificationChannel(channel);
builder = new NotificationCompat.Builder(this, CHANNEL_ID);
} else {
builder = new NotificationCompat.Builder(this);
}
Intent deactivateIntent = new Intent(StatusBarBroadcastReceiver.STATUS_BAR_BTN_DEACTIVATE_CLICK_ACTION);
deactivateIntent.setClass(this, StatusBarBroadcastReceiver.class);
Intent settingsIntent = new Intent(StatusBarBroadcastReceiver.STATUS_BAR_BTN_SETTINGS_CLICK_ACTION);
settingsIntent.setClass(this, StatusBarBroadcastReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), getPendingIntent(PendingIntent.FLAG_UPDATE_CURRENT));
builder.setWhen(0)
.setContentTitle(getResources().getString(R.string.notice_activated))
.setDefaults(NotificationCompat.DEFAULT_LIGHTS)
.setSmallIcon(R.drawable.ic_security)
.setColor(getResources().getColor(R.color.colorPrimary)) //backward compatibility
.setAutoCancel(false)
.setOngoing(true)
.setTicker(getResources().getString(R.string.notice_activated))
.setContentIntent(pIntent)
.addAction(R.drawable.ic_clear, getResources().getString(R.string.button_text_deactivate),
PendingIntent.getBroadcast(this, 0,
deactivateIntent, getPendingIntent(PendingIntent.FLAG_UPDATE_CURRENT)))
.addAction(R.drawable.ic_settings, getResources().getString(R.string.action_settings),
PendingIntent.getBroadcast(this, 0,
settingsIntent, getPendingIntent(PendingIntent.FLAG_UPDATE_CURRENT)));
Notification notification = builder.build();
manager.notify(NOTIFICATION_ACTIVATED, notification);
this.notification = builder;
}
Daedalus.initRuleResolver();
startThread();
Daedalus.updateShortcut(getApplicationContext());
if (MainActivity.getInstance() != null) {
MainActivity.getInstance().startActivity(new Intent(getApplicationContext(), MainActivity.class)
.putExtra(MainActivity.LAUNCH_ACTION, MainActivity.LAUNCH_ACTION_SERVICE_DONE));
}
return START_STICKY;
case ACTION_DEACTIVATE:
stopThread();
return START_NOT_STICKY;
}
}
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);
receiver = null;
}
}
private void stopThread() {
Log.d(TAG, "stopThread");
activated = false;
boolean shouldRefresh = false;
try {
if (this.descriptor != null) {
this.descriptor.close();
this.descriptor = null;
}
if (mThread != null) {
running = false;
shouldRefresh = true;
if (provider != null) {
provider.shutdown();
mThread.interrupt();
provider.stop();
} else {
mThread.interrupt();
}
mThread = null;
}
if (notification != null) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ACTIVATED);
notification = null;
}
dnsServers = null;
} catch (Exception e) {
Logger.logException(e);
}
stopSelf();
if (shouldRefresh) {
RuleResolver.clear();
DnsServerHelper.clearCache();
Logger.info("Daedalus VPN service has stopped");
}
if (shouldRefresh && MainActivity.getInstance() != null) {
MainActivity.getInstance().startActivity(new Intent(getApplicationContext(), MainActivity.class)
.putExtra(MainActivity.LAUNCH_ACTION, MainActivity.LAUNCH_ACTION_SERVICE_DONE));
} else if (shouldRefresh) {
Daedalus.updateShortcut(getApplicationContext());
}
}
@Override
public void onRevoke() {
stopThread();
}
private InetAddress addDnsServer(Builder builder, String format, byte[] ipv6Template, AbstractDnsServer addr)
throws UnknownHostException {
int size = dnsServers.size();
size++;
if (addr.getAddress().contains("/")) {//https uri
String alias = String.format(format, size + 1);
dnsServers.put(alias, addr);
builder.addRoute(alias, 32);
return InetAddress.getByName(alias);
}
InetAddress address = InetAddress.getByName(addr.getAddress());
if (address instanceof Inet6Address && ipv6Template == null) {
Log.i(TAG, "addDnsServer: Ignoring DNS server " + address);
} else if (address instanceof Inet4Address) {
String alias = String.format(format, size + 1);
addr.setHostAddress(address.getHostAddress());
dnsServers.put(alias, addr);
builder.addRoute(alias, 32);
return InetAddress.getByName(alias);
} else if (address instanceof Inet6Address) {
ipv6Template[ipv6Template.length - 1] = (byte) (size + 1);
InetAddress i6addr = Inet6Address.getByAddress(ipv6Template);
addr.setHostAddress(address.getHostAddress());
dnsServers.put(i6addr.getHostAddress(), addr);
return i6addr;
}
return null;
}
@Override
public void run() {
try {
DnsServerHelper.buildCache();
Builder builder = new Builder()
.setSession("Daedalus")
.setConfigureIntent(PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class).putExtra(MainActivity.LAUNCH_FRAGMENT, MainActivity.FRAGMENT_SETTINGS),
getPendingIntent(PendingIntent.FLAG_ONE_SHOT)));
if (Daedalus.getPrefs().getBoolean("settings_app_filter_switch", false)) {
ArrayList<String> apps = Daedalus.configurations.getAppObjects();
if (apps.size() > 0) {
boolean mode = Daedalus.getPrefs().getBoolean("settings_app_filter_mode_switch", false);
for (String app : apps) {
try {
if (mode) {
builder.addDisallowedApplication(app);
} else {
builder.addAllowedApplication(app);
}
Logger.debug("Added app to list: " + app);
} catch (PackageManager.NameNotFoundException e) {
Logger.error("Package Not Found:" + app);
}
}
}
}
String format = null;
for (String prefix : new String[]{"10.0.0", "192.0.2", "198.51.100", "203.0.113", "192.168.50"}) {
try {
builder.addAddress(prefix + ".1", 24);
} catch (IllegalArgumentException e) {
continue;
}
format = prefix + ".%d";
break;
}
boolean advanced = Daedalus.getPrefs().getBoolean("settings_advanced_switch", false);
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};
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;
}
if (advanced) {
dnsServers = new HashMap<>();
aliasPrimary = addDnsServer(builder, format, ipv6Template, primaryServer);
aliasSecondary = addDnsServer(builder, format, ipv6Template, secondaryServer);
} else {
aliasPrimary = InetAddress.getByName(primaryServer.getAddress());
aliasSecondary = InetAddress.getByName(secondaryServer.getAddress());
}
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) {
builder.setBlocking(true);
builder.allowFamily(OsConstants.AF_INET);
builder.allowFamily(OsConstants.AF_INET6);
}
descriptor = builder.establish();
Logger.info("Daedalus VPN service is started");
if (advanced) {
provider = ProviderPicker.getProvider(descriptor, this);
provider.start();
provider.process();
} else {
while (running) {
Thread.sleep(1000);
}
}
} 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 {
stopThread();
}
}
public void providerLoopCallback() {
if (statisticQuery) {
updateUserInterface();
}
}
private void updateUserInterface() {
long time = System.currentTimeMillis();
if (time - lastUpdate >= 1000) {
lastUpdate = time;
if (notification != null) {
notification.setContentTitle(getResources().getString(R.string.notice_queries) + " " + provider.getDnsQueryTimes());
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ACTIVATED, notification.build());
}
}
}
public static class VpnNetworkException extends Exception {
public VpnNetworkException(String s) {
super(s);
}
public VpnNetworkException(String s, Throwable t) {
super(s, t);
}
}
}