mirror of
https://code.briarproject.org/briar/briar.git
synced 2026-02-13 03:09:04 +01:00
Compare commits
198 Commits
1712-passi
...
limit-in-m
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
327e12e9f8 | ||
|
|
4e5f2e31df | ||
|
|
518c0370c8 | ||
|
|
7ef2fb5f0c | ||
|
|
1210b27bd1 | ||
|
|
cdf1a4abcd | ||
|
|
b18ef7e72d | ||
|
|
48d907dda5 | ||
|
|
3e5b7f451a | ||
|
|
95cccd1d15 | ||
|
|
0a33c77393 | ||
|
|
80caa7634a | ||
|
|
2a8778d3cc | ||
|
|
2cf146a104 | ||
|
|
a1e3c81bda | ||
|
|
bbcb183c24 | ||
|
|
7fcb3394ca | ||
|
|
4310e4d1af | ||
|
|
82e85bdb39 | ||
|
|
5ba0728abc | ||
|
|
46bdb3589c | ||
|
|
392bc0d339 | ||
|
|
02cf6bfcaa | ||
|
|
08a8a0b281 | ||
|
|
b189a38f62 | ||
|
|
57b0641e5f | ||
|
|
5b5d513316 | ||
|
|
6684fb2e1b | ||
|
|
73c6a29ede | ||
|
|
a8fe0a01ac | ||
|
|
c75c8da4b9 | ||
|
|
2f3f3d256c | ||
|
|
1141d01dc7 | ||
|
|
e06eee2358 | ||
|
|
c37fe2a246 | ||
|
|
79ad5ca07e | ||
|
|
0e2d905486 | ||
|
|
6094014487 | ||
|
|
9603ff93e9 | ||
|
|
e7ac6aef8c | ||
|
|
4e18115d88 | ||
|
|
b57fb9c842 | ||
|
|
196a2b7e22 | ||
|
|
37712203d7 | ||
|
|
cc67237893 | ||
|
|
79f3a77e1a | ||
|
|
3ecec61c25 | ||
|
|
1e2dc862ef | ||
|
|
452c3afbb3 | ||
|
|
9d60fbe957 | ||
|
|
434b8a37f3 | ||
|
|
5e6a382b4b | ||
|
|
b5bb4aff7f | ||
|
|
b0bf9d5a8c | ||
|
|
1e6fd8bb74 | ||
|
|
eac93f43d3 | ||
|
|
23f22af6e4 | ||
|
|
6e8e955dc2 | ||
|
|
2e2bc2d82f | ||
|
|
1af951f8b4 | ||
|
|
086c10abc0 | ||
|
|
b5341700be | ||
|
|
d8be340120 | ||
|
|
7e0d21de38 | ||
|
|
1bab15baaf | ||
|
|
af1a91c819 | ||
|
|
e6c3f82fe2 | ||
|
|
b2840c1b00 | ||
|
|
942bb28701 | ||
|
|
94dd0a2661 | ||
|
|
3aa00ecb3d | ||
|
|
d5395d3d01 | ||
|
|
b6b721e3b1 | ||
|
|
7cdd05fd67 | ||
|
|
286f6f492c | ||
|
|
eb6b4aa850 | ||
|
|
adb657a5b6 | ||
|
|
d794777eb2 | ||
|
|
090123579d | ||
|
|
f1bde4e75c | ||
|
|
ac80a90ef3 | ||
|
|
dfefb88b32 | ||
|
|
86641741a0 | ||
|
|
280f87065e | ||
|
|
cbe645a4a3 | ||
|
|
f4e9e10245 | ||
|
|
e9f78bc486 | ||
|
|
a4091be6f7 | ||
|
|
49f0640278 | ||
|
|
d617e67006 | ||
|
|
2063f6c57c | ||
|
|
f68d8d284f | ||
|
|
3c63fecb5d | ||
|
|
41fdd584ad | ||
|
|
1b37dceb28 | ||
|
|
c183ca0340 | ||
|
|
90e91221d9 | ||
|
|
b91fe66461 | ||
|
|
b5ab077afa | ||
|
|
496d4188c7 | ||
|
|
ab682c82a3 | ||
|
|
375a7276ad | ||
|
|
b7084b2486 | ||
|
|
aa152a80d1 | ||
|
|
3f0d9233d9 | ||
|
|
9d96ce6db0 | ||
|
|
45fb5bb445 | ||
|
|
0756d92ca1 | ||
|
|
37f80c7682 | ||
|
|
b409215c57 | ||
|
|
4f0aaf03fd | ||
|
|
597fef6d50 | ||
|
|
c1d0936a1e | ||
|
|
717be0178a | ||
|
|
34677eb3a7 | ||
|
|
1dd15567de | ||
|
|
428f06abdd | ||
|
|
e1d1c62708 | ||
|
|
ae75090d23 | ||
|
|
443043ae09 | ||
|
|
fb85730b8e | ||
|
|
48b1e77065 | ||
|
|
a03953563f | ||
|
|
033fd2d3b4 | ||
|
|
011d8e1df7 | ||
|
|
ef5e2dad72 | ||
|
|
f35e87c8ad | ||
|
|
e4940a046a | ||
|
|
0a666df164 | ||
|
|
6fb4b95b18 | ||
|
|
5567982fb4 | ||
|
|
25e50ceb10 | ||
|
|
1495daf977 | ||
|
|
badc6da649 | ||
|
|
e065d45d16 | ||
|
|
d0c53f1310 | ||
|
|
e1084ffadd | ||
|
|
2bd2f67693 | ||
|
|
c2b0a4b8d1 | ||
|
|
ee19d2f574 | ||
|
|
e9ec5734e2 | ||
|
|
7b1c6f3fdd | ||
|
|
d689cf776c | ||
|
|
f0fd1844dd | ||
|
|
d16a301fc4 | ||
|
|
3ab88181eb | ||
|
|
802e599f09 | ||
|
|
a6bd59d3c9 | ||
|
|
b04b724028 | ||
|
|
71b0408fe6 | ||
|
|
2d38bd5734 | ||
|
|
ff5da8404a | ||
|
|
75615a4e7f | ||
|
|
96e32ad64e | ||
|
|
0fec5d7783 | ||
|
|
ee74b3774b | ||
|
|
c783a2f352 | ||
|
|
77aa5401f3 | ||
|
|
99686f5316 | ||
|
|
f5b4f6e071 | ||
|
|
a2de841e6a | ||
|
|
1f94c2d4e8 | ||
|
|
413ce29c0c | ||
|
|
c67f758c90 | ||
|
|
339524500b | ||
|
|
03811f78fa | ||
|
|
fc86c46456 | ||
|
|
7ae86d70af | ||
|
|
63e3c661a3 | ||
|
|
4f54bd90fb | ||
|
|
706c03aa8b | ||
|
|
c42a987927 | ||
|
|
297dbe0b16 | ||
|
|
4130662e1f | ||
|
|
c08bdf96cd | ||
|
|
8bb534564f | ||
|
|
5e60a717fc | ||
|
|
dd1509350c | ||
|
|
465ba3d337 | ||
|
|
7561c5039e | ||
|
|
242d6f8a0e | ||
|
|
c554847b54 | ||
|
|
d30b250389 | ||
|
|
ecea2c587d | ||
|
|
43a91e2e57 | ||
|
|
ea288b998b | ||
|
|
48dc598ca3 | ||
|
|
e2d63ac6a4 | ||
|
|
afc85cdf52 | ||
|
|
b2a1ea84f8 | ||
|
|
fcc26c093b | ||
|
|
5a741bf13b | ||
|
|
5dc460851b | ||
|
|
b805514f70 | ||
|
|
69d94c9f29 | ||
|
|
53d4b7a0df | ||
|
|
dcb5f95934 | ||
|
|
ff8a422638 |
3
.idea/codeStyles/Project.xml
generated
3
.idea/codeStyles/Project.xml
generated
@@ -1,8 +1,5 @@
|
|||||||
<component name="ProjectCodeStyleConfiguration">
|
<component name="ProjectCodeStyleConfiguration">
|
||||||
<code_scheme name="Project" version="173">
|
<code_scheme name="Project" version="173">
|
||||||
<AndroidXmlCodeStyleSettings>
|
|
||||||
<option name="ARRANGEMENT_SETTINGS_MIGRATED_TO_191" value="true" />
|
|
||||||
</AndroidXmlCodeStyleSettings>
|
|
||||||
<JavaCodeStyleSettings>
|
<JavaCodeStyleSettings>
|
||||||
<option name="ANNOTATION_PARAMETER_WRAP" value="1" />
|
<option name="ANNOTATION_PARAMETER_WRAP" value="1" />
|
||||||
<option name="IMPORT_LAYOUT_TABLE">
|
<option name="IMPORT_LAYOUT_TABLE">
|
||||||
|
|||||||
9
TRANSLATION.md
Normal file
9
TRANSLATION.md
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
Translations for this project are managed through Transifex:
|
||||||
|
|
||||||
|
https://transifex.com/otf/briar
|
||||||
|
|
||||||
|
If you'd like to volunteer as a translator, please create a Transifex account and request to be
|
||||||
|
added to the project's translation team. The Localization Lab has some instructions and advice for
|
||||||
|
translators here:
|
||||||
|
|
||||||
|
https://wiki.localizationlab.org/index.php/Briar
|
||||||
@@ -11,8 +11,8 @@ android {
|
|||||||
defaultConfig {
|
defaultConfig {
|
||||||
minSdkVersion 16
|
minSdkVersion 16
|
||||||
targetSdkVersion 28
|
targetSdkVersion 28
|
||||||
versionCode 10207
|
versionCode 10209
|
||||||
versionName "1.2.7"
|
versionName "1.2.9"
|
||||||
consumerProguardFiles 'proguard-rules.txt'
|
consumerProguardFiles 'proguard-rules.txt'
|
||||||
|
|
||||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
android:label="@string/app_name"
|
android:label="@string/app_name"
|
||||||
android:supportsRtl="true">
|
android:supportsRtl="true">
|
||||||
|
|
||||||
|
<receiver android:name=".system.AlarmReceiver" />
|
||||||
|
|
||||||
</application>
|
</application>
|
||||||
|
|
||||||
</manifest>
|
</manifest>
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import org.briarproject.bramble.plugin.tor.CircumventionModule;
|
|||||||
import org.briarproject.bramble.reporting.ReportingModule;
|
import org.briarproject.bramble.reporting.ReportingModule;
|
||||||
import org.briarproject.bramble.socks.SocksModule;
|
import org.briarproject.bramble.socks.SocksModule;
|
||||||
import org.briarproject.bramble.system.AndroidSystemModule;
|
import org.briarproject.bramble.system.AndroidSystemModule;
|
||||||
|
import org.briarproject.bramble.system.AndroidTaskSchedulerModule;
|
||||||
|
import org.briarproject.bramble.system.AndroidWakefulIoExecutorModule;
|
||||||
|
|
||||||
import dagger.Module;
|
import dagger.Module;
|
||||||
|
|
||||||
@@ -13,6 +15,8 @@ import dagger.Module;
|
|||||||
AndroidBatteryModule.class,
|
AndroidBatteryModule.class,
|
||||||
AndroidNetworkModule.class,
|
AndroidNetworkModule.class,
|
||||||
AndroidSystemModule.class,
|
AndroidSystemModule.class,
|
||||||
|
AndroidTaskSchedulerModule.class,
|
||||||
|
AndroidWakefulIoExecutorModule.class,
|
||||||
CircumventionModule.class,
|
CircumventionModule.class,
|
||||||
ReportingModule.class,
|
ReportingModule.class,
|
||||||
SocksModule.class
|
SocksModule.class
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package org.briarproject.bramble;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.system.AlarmListener;
|
||||||
|
|
||||||
|
public interface BrambleAppComponent {
|
||||||
|
|
||||||
|
AlarmListener alarmListener();
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package org.briarproject.bramble;
|
||||||
|
|
||||||
|
public interface BrambleApplication {
|
||||||
|
|
||||||
|
BrambleAppComponent getBrambleAppComponent();
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package org.briarproject.bramble.api.system;
|
||||||
|
|
||||||
|
import android.content.Intent;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
|
||||||
|
@NotNullByDefault
|
||||||
|
public interface AlarmListener {
|
||||||
|
|
||||||
|
void onAlarm(Intent intent);
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package org.briarproject.bramble.api.system;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
|
||||||
|
@NotNullByDefault
|
||||||
|
public interface AndroidWakeLock {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Acquires the wake lock. This has no effect if the wake lock has already
|
||||||
|
* been acquired.
|
||||||
|
*/
|
||||||
|
void acquire();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Releases the wake lock. This has no effect if the wake lock has already
|
||||||
|
* been released.
|
||||||
|
*/
|
||||||
|
void release();
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package org.briarproject.bramble.api.system;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
|
@NotNullByDefault
|
||||||
|
public interface AndroidWakeLockManager {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a wake lock with the given tag. The tag is only used for
|
||||||
|
* logging; the underlying OS wake lock will use its own tag.
|
||||||
|
*/
|
||||||
|
AndroidWakeLock createWakeLock(String tag);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs the given task while holding a wake lock.
|
||||||
|
*/
|
||||||
|
void runWakefully(Runnable r, String tag);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Submits the given task to the given executor while holding a wake lock.
|
||||||
|
* The lock is released when the task completes, or if an exception is
|
||||||
|
* thrown while submitting or running the task.
|
||||||
|
*/
|
||||||
|
void executeWakefully(Runnable r, Executor executor, String tag);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts a dedicated thread to run the given task asynchronously. A wake
|
||||||
|
* lock is acquired before starting the thread and released when the task
|
||||||
|
* completes, or if an exception is thrown while starting the thread or
|
||||||
|
* running the task.
|
||||||
|
* <p>
|
||||||
|
* This method should only be used for lifecycle management tasks that
|
||||||
|
* can't be run on an executor.
|
||||||
|
*/
|
||||||
|
void executeWakefully(Runnable r, String tag);
|
||||||
|
}
|
||||||
@@ -9,16 +9,17 @@ import android.net.ConnectivityManager;
|
|||||||
import android.net.NetworkInfo;
|
import android.net.NetworkInfo;
|
||||||
|
|
||||||
import org.briarproject.bramble.api.event.EventBus;
|
import org.briarproject.bramble.api.event.EventBus;
|
||||||
|
import org.briarproject.bramble.api.event.EventExecutor;
|
||||||
import org.briarproject.bramble.api.lifecycle.Service;
|
import org.briarproject.bramble.api.lifecycle.Service;
|
||||||
import org.briarproject.bramble.api.network.NetworkManager;
|
import org.briarproject.bramble.api.network.NetworkManager;
|
||||||
import org.briarproject.bramble.api.network.NetworkStatus;
|
import org.briarproject.bramble.api.network.NetworkStatus;
|
||||||
import org.briarproject.bramble.api.network.event.NetworkStatusEvent;
|
import org.briarproject.bramble.api.network.event.NetworkStatusEvent;
|
||||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||||
import org.briarproject.bramble.api.system.Scheduler;
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler.Cancellable;
|
||||||
|
|
||||||
import java.util.concurrent.Future;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
@@ -50,20 +51,22 @@ class AndroidNetworkManager implements NetworkManager, Service {
|
|||||||
private static final String WIFI_AP_STATE_CHANGED_ACTION =
|
private static final String WIFI_AP_STATE_CHANGED_ACTION =
|
||||||
"android.net.wifi.WIFI_AP_STATE_CHANGED";
|
"android.net.wifi.WIFI_AP_STATE_CHANGED";
|
||||||
|
|
||||||
private final ScheduledExecutorService scheduler;
|
private final TaskScheduler scheduler;
|
||||||
private final EventBus eventBus;
|
private final EventBus eventBus;
|
||||||
|
private final Executor eventExecutor;
|
||||||
private final Context appContext;
|
private final Context appContext;
|
||||||
private final AtomicReference<Future<?>> connectivityCheck =
|
private final AtomicReference<Cancellable> connectivityCheck =
|
||||||
new AtomicReference<>();
|
new AtomicReference<>();
|
||||||
private final AtomicBoolean used = new AtomicBoolean(false);
|
private final AtomicBoolean used = new AtomicBoolean(false);
|
||||||
|
|
||||||
private volatile BroadcastReceiver networkStateReceiver = null;
|
private volatile BroadcastReceiver networkStateReceiver = null;
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
AndroidNetworkManager(@Scheduler ScheduledExecutorService scheduler,
|
AndroidNetworkManager(TaskScheduler scheduler, EventBus eventBus,
|
||||||
EventBus eventBus, Application app) {
|
@EventExecutor Executor eventExecutor, Application app) {
|
||||||
this.scheduler = scheduler;
|
this.scheduler = scheduler;
|
||||||
this.eventBus = eventBus;
|
this.eventBus = eventBus;
|
||||||
|
this.eventExecutor = eventExecutor;
|
||||||
this.appContext = app.getApplicationContext();
|
this.appContext = app.getApplicationContext();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,11 +107,12 @@ class AndroidNetworkManager implements NetworkManager, Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void scheduleConnectionStatusUpdate(int delay, TimeUnit unit) {
|
private void scheduleConnectionStatusUpdate(int delay, TimeUnit unit) {
|
||||||
Future<?> newConnectivityCheck =
|
Cancellable newConnectivityCheck =
|
||||||
scheduler.schedule(this::updateConnectionStatus, delay, unit);
|
scheduler.schedule(this::updateConnectionStatus, eventExecutor,
|
||||||
Future<?> oldConnectivityCheck =
|
delay, unit);
|
||||||
|
Cancellable oldConnectivityCheck =
|
||||||
connectivityCheck.getAndSet(newConnectivityCheck);
|
connectivityCheck.getAndSet(newConnectivityCheck);
|
||||||
if (oldConnectivityCheck != null) oldConnectivityCheck.cancel(false);
|
if (oldConnectivityCheck != null) oldConnectivityCheck.cancel();
|
||||||
}
|
}
|
||||||
|
|
||||||
private class NetworkStateReceiver extends BroadcastReceiver {
|
private class NetworkStateReceiver extends BroadcastReceiver {
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package org.briarproject.bramble.plugin.bluetooth;
|
||||||
|
|
||||||
|
import android.bluetooth.BluetoothSocket;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||||
|
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@NotNullByDefault
|
||||||
|
class AndroidBluetoothConnectionFactory
|
||||||
|
implements BluetoothConnectionFactory<BluetoothSocket> {
|
||||||
|
|
||||||
|
private final BluetoothConnectionLimiter connectionLimiter;
|
||||||
|
private final AndroidWakeLockManager wakeLockManager;
|
||||||
|
private final TimeoutMonitor timeoutMonitor;
|
||||||
|
|
||||||
|
AndroidBluetoothConnectionFactory(
|
||||||
|
BluetoothConnectionLimiter connectionLimiter,
|
||||||
|
AndroidWakeLockManager wakeLockManager,
|
||||||
|
TimeoutMonitor timeoutMonitor) {
|
||||||
|
this.connectionLimiter = connectionLimiter;
|
||||||
|
this.wakeLockManager = wakeLockManager;
|
||||||
|
this.timeoutMonitor = timeoutMonitor;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public DuplexTransportConnection wrapSocket(DuplexPlugin plugin,
|
||||||
|
BluetoothSocket s) throws IOException {
|
||||||
|
return new AndroidBluetoothTransportConnection(plugin,
|
||||||
|
connectionLimiter, wakeLockManager, timeoutMonitor, s);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package org.briarproject.bramble.plugin.bluetooth;
|
package org.briarproject.bramble.plugin.bluetooth;
|
||||||
|
|
||||||
|
import android.app.Application;
|
||||||
import android.bluetooth.BluetoothAdapter;
|
import android.bluetooth.BluetoothAdapter;
|
||||||
import android.bluetooth.BluetoothDevice;
|
import android.bluetooth.BluetoothDevice;
|
||||||
import android.bluetooth.BluetoothServerSocket;
|
import android.bluetooth.BluetoothServerSocket;
|
||||||
@@ -9,7 +10,6 @@ import android.content.Context;
|
|||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
import android.content.IntentFilter;
|
import android.content.IntentFilter;
|
||||||
|
|
||||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
|
||||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
@@ -59,7 +59,8 @@ import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress;
|
|||||||
|
|
||||||
@MethodsNotNullByDefault
|
@MethodsNotNullByDefault
|
||||||
@ParametersNotNullByDefault
|
@ParametersNotNullByDefault
|
||||||
class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
class AndroidBluetoothPlugin
|
||||||
|
extends BluetoothPlugin<BluetoothSocket, BluetoothServerSocket> {
|
||||||
|
|
||||||
private static final Logger LOG =
|
private static final Logger LOG =
|
||||||
getLogger(AndroidBluetoothPlugin.class.getName());
|
getLogger(AndroidBluetoothPlugin.class.getName());
|
||||||
@@ -67,24 +68,31 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
|||||||
private static final int MAX_DISCOVERY_MS = 10_000;
|
private static final int MAX_DISCOVERY_MS = 10_000;
|
||||||
|
|
||||||
private final AndroidExecutor androidExecutor;
|
private final AndroidExecutor androidExecutor;
|
||||||
private final Context appContext;
|
private final Application app;
|
||||||
private final Clock clock;
|
private final Clock clock;
|
||||||
|
|
||||||
private volatile boolean wasEnabledByUs = false;
|
|
||||||
private volatile BluetoothStateReceiver receiver = null;
|
private volatile BluetoothStateReceiver receiver = null;
|
||||||
|
|
||||||
// Non-null if the plugin started successfully
|
// Non-null if the plugin started successfully
|
||||||
private volatile BluetoothAdapter adapter = null;
|
private volatile BluetoothAdapter adapter = null;
|
||||||
|
|
||||||
AndroidBluetoothPlugin(BluetoothConnectionLimiter connectionLimiter,
|
AndroidBluetoothPlugin(BluetoothConnectionLimiter connectionLimiter,
|
||||||
TimeoutMonitor timeoutMonitor, Executor ioExecutor,
|
BluetoothConnectionFactory<BluetoothSocket> connectionFactory,
|
||||||
SecureRandom secureRandom, AndroidExecutor androidExecutor,
|
Executor ioExecutor,
|
||||||
Context appContext, Clock clock, Backoff backoff,
|
Executor wakefulIoExecutor,
|
||||||
PluginCallback callback, int maxLatency, int maxIdleTime) {
|
SecureRandom secureRandom,
|
||||||
super(connectionLimiter, timeoutMonitor, ioExecutor, secureRandom,
|
AndroidExecutor androidExecutor,
|
||||||
backoff, callback, maxLatency, maxIdleTime);
|
Application app,
|
||||||
|
Clock clock,
|
||||||
|
Backoff backoff,
|
||||||
|
PluginCallback callback,
|
||||||
|
int maxLatency,
|
||||||
|
int maxIdleTime) {
|
||||||
|
super(connectionLimiter, connectionFactory, ioExecutor,
|
||||||
|
wakefulIoExecutor, secureRandom, backoff, callback,
|
||||||
|
maxLatency, maxIdleTime);
|
||||||
this.androidExecutor = androidExecutor;
|
this.androidExecutor = androidExecutor;
|
||||||
this.appContext = appContext;
|
this.app = app;
|
||||||
this.clock = clock;
|
this.clock = clock;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,13 +104,13 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
|||||||
filter.addAction(ACTION_STATE_CHANGED);
|
filter.addAction(ACTION_STATE_CHANGED);
|
||||||
filter.addAction(ACTION_SCAN_MODE_CHANGED);
|
filter.addAction(ACTION_SCAN_MODE_CHANGED);
|
||||||
receiver = new BluetoothStateReceiver();
|
receiver = new BluetoothStateReceiver();
|
||||||
appContext.registerReceiver(receiver, filter);
|
app.registerReceiver(receiver, filter);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void stop() {
|
public void stop() {
|
||||||
super.stop();
|
super.stop();
|
||||||
if (receiver != null) appContext.unregisterReceiver(receiver);
|
if (receiver != null) app.unregisterReceiver(receiver);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -124,36 +132,10 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
|||||||
return adapter != null && adapter.isEnabled();
|
return adapter != null && adapter.isEnabled();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
void enableAdapter() {
|
|
||||||
if (adapter != null && !adapter.isEnabled()) {
|
|
||||||
if (adapter.enable()) {
|
|
||||||
LOG.info("Enabling Bluetooth");
|
|
||||||
wasEnabledByUs = true;
|
|
||||||
} else {
|
|
||||||
LOG.info("Could not enable Bluetooth");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
void disableAdapterIfEnabledByUs() {
|
|
||||||
if (isAdapterEnabled() && wasEnabledByUs) {
|
|
||||||
if (adapter.disable()) LOG.info("Disabling Bluetooth");
|
|
||||||
else LOG.info("Could not disable Bluetooth");
|
|
||||||
wasEnabledByUs = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
void setEnabledByUs() {
|
|
||||||
wasEnabledByUs = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Nullable
|
@Nullable
|
||||||
String getBluetoothAddress() {
|
String getBluetoothAddress() {
|
||||||
String address = AndroidUtils.getBluetoothAddress(appContext, adapter);
|
String address = AndroidUtils.getBluetoothAddress(app, adapter);
|
||||||
return address.isEmpty() ? null : address;
|
return address.isEmpty() ? null : address;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,13 +153,7 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
|||||||
@Override
|
@Override
|
||||||
DuplexTransportConnection acceptConnection(BluetoothServerSocket ss)
|
DuplexTransportConnection acceptConnection(BluetoothServerSocket ss)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
return wrapSocket(ss.accept());
|
return connectionFactory.wrapSocket(this, ss.accept());
|
||||||
}
|
|
||||||
|
|
||||||
private DuplexTransportConnection wrapSocket(BluetoothSocket s)
|
|
||||||
throws IOException {
|
|
||||||
return new AndroidBluetoothTransportConnection(this, connectionLimiter,
|
|
||||||
timeoutMonitor, s);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -194,7 +170,7 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
|||||||
try {
|
try {
|
||||||
s = d.createInsecureRfcommSocketToServiceRecord(u);
|
s = d.createInsecureRfcommSocketToServiceRecord(u);
|
||||||
s.connect();
|
s.connect();
|
||||||
return wrapSocket(s);
|
return connectionFactory.wrapSocket(this, s);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
IoUtils.tryToClose(s, LOG, WARNING);
|
IoUtils.tryToClose(s, LOG, WARNING);
|
||||||
throw e;
|
throw e;
|
||||||
@@ -229,7 +205,7 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
|||||||
filter.addAction(ACTION_DISCOVERY_STARTED);
|
filter.addAction(ACTION_DISCOVERY_STARTED);
|
||||||
filter.addAction(ACTION_DISCOVERY_FINISHED);
|
filter.addAction(ACTION_DISCOVERY_FINISHED);
|
||||||
filter.addAction(ACTION_FOUND);
|
filter.addAction(ACTION_FOUND);
|
||||||
appContext.registerReceiver(receiver, filter);
|
app.registerReceiver(receiver, filter);
|
||||||
try {
|
try {
|
||||||
if (adapter.startDiscovery()) {
|
if (adapter.startDiscovery()) {
|
||||||
long now = clock.currentTimeMillis();
|
long now = clock.currentTimeMillis();
|
||||||
@@ -266,7 +242,7 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
|||||||
} finally {
|
} finally {
|
||||||
LOG.info("Cancelling discovery");
|
LOG.info("Cancelling discovery");
|
||||||
adapter.cancelDiscovery();
|
adapter.cancelDiscovery();
|
||||||
appContext.unregisterReceiver(receiver);
|
app.unregisterReceiver(receiver);
|
||||||
}
|
}
|
||||||
// Shuffle the addresses so we don't always try the same one first
|
// Shuffle the addresses so we don't always try the same one first
|
||||||
shuffle(addresses);
|
shuffle(addresses);
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
package org.briarproject.bramble.plugin.bluetooth;
|
package org.briarproject.bramble.plugin.bluetooth;
|
||||||
|
|
||||||
import android.content.Context;
|
import android.app.Application;
|
||||||
|
import android.bluetooth.BluetoothSocket;
|
||||||
|
|
||||||
import org.briarproject.bramble.api.event.EventBus;
|
import org.briarproject.bramble.api.event.EventBus;
|
||||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||||
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
||||||
@@ -12,12 +14,15 @@ import org.briarproject.bramble.api.plugin.TransportId;
|
|||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||||
import org.briarproject.bramble.api.system.AndroidExecutor;
|
import org.briarproject.bramble.api.system.AndroidExecutor;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
|
import org.briarproject.bramble.api.system.WakefulIoExecutor;
|
||||||
|
|
||||||
import java.security.SecureRandom;
|
import java.security.SecureRandom;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
import javax.annotation.concurrent.Immutable;
|
import javax.annotation.concurrent.Immutable;
|
||||||
|
import javax.inject.Inject;
|
||||||
|
|
||||||
import static org.briarproject.bramble.api.plugin.BluetoothConstants.ID;
|
import static org.briarproject.bramble.api.plugin.BluetoothConstants.ID;
|
||||||
|
|
||||||
@@ -31,22 +36,32 @@ public class AndroidBluetoothPluginFactory implements DuplexPluginFactory {
|
|||||||
private static final int MAX_POLLING_INTERVAL = 10 * 60 * 1000; // 10 mins
|
private static final int MAX_POLLING_INTERVAL = 10 * 60 * 1000; // 10 mins
|
||||||
private static final double BACKOFF_BASE = 1.2;
|
private static final double BACKOFF_BASE = 1.2;
|
||||||
|
|
||||||
private final Executor ioExecutor;
|
private final Executor ioExecutor, wakefulIoExecutor;
|
||||||
private final AndroidExecutor androidExecutor;
|
private final AndroidExecutor androidExecutor;
|
||||||
private final Context appContext;
|
private final AndroidWakeLockManager wakeLockManager;
|
||||||
|
private final Application app;
|
||||||
private final SecureRandom secureRandom;
|
private final SecureRandom secureRandom;
|
||||||
private final EventBus eventBus;
|
private final EventBus eventBus;
|
||||||
private final Clock clock;
|
private final Clock clock;
|
||||||
private final TimeoutMonitor timeoutMonitor;
|
private final TimeoutMonitor timeoutMonitor;
|
||||||
private final BackoffFactory backoffFactory;
|
private final BackoffFactory backoffFactory;
|
||||||
|
|
||||||
public AndroidBluetoothPluginFactory(Executor ioExecutor,
|
@Inject
|
||||||
AndroidExecutor androidExecutor, Context appContext,
|
public AndroidBluetoothPluginFactory(@IoExecutor Executor ioExecutor,
|
||||||
SecureRandom secureRandom, EventBus eventBus, Clock clock,
|
@WakefulIoExecutor Executor wakefulIoExecutor,
|
||||||
TimeoutMonitor timeoutMonitor, BackoffFactory backoffFactory) {
|
AndroidExecutor androidExecutor,
|
||||||
|
AndroidWakeLockManager wakeLockManager,
|
||||||
|
Application app,
|
||||||
|
SecureRandom secureRandom,
|
||||||
|
EventBus eventBus,
|
||||||
|
Clock clock,
|
||||||
|
TimeoutMonitor timeoutMonitor,
|
||||||
|
BackoffFactory backoffFactory) {
|
||||||
this.ioExecutor = ioExecutor;
|
this.ioExecutor = ioExecutor;
|
||||||
|
this.wakefulIoExecutor = wakefulIoExecutor;
|
||||||
this.androidExecutor = androidExecutor;
|
this.androidExecutor = androidExecutor;
|
||||||
this.appContext = appContext;
|
this.wakeLockManager = wakeLockManager;
|
||||||
|
this.app = app;
|
||||||
this.secureRandom = secureRandom;
|
this.secureRandom = secureRandom;
|
||||||
this.eventBus = eventBus;
|
this.eventBus = eventBus;
|
||||||
this.clock = clock;
|
this.clock = clock;
|
||||||
@@ -67,13 +82,16 @@ public class AndroidBluetoothPluginFactory implements DuplexPluginFactory {
|
|||||||
@Override
|
@Override
|
||||||
public DuplexPlugin createPlugin(PluginCallback callback) {
|
public DuplexPlugin createPlugin(PluginCallback callback) {
|
||||||
BluetoothConnectionLimiter connectionLimiter =
|
BluetoothConnectionLimiter connectionLimiter =
|
||||||
new BluetoothConnectionLimiterImpl(eventBus, clock);
|
new BluetoothConnectionLimiterImpl(eventBus);
|
||||||
|
BluetoothConnectionFactory<BluetoothSocket> connectionFactory =
|
||||||
|
new AndroidBluetoothConnectionFactory(connectionLimiter,
|
||||||
|
wakeLockManager, timeoutMonitor);
|
||||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||||
AndroidBluetoothPlugin plugin = new AndroidBluetoothPlugin(
|
AndroidBluetoothPlugin plugin = new AndroidBluetoothPlugin(
|
||||||
connectionLimiter, timeoutMonitor, ioExecutor, secureRandom,
|
connectionLimiter, connectionFactory, ioExecutor,
|
||||||
androidExecutor, appContext, clock, backoff,
|
wakefulIoExecutor, secureRandom, androidExecutor, app,
|
||||||
callback, MAX_LATENCY, MAX_IDLE_TIME);
|
clock, backoff, callback, MAX_LATENCY, MAX_IDLE_TIME);
|
||||||
eventBus.addListener(plugin);
|
eventBus.addListener(plugin);
|
||||||
return plugin;
|
return plugin;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import org.briarproject.bramble.api.io.TimeoutMonitor;
|
|||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Plugin;
|
import org.briarproject.bramble.api.plugin.Plugin;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.AbstractDuplexTransportConnection;
|
import org.briarproject.bramble.api.plugin.duplex.AbstractDuplexTransportConnection;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLock;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
@@ -21,16 +23,20 @@ class AndroidBluetoothTransportConnection
|
|||||||
private final BluetoothConnectionLimiter connectionLimiter;
|
private final BluetoothConnectionLimiter connectionLimiter;
|
||||||
private final BluetoothSocket socket;
|
private final BluetoothSocket socket;
|
||||||
private final InputStream in;
|
private final InputStream in;
|
||||||
|
private final AndroidWakeLock wakeLock;
|
||||||
|
|
||||||
AndroidBluetoothTransportConnection(Plugin plugin,
|
AndroidBluetoothTransportConnection(Plugin plugin,
|
||||||
BluetoothConnectionLimiter connectionLimiter,
|
BluetoothConnectionLimiter connectionLimiter,
|
||||||
TimeoutMonitor timeoutMonitor, BluetoothSocket socket)
|
AndroidWakeLockManager wakeLockManager,
|
||||||
throws IOException {
|
TimeoutMonitor timeoutMonitor,
|
||||||
|
BluetoothSocket socket) throws IOException {
|
||||||
super(plugin);
|
super(plugin);
|
||||||
this.connectionLimiter = connectionLimiter;
|
this.connectionLimiter = connectionLimiter;
|
||||||
this.socket = socket;
|
this.socket = socket;
|
||||||
in = timeoutMonitor.createTimeoutInputStream(
|
in = timeoutMonitor.createTimeoutInputStream(
|
||||||
socket.getInputStream(), plugin.getMaxIdleTime() * 2);
|
socket.getInputStream(), plugin.getMaxIdleTime() * 2);
|
||||||
|
wakeLock = wakeLockManager.createWakeLock("BluetoothConnection");
|
||||||
|
wakeLock.acquire();
|
||||||
String address = socket.getRemoteDevice().getAddress();
|
String address = socket.getRemoteDevice().getAddress();
|
||||||
if (isValidBluetoothAddress(address)) remote.put(PROP_ADDRESS, address);
|
if (isValidBluetoothAddress(address)) remote.put(PROP_ADDRESS, address);
|
||||||
}
|
}
|
||||||
@@ -49,7 +55,9 @@ class AndroidBluetoothTransportConnection
|
|||||||
protected void closeConnection(boolean exception) throws IOException {
|
protected void closeConnection(boolean exception) throws IOException {
|
||||||
try {
|
try {
|
||||||
socket.close();
|
socket.close();
|
||||||
|
in.close();
|
||||||
} finally {
|
} finally {
|
||||||
|
wakeLock.release();
|
||||||
connectionLimiter.connectionClosed(this);
|
connectionLimiter.connectionClosed(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,30 @@
|
|||||||
package org.briarproject.bramble.plugin.tcp;
|
package org.briarproject.bramble.plugin.tcp;
|
||||||
|
|
||||||
import android.content.Context;
|
import android.annotation.TargetApi;
|
||||||
|
import android.app.Application;
|
||||||
import android.net.ConnectivityManager;
|
import android.net.ConnectivityManager;
|
||||||
|
import android.net.LinkAddress;
|
||||||
|
import android.net.LinkProperties;
|
||||||
import android.net.Network;
|
import android.net.Network;
|
||||||
import android.net.NetworkInfo;
|
import android.net.NetworkCapabilities;
|
||||||
import android.net.wifi.WifiInfo;
|
import android.net.wifi.WifiInfo;
|
||||||
import android.net.wifi.WifiManager;
|
import android.net.wifi.WifiManager;
|
||||||
|
|
||||||
import org.briarproject.bramble.PoliteExecutor;
|
import org.briarproject.bramble.PoliteExecutor;
|
||||||
|
import org.briarproject.bramble.api.Pair;
|
||||||
import org.briarproject.bramble.api.event.Event;
|
import org.briarproject.bramble.api.event.Event;
|
||||||
import org.briarproject.bramble.api.event.EventListener;
|
|
||||||
import org.briarproject.bramble.api.network.event.NetworkStatusEvent;
|
import org.briarproject.bramble.api.network.event.NetworkStatusEvent;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||||
|
import org.briarproject.bramble.api.settings.Settings;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
|
import java.net.InterfaceAddress;
|
||||||
|
import java.net.NetworkInterface;
|
||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
|
import java.net.SocketException;
|
||||||
import java.net.UnknownHostException;
|
import java.net.UnknownHostException;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
@@ -28,14 +35,22 @@ import javax.net.SocketFactory;
|
|||||||
|
|
||||||
import static android.content.Context.CONNECTIVITY_SERVICE;
|
import static android.content.Context.CONNECTIVITY_SERVICE;
|
||||||
import static android.content.Context.WIFI_SERVICE;
|
import static android.content.Context.WIFI_SERVICE;
|
||||||
import static android.net.ConnectivityManager.TYPE_WIFI;
|
import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
|
||||||
import static android.os.Build.VERSION.SDK_INT;
|
import static android.os.Build.VERSION.SDK_INT;
|
||||||
import static java.util.Collections.emptyList;
|
import static java.util.Collections.emptyList;
|
||||||
|
import static java.util.Collections.list;
|
||||||
import static java.util.Collections.singletonList;
|
import static java.util.Collections.singletonList;
|
||||||
|
import static java.util.logging.Level.WARNING;
|
||||||
import static java.util.logging.Logger.getLogger;
|
import static java.util.logging.Logger.getLogger;
|
||||||
|
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
||||||
|
import static org.briarproject.bramble.api.plugin.LanTcpConstants.DEFAULT_PREF_PLUGIN_ENABLE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.ACTIVE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.INACTIVE;
|
||||||
|
import static org.briarproject.bramble.util.IoUtils.tryToClose;
|
||||||
|
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||||
|
|
||||||
@NotNullByDefault
|
@NotNullByDefault
|
||||||
class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
|
class AndroidLanTcpPlugin extends LanTcpPlugin {
|
||||||
|
|
||||||
private static final Logger LOG =
|
private static final Logger LOG =
|
||||||
getLogger(AndroidLanTcpPlugin.class.getName());
|
getLogger(AndroidLanTcpPlugin.class.getName());
|
||||||
@@ -47,20 +62,22 @@ class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
|
|||||||
|
|
||||||
private volatile SocketFactory socketFactory;
|
private volatile SocketFactory socketFactory;
|
||||||
|
|
||||||
AndroidLanTcpPlugin(Executor ioExecutor, Context appContext,
|
AndroidLanTcpPlugin(Executor ioExecutor,
|
||||||
Backoff backoff, PluginCallback callback, int maxLatency,
|
Executor wakefulIoExecutor,
|
||||||
int maxIdleTime, int connectionTimeout) {
|
Application app,
|
||||||
super(ioExecutor, backoff, callback, maxLatency, maxIdleTime,
|
Backoff backoff,
|
||||||
connectionTimeout);
|
PluginCallback callback,
|
||||||
|
int maxLatency,
|
||||||
|
int maxIdleTime,
|
||||||
|
int connectionTimeout) {
|
||||||
|
super(ioExecutor, wakefulIoExecutor, backoff, callback, maxLatency,
|
||||||
|
maxIdleTime, connectionTimeout);
|
||||||
// Don't execute more than one connection status check at a time
|
// Don't execute more than one connection status check at a time
|
||||||
connectionStatusExecutor =
|
connectionStatusExecutor =
|
||||||
new PoliteExecutor("AndroidLanTcpPlugin", ioExecutor, 1);
|
new PoliteExecutor("AndroidLanTcpPlugin", ioExecutor, 1);
|
||||||
ConnectivityManager connectivityManager = (ConnectivityManager)
|
connectivityManager = (ConnectivityManager)
|
||||||
appContext.getSystemService(CONNECTIVITY_SERVICE);
|
requireNonNull(app.getSystemService(CONNECTIVITY_SERVICE));
|
||||||
if (connectivityManager == null) throw new AssertionError();
|
wifiManager = (WifiManager) app.getSystemService(WIFI_SERVICE);
|
||||||
this.connectivityManager = connectivityManager;
|
|
||||||
wifiManager = (WifiManager) appContext.getApplicationContext()
|
|
||||||
.getSystemService(WIFI_SERVICE);
|
|
||||||
socketFactory = SocketFactory.getDefault();
|
socketFactory = SocketFactory.getDefault();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,37 +85,137 @@ class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
|
|||||||
public void start() {
|
public void start() {
|
||||||
if (used.getAndSet(true)) throw new IllegalStateException();
|
if (used.getAndSet(true)) throw new IllegalStateException();
|
||||||
initialisePortProperty();
|
initialisePortProperty();
|
||||||
running = true;
|
Settings settings = callback.getSettings();
|
||||||
|
state.setStarted(settings.getBoolean(PREF_PLUGIN_ENABLE,
|
||||||
|
DEFAULT_PREF_PLUGIN_ENABLE));
|
||||||
updateConnectionStatus();
|
updateConnectionStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void stop() {
|
|
||||||
running = false;
|
|
||||||
tryToClose(socket);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected Socket createSocket() throws IOException {
|
protected Socket createSocket() throws IOException {
|
||||||
return socketFactory.createSocket();
|
return socketFactory.createSocket();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected List<InetAddress> getUsableLocalInetAddresses() {
|
protected List<InetAddress> getUsableLocalInetAddresses(boolean ipv4) {
|
||||||
// If the device doesn't have wifi, don't open any sockets
|
InetAddress addr = getWifiAddress(ipv4);
|
||||||
if (wifiManager == null) return emptyList();
|
return addr == null ? emptyList() : singletonList(addr);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
private InetAddress getWifiAddress(boolean ipv4) {
|
||||||
|
Pair<InetAddress, Boolean> wifi = getWifiIpv4Address();
|
||||||
|
if (ipv4) return wifi == null ? null : wifi.getFirst();
|
||||||
|
// If there's no wifi IPv4 address, we might be a client on an
|
||||||
|
// IPv6-only wifi network. We can only detect this on API 21+
|
||||||
|
if (wifi == null) {
|
||||||
|
return SDK_INT >= 21 ? getWifiClientIpv6Address() : null;
|
||||||
|
}
|
||||||
|
// Use the wifi IPv4 address to determine which interface's IPv6
|
||||||
|
// address we should return (if the interface has a suitable address)
|
||||||
|
return getIpv6AddressForInterface(wifi.getFirst());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a {@link Pair} where the first element is the IPv4 address of
|
||||||
|
* the wifi interface and the second element is true if this device is
|
||||||
|
* providing an access point, or false if this device is a client. Returns
|
||||||
|
* null if this device isn't connected to wifi as an access point or client.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private Pair<InetAddress, Boolean> getWifiIpv4Address() {
|
||||||
|
if (wifiManager == null) return null;
|
||||||
// If we're connected to a wifi network, return its address
|
// If we're connected to a wifi network, return its address
|
||||||
WifiInfo info = wifiManager.getConnectionInfo();
|
WifiInfo info = wifiManager.getConnectionInfo();
|
||||||
if (info != null && info.getIpAddress() != 0) {
|
if (info != null && info.getIpAddress() != 0) {
|
||||||
return singletonList(intToInetAddress(info.getIpAddress()));
|
return new Pair<>(intToInetAddress(info.getIpAddress()), false);
|
||||||
}
|
}
|
||||||
// If we're running an access point, return its address
|
List<InterfaceAddress> ifAddrs = getLocalInterfaceAddresses();
|
||||||
for (InetAddress addr : getLocalInetAddresses()) {
|
// If we're providing a normal access point, return its address
|
||||||
if (addr.equals(WIFI_AP_ADDRESS)) return singletonList(addr);
|
for (InterfaceAddress ifAddr : ifAddrs) {
|
||||||
if (addr.equals(WIFI_DIRECT_AP_ADDRESS)) return singletonList(addr);
|
if (isAndroidWifiApAddress(ifAddr)) {
|
||||||
|
return new Pair<>(ifAddr.getAddress(), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// If we're providing a wifi direct access point, return its address
|
||||||
|
for (InterfaceAddress ifAddr : ifAddrs) {
|
||||||
|
if (isAndroidWifiDirectApAddress(ifAddr)) {
|
||||||
|
return new Pair<>(ifAddr.getAddress(), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Not connected to wifi
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true if the given address belongs to a network provided by an
|
||||||
|
* Android access point (including the access point's own address).
|
||||||
|
* <p>
|
||||||
|
* The access point's address is usually 192.168.43.1, but at least one
|
||||||
|
* device (Honor 8A) may use other addresses in the range 192.168.43.0/24.
|
||||||
|
*/
|
||||||
|
private boolean isAndroidWifiApAddress(InterfaceAddress ifAddr) {
|
||||||
|
if (ifAddr.getNetworkPrefixLength() != 24) return false;
|
||||||
|
byte[] ip = ifAddr.getAddress().getAddress();
|
||||||
|
return ip.length == 4
|
||||||
|
&& ip[0] == (byte) 192
|
||||||
|
&& ip[1] == (byte) 168
|
||||||
|
&& ip[2] == (byte) 43;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true if the given address belongs to a network provided by an
|
||||||
|
* Android wifi direct legacy mode access point (including the access
|
||||||
|
* point's own address).
|
||||||
|
*/
|
||||||
|
private boolean isAndroidWifiDirectApAddress(InterfaceAddress ifAddr) {
|
||||||
|
if (ifAddr.getNetworkPrefixLength() != 24) return false;
|
||||||
|
byte[] ip = ifAddr.getAddress().getAddress();
|
||||||
|
return ip.length == 4
|
||||||
|
&& ip[0] == (byte) 192
|
||||||
|
&& ip[1] == (byte) 168
|
||||||
|
&& ip[2] == (byte) 49;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a link-local IPv6 address for the wifi client interface, or null
|
||||||
|
* if there's no such interface or it doesn't have a suitable address.
|
||||||
|
*/
|
||||||
|
@TargetApi(21)
|
||||||
|
@Nullable
|
||||||
|
private InetAddress getWifiClientIpv6Address() {
|
||||||
|
for (Network net : connectivityManager.getAllNetworks()) {
|
||||||
|
NetworkCapabilities caps =
|
||||||
|
connectivityManager.getNetworkCapabilities(net);
|
||||||
|
if (caps == null || !caps.hasTransport(TRANSPORT_WIFI)) continue;
|
||||||
|
LinkProperties props = connectivityManager.getLinkProperties(net);
|
||||||
|
if (props == null) continue;
|
||||||
|
for (LinkAddress linkAddress : props.getLinkAddresses()) {
|
||||||
|
InetAddress addr = linkAddress.getAddress();
|
||||||
|
if (isIpv6LinkLocalAddress(addr)) return addr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a link-local IPv6 address for the interface with the given IPv4
|
||||||
|
* address, or null if the interface doesn't have a suitable address.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private InetAddress getIpv6AddressForInterface(InetAddress ipv4) {
|
||||||
|
try {
|
||||||
|
NetworkInterface iface = NetworkInterface.getByInetAddress(ipv4);
|
||||||
|
if (iface == null) return null;
|
||||||
|
for (InetAddress addr : list(iface.getInetAddresses())) {
|
||||||
|
if (isIpv6LinkLocalAddress(addr)) return addr;
|
||||||
|
}
|
||||||
|
// No suitable address
|
||||||
|
return null;
|
||||||
|
} catch (SocketException e) {
|
||||||
|
logException(LOG, WARNING, e);
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
// No suitable addresses
|
|
||||||
return emptyList();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private InetAddress intToInetAddress(int ip) {
|
private InetAddress intToInetAddress(int ip) {
|
||||||
@@ -120,9 +237,11 @@ class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
|
|||||||
private SocketFactory getSocketFactory() {
|
private SocketFactory getSocketFactory() {
|
||||||
if (SDK_INT < 21) return SocketFactory.getDefault();
|
if (SDK_INT < 21) return SocketFactory.getDefault();
|
||||||
for (Network net : connectivityManager.getAllNetworks()) {
|
for (Network net : connectivityManager.getAllNetworks()) {
|
||||||
NetworkInfo info = connectivityManager.getNetworkInfo(net);
|
NetworkCapabilities caps =
|
||||||
if (info != null && info.getType() == TYPE_WIFI)
|
connectivityManager.getNetworkCapabilities(net);
|
||||||
|
if (caps != null && caps.hasTransport(TRANSPORT_WIFI)) {
|
||||||
return net.getSocketFactory();
|
return net.getSocketFactory();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
LOG.warning("Could not find suitable socket factory");
|
LOG.warning("Could not find suitable socket factory");
|
||||||
return SocketFactory.getDefault();
|
return SocketFactory.getDefault();
|
||||||
@@ -130,31 +249,59 @@ class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void eventOccurred(Event e) {
|
public void eventOccurred(Event e) {
|
||||||
|
super.eventOccurred(e);
|
||||||
if (e instanceof NetworkStatusEvent) updateConnectionStatus();
|
if (e instanceof NetworkStatusEvent) updateConnectionStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void updateConnectionStatus() {
|
private void updateConnectionStatus() {
|
||||||
connectionStatusExecutor.execute(() -> {
|
connectionStatusExecutor.execute(() -> {
|
||||||
if (!running) return;
|
State s = getState();
|
||||||
List<InetAddress> addrs = getUsableLocalInetAddresses();
|
if (s != ACTIVE && s != INACTIVE) return;
|
||||||
if (addrs.contains(WIFI_AP_ADDRESS)
|
Pair<InetAddress, Boolean> wifi = getPreferredWifiAddress();
|
||||||
|| addrs.contains(WIFI_DIRECT_AP_ADDRESS)) {
|
if (wifi == null) {
|
||||||
|
LOG.info("Not connected to wifi");
|
||||||
|
socketFactory = SocketFactory.getDefault();
|
||||||
|
// Server sockets may not have been closed automatically when
|
||||||
|
// interface was taken down. If any sockets are open, closing
|
||||||
|
// them here will cause the sockets to be cleared and the state
|
||||||
|
// to be updated in acceptContactConnections()
|
||||||
|
if (s == ACTIVE) {
|
||||||
|
LOG.info("Closing server sockets");
|
||||||
|
tryToClose(state.getServerSocket(true), LOG, WARNING);
|
||||||
|
tryToClose(state.getServerSocket(false), LOG, WARNING);
|
||||||
|
}
|
||||||
|
} else if (wifi.getSecond()) {
|
||||||
LOG.info("Providing wifi hotspot");
|
LOG.info("Providing wifi hotspot");
|
||||||
// There's no corresponding Network object and thus no way
|
// There's no corresponding Network object and thus no way
|
||||||
// to get a suitable socket factory, so we won't be able to
|
// to get a suitable socket factory, so we won't be able to
|
||||||
// make outgoing connections on API 21+ if another network
|
// make outgoing connections on API 21+ if another network
|
||||||
// has internet access
|
// has internet access
|
||||||
socketFactory = SocketFactory.getDefault();
|
socketFactory = SocketFactory.getDefault();
|
||||||
if (socket == null || socket.isClosed()) bind();
|
bind();
|
||||||
} else if (addrs.isEmpty()) {
|
|
||||||
LOG.info("Not connected to wifi");
|
|
||||||
socketFactory = SocketFactory.getDefault();
|
|
||||||
tryToClose(socket);
|
|
||||||
} else {
|
} else {
|
||||||
LOG.info("Connected to wifi");
|
LOG.info("Connected to wifi");
|
||||||
socketFactory = getSocketFactory();
|
socketFactory = getSocketFactory();
|
||||||
if (socket == null || socket.isClosed()) bind();
|
bind();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a {@link Pair} where the first element is an IP address (IPv4 if
|
||||||
|
* available, otherwise IPv6) of the wifi interface and the second element
|
||||||
|
* is true if this device is providing an access point, or false if this
|
||||||
|
* device is a client. Returns null if this device isn't connected to wifi
|
||||||
|
* as an access point or client.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private Pair<InetAddress, Boolean> getPreferredWifiAddress() {
|
||||||
|
Pair<InetAddress, Boolean> wifi = getWifiIpv4Address();
|
||||||
|
// If there's no wifi IPv4 address, we might be a client on an
|
||||||
|
// IPv6-only wifi network. We can only detect this on API 21+
|
||||||
|
if (wifi == null && SDK_INT >= 21) {
|
||||||
|
InetAddress ipv6 = getWifiClientIpv6Address();
|
||||||
|
if (ipv6 != null) return new Pair<>(ipv6, false);
|
||||||
|
}
|
||||||
|
return wifi;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
package org.briarproject.bramble.plugin.tcp;
|
package org.briarproject.bramble.plugin.tcp;
|
||||||
|
|
||||||
import android.content.Context;
|
import android.app.Application;
|
||||||
|
|
||||||
import org.briarproject.bramble.api.event.EventBus;
|
import org.briarproject.bramble.api.event.EventBus;
|
||||||
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
||||||
@@ -10,10 +11,12 @@ import org.briarproject.bramble.api.plugin.PluginCallback;
|
|||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||||
|
import org.briarproject.bramble.api.system.WakefulIoExecutor;
|
||||||
|
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
import javax.annotation.concurrent.Immutable;
|
import javax.annotation.concurrent.Immutable;
|
||||||
|
import javax.inject.Inject;
|
||||||
|
|
||||||
import static org.briarproject.bramble.api.plugin.LanTcpConstants.ID;
|
import static org.briarproject.bramble.api.plugin.LanTcpConstants.ID;
|
||||||
|
|
||||||
@@ -28,17 +31,22 @@ public class AndroidLanTcpPluginFactory implements DuplexPluginFactory {
|
|||||||
private static final int MAX_POLLING_INTERVAL = 600_000; // 10 mins
|
private static final int MAX_POLLING_INTERVAL = 600_000; // 10 mins
|
||||||
private static final double BACKOFF_BASE = 1.2;
|
private static final double BACKOFF_BASE = 1.2;
|
||||||
|
|
||||||
private final Executor ioExecutor;
|
private final Executor ioExecutor, wakefulIoExecutor;
|
||||||
private final EventBus eventBus;
|
private final EventBus eventBus;
|
||||||
private final BackoffFactory backoffFactory;
|
private final BackoffFactory backoffFactory;
|
||||||
private final Context appContext;
|
private final Application app;
|
||||||
|
|
||||||
public AndroidLanTcpPluginFactory(Executor ioExecutor, EventBus eventBus,
|
@Inject
|
||||||
BackoffFactory backoffFactory, Context appContext) {
|
public AndroidLanTcpPluginFactory(@IoExecutor Executor ioExecutor,
|
||||||
|
@WakefulIoExecutor Executor wakefulIoExecutor,
|
||||||
|
EventBus eventBus,
|
||||||
|
BackoffFactory backoffFactory,
|
||||||
|
Application app) {
|
||||||
this.ioExecutor = ioExecutor;
|
this.ioExecutor = ioExecutor;
|
||||||
|
this.wakefulIoExecutor = wakefulIoExecutor;
|
||||||
this.eventBus = eventBus;
|
this.eventBus = eventBus;
|
||||||
this.backoffFactory = backoffFactory;
|
this.backoffFactory = backoffFactory;
|
||||||
this.appContext = appContext;
|
this.app = app;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -56,8 +64,8 @@ public class AndroidLanTcpPluginFactory implements DuplexPluginFactory {
|
|||||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||||
AndroidLanTcpPlugin plugin = new AndroidLanTcpPlugin(ioExecutor,
|
AndroidLanTcpPlugin plugin = new AndroidLanTcpPlugin(ioExecutor,
|
||||||
appContext, backoff, callback, MAX_LATENCY, MAX_IDLE_TIME,
|
wakefulIoExecutor, app, backoff, callback,
|
||||||
CONNECTION_TIMEOUT);
|
MAX_LATENCY, MAX_IDLE_TIME, CONNECTION_TIMEOUT);
|
||||||
eventBus.addListener(plugin);
|
eventBus.addListener(plugin);
|
||||||
return plugin;
|
return plugin;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
package org.briarproject.bramble.plugin.tor;
|
package org.briarproject.bramble.plugin.tor;
|
||||||
|
|
||||||
import android.content.Context;
|
import android.app.Application;
|
||||||
import android.content.pm.PackageInfo;
|
import android.content.pm.PackageInfo;
|
||||||
import android.content.pm.PackageManager;
|
import android.content.pm.PackageManager;
|
||||||
import android.content.pm.PackageManager.NameNotFoundException;
|
import android.content.pm.PackageManager.NameNotFoundException;
|
||||||
import android.os.PowerManager;
|
|
||||||
|
|
||||||
import org.briarproject.bramble.api.battery.BatteryManager;
|
import org.briarproject.bramble.api.battery.BatteryManager;
|
||||||
import org.briarproject.bramble.api.network.NetworkManager;
|
import org.briarproject.bramble.api.network.NetworkManager;
|
||||||
@@ -12,48 +11,50 @@ import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
|||||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLock;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
import org.briarproject.bramble.api.system.LocationUtils;
|
import org.briarproject.bramble.api.system.LocationUtils;
|
||||||
import org.briarproject.bramble.api.system.ResourceProvider;
|
import org.briarproject.bramble.api.system.ResourceProvider;
|
||||||
import org.briarproject.bramble.util.RenewableWakeLock;
|
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
|
|
||||||
import javax.net.SocketFactory;
|
import javax.net.SocketFactory;
|
||||||
|
|
||||||
import static android.content.Context.MODE_PRIVATE;
|
|
||||||
import static android.content.Context.POWER_SERVICE;
|
|
||||||
import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
|
|
||||||
import static java.util.concurrent.TimeUnit.MINUTES;
|
|
||||||
|
|
||||||
@MethodsNotNullByDefault
|
@MethodsNotNullByDefault
|
||||||
@ParametersNotNullByDefault
|
@ParametersNotNullByDefault
|
||||||
class AndroidTorPlugin extends TorPlugin {
|
class AndroidTorPlugin extends TorPlugin {
|
||||||
|
|
||||||
private final Context appContext;
|
private final Application app;
|
||||||
private final RenewableWakeLock wakeLock;
|
private final AndroidWakeLock wakeLock;
|
||||||
|
|
||||||
AndroidTorPlugin(Executor ioExecutor, ScheduledExecutorService scheduler,
|
AndroidTorPlugin(Executor ioExecutor,
|
||||||
Context appContext, NetworkManager networkManager,
|
Executor wakefulIoExecutor,
|
||||||
LocationUtils locationUtils, SocketFactory torSocketFactory,
|
Application app,
|
||||||
Clock clock, ResourceProvider resourceProvider,
|
NetworkManager networkManager,
|
||||||
|
LocationUtils locationUtils,
|
||||||
|
SocketFactory torSocketFactory,
|
||||||
|
Clock clock,
|
||||||
|
ResourceProvider resourceProvider,
|
||||||
CircumventionProvider circumventionProvider,
|
CircumventionProvider circumventionProvider,
|
||||||
BatteryManager batteryManager, Backoff backoff,
|
BatteryManager batteryManager,
|
||||||
|
AndroidWakeLockManager wakeLockManager,
|
||||||
|
Backoff backoff,
|
||||||
TorRendezvousCrypto torRendezvousCrypto,
|
TorRendezvousCrypto torRendezvousCrypto,
|
||||||
PluginCallback callback, String architecture, int maxLatency,
|
PluginCallback callback,
|
||||||
int maxIdleTime) {
|
String architecture,
|
||||||
super(ioExecutor, networkManager, locationUtils, torSocketFactory,
|
int maxLatency,
|
||||||
clock, resourceProvider, circumventionProvider, batteryManager,
|
int maxIdleTime,
|
||||||
backoff, torRendezvousCrypto, callback, architecture, maxLatency, maxIdleTime,
|
File torDirectory) {
|
||||||
appContext.getDir("tor", MODE_PRIVATE));
|
super(ioExecutor, wakefulIoExecutor, networkManager, locationUtils,
|
||||||
this.appContext = appContext;
|
torSocketFactory, clock, resourceProvider,
|
||||||
PowerManager pm = (PowerManager)
|
circumventionProvider, batteryManager, backoff,
|
||||||
appContext.getSystemService(POWER_SERVICE);
|
torRendezvousCrypto, callback, architecture, maxLatency,
|
||||||
if (pm == null) throw new AssertionError();
|
maxIdleTime, torDirectory);
|
||||||
wakeLock = new RenewableWakeLock(pm, scheduler, PARTIAL_WAKE_LOCK,
|
this.app = app;
|
||||||
getWakeLockTag(), 1, MINUTES);
|
wakeLock = wakeLockManager.createWakeLock("TorPlugin");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -64,8 +65,8 @@ class AndroidTorPlugin extends TorPlugin {
|
|||||||
@Override
|
@Override
|
||||||
protected long getLastUpdateTime() {
|
protected long getLastUpdateTime() {
|
||||||
try {
|
try {
|
||||||
PackageManager pm = appContext.getPackageManager();
|
PackageManager pm = app.getPackageManager();
|
||||||
PackageInfo pi = pm.getPackageInfo(appContext.getPackageName(), 0);
|
PackageInfo pi = pm.getPackageInfo(app.getPackageName(), 0);
|
||||||
return pi.lastUpdateTime;
|
return pi.lastUpdateTime;
|
||||||
} catch (NameNotFoundException e) {
|
} catch (NameNotFoundException e) {
|
||||||
throw new AssertionError(e);
|
throw new AssertionError(e);
|
||||||
@@ -74,7 +75,6 @@ class AndroidTorPlugin extends TorPlugin {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void enableNetwork(boolean enable) throws IOException {
|
protected void enableNetwork(boolean enable) throws IOException {
|
||||||
if (!running) return;
|
|
||||||
if (enable) wakeLock.acquire();
|
if (enable) wakeLock.acquire();
|
||||||
super.enableNetwork(enable);
|
super.enableNetwork(enable);
|
||||||
if (!enable) wakeLock.release();
|
if (!enable) wakeLock.release();
|
||||||
@@ -85,17 +85,4 @@ class AndroidTorPlugin extends TorPlugin {
|
|||||||
super.stop();
|
super.stop();
|
||||||
wakeLock.release();
|
wakeLock.release();
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getWakeLockTag() {
|
|
||||||
PackageManager pm = appContext.getPackageManager();
|
|
||||||
for (PackageInfo info : pm.getInstalledPackages(0)) {
|
|
||||||
String name = info.packageName.toLowerCase();
|
|
||||||
if (name.startsWith("com.huawei.powergenie")) {
|
|
||||||
return "LocationManagerService";
|
|
||||||
} else if (name.startsWith("com.evenwell.powermonitor")) {
|
|
||||||
return "AudioIn";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return getClass().getSimpleName();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,28 +1,33 @@
|
|||||||
package org.briarproject.bramble.plugin.tor;
|
package org.briarproject.bramble.plugin.tor;
|
||||||
|
|
||||||
import android.content.Context;
|
import android.app.Application;
|
||||||
|
|
||||||
import org.briarproject.bramble.api.battery.BatteryManager;
|
import org.briarproject.bramble.api.battery.BatteryManager;
|
||||||
import org.briarproject.bramble.api.event.EventBus;
|
import org.briarproject.bramble.api.event.EventBus;
|
||||||
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
import org.briarproject.bramble.api.network.NetworkManager;
|
import org.briarproject.bramble.api.network.NetworkManager;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
||||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||||
import org.briarproject.bramble.api.plugin.TorConstants;
|
import org.briarproject.bramble.api.plugin.TorConstants;
|
||||||
|
import org.briarproject.bramble.api.plugin.TorDirectory;
|
||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
import org.briarproject.bramble.api.system.LocationUtils;
|
import org.briarproject.bramble.api.system.LocationUtils;
|
||||||
import org.briarproject.bramble.api.system.ResourceProvider;
|
import org.briarproject.bramble.api.system.ResourceProvider;
|
||||||
|
import org.briarproject.bramble.api.system.WakefulIoExecutor;
|
||||||
import org.briarproject.bramble.util.AndroidUtils;
|
import org.briarproject.bramble.util.AndroidUtils;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
import javax.annotation.concurrent.Immutable;
|
import javax.annotation.concurrent.Immutable;
|
||||||
|
import javax.inject.Inject;
|
||||||
import javax.net.SocketFactory;
|
import javax.net.SocketFactory;
|
||||||
|
|
||||||
@Immutable
|
@Immutable
|
||||||
@@ -38,9 +43,8 @@ public class AndroidTorPluginFactory implements DuplexPluginFactory {
|
|||||||
private static final int MAX_POLLING_INTERVAL = 10 * 60 * 1000; // 10 mins
|
private static final int MAX_POLLING_INTERVAL = 10 * 60 * 1000; // 10 mins
|
||||||
private static final double BACKOFF_BASE = 1.2;
|
private static final double BACKOFF_BASE = 1.2;
|
||||||
|
|
||||||
private final Executor ioExecutor;
|
private final Executor ioExecutor, wakefulIoExecutor;
|
||||||
private final ScheduledExecutorService scheduler;
|
private final Application app;
|
||||||
private final Context appContext;
|
|
||||||
private final NetworkManager networkManager;
|
private final NetworkManager networkManager;
|
||||||
private final LocationUtils locationUtils;
|
private final LocationUtils locationUtils;
|
||||||
private final EventBus eventBus;
|
private final EventBus eventBus;
|
||||||
@@ -49,18 +53,28 @@ public class AndroidTorPluginFactory implements DuplexPluginFactory {
|
|||||||
private final ResourceProvider resourceProvider;
|
private final ResourceProvider resourceProvider;
|
||||||
private final CircumventionProvider circumventionProvider;
|
private final CircumventionProvider circumventionProvider;
|
||||||
private final BatteryManager batteryManager;
|
private final BatteryManager batteryManager;
|
||||||
|
private final AndroidWakeLockManager wakeLockManager;
|
||||||
private final Clock clock;
|
private final Clock clock;
|
||||||
|
private final File torDirectory;
|
||||||
|
|
||||||
public AndroidTorPluginFactory(Executor ioExecutor,
|
@Inject
|
||||||
ScheduledExecutorService scheduler, Context appContext,
|
public AndroidTorPluginFactory(@IoExecutor Executor ioExecutor,
|
||||||
NetworkManager networkManager, LocationUtils locationUtils,
|
@WakefulIoExecutor Executor wakefulIoExecutor,
|
||||||
EventBus eventBus, SocketFactory torSocketFactory,
|
Application app,
|
||||||
BackoffFactory backoffFactory, ResourceProvider resourceProvider,
|
NetworkManager networkManager,
|
||||||
|
LocationUtils locationUtils,
|
||||||
|
EventBus eventBus,
|
||||||
|
SocketFactory torSocketFactory,
|
||||||
|
BackoffFactory backoffFactory,
|
||||||
|
ResourceProvider resourceProvider,
|
||||||
CircumventionProvider circumventionProvider,
|
CircumventionProvider circumventionProvider,
|
||||||
BatteryManager batteryManager, Clock clock) {
|
BatteryManager batteryManager,
|
||||||
|
AndroidWakeLockManager wakeLockManager,
|
||||||
|
Clock clock,
|
||||||
|
@TorDirectory File torDirectory) {
|
||||||
this.ioExecutor = ioExecutor;
|
this.ioExecutor = ioExecutor;
|
||||||
this.scheduler = scheduler;
|
this.wakefulIoExecutor = wakefulIoExecutor;
|
||||||
this.appContext = appContext;
|
this.app = app;
|
||||||
this.networkManager = networkManager;
|
this.networkManager = networkManager;
|
||||||
this.locationUtils = locationUtils;
|
this.locationUtils = locationUtils;
|
||||||
this.eventBus = eventBus;
|
this.eventBus = eventBus;
|
||||||
@@ -69,7 +83,9 @@ public class AndroidTorPluginFactory implements DuplexPluginFactory {
|
|||||||
this.resourceProvider = resourceProvider;
|
this.resourceProvider = resourceProvider;
|
||||||
this.circumventionProvider = circumventionProvider;
|
this.circumventionProvider = circumventionProvider;
|
||||||
this.batteryManager = batteryManager;
|
this.batteryManager = batteryManager;
|
||||||
|
this.wakeLockManager = wakeLockManager;
|
||||||
this.clock = clock;
|
this.clock = clock;
|
||||||
|
this.torDirectory = torDirectory;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -112,11 +128,12 @@ public class AndroidTorPluginFactory implements DuplexPluginFactory {
|
|||||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||||
TorRendezvousCrypto torRendezvousCrypto = new TorRendezvousCryptoImpl();
|
TorRendezvousCrypto torRendezvousCrypto = new TorRendezvousCryptoImpl();
|
||||||
AndroidTorPlugin plugin = new AndroidTorPlugin(ioExecutor, scheduler,
|
AndroidTorPlugin plugin = new AndroidTorPlugin(ioExecutor,
|
||||||
appContext, networkManager, locationUtils, torSocketFactory,
|
wakefulIoExecutor, app, networkManager, locationUtils,
|
||||||
clock, resourceProvider, circumventionProvider, batteryManager,
|
torSocketFactory, clock, resourceProvider,
|
||||||
|
circumventionProvider, batteryManager, wakeLockManager,
|
||||||
backoff, torRendezvousCrypto, callback, architecture,
|
backoff, torRendezvousCrypto, callback, architecture,
|
||||||
MAX_LATENCY, MAX_IDLE_TIME);
|
MAX_LATENCY, MAX_IDLE_TIME, torDirectory);
|
||||||
eventBus.addListener(plugin);
|
eventBus.addListener(plugin);
|
||||||
return plugin;
|
return plugin;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
|
||||||
|
@NotNullByDefault
|
||||||
|
interface AlarmConstants {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request code for the broadcast intent attached to the periodic alarm.
|
||||||
|
*/
|
||||||
|
int REQUEST_ALARM = 1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Key for storing the process ID in the extras of the periodic alarm's
|
||||||
|
* intent. This allows us to ignore alarms scheduled by dead processes.
|
||||||
|
*/
|
||||||
|
String EXTRA_PID = "org.briarproject.bramble.EXTRA_PID";
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.BrambleApplication;
|
||||||
|
|
||||||
|
public class AlarmReceiver extends BroadcastReceiver {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onReceive(Context ctx, Intent intent) {
|
||||||
|
BrambleApplication app =
|
||||||
|
(BrambleApplication) ctx.getApplicationContext();
|
||||||
|
app.getBrambleAppComponent().alarmListener().onAlarm(intent);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -61,12 +61,12 @@ class AndroidLocationUtils implements LocationUtils {
|
|||||||
private String getCountryFromPhoneNetwork() {
|
private String getCountryFromPhoneNetwork() {
|
||||||
Object o = appContext.getSystemService(TELEPHONY_SERVICE);
|
Object o = appContext.getSystemService(TELEPHONY_SERVICE);
|
||||||
TelephonyManager tm = (TelephonyManager) o;
|
TelephonyManager tm = (TelephonyManager) o;
|
||||||
return tm.getNetworkCountryIso();
|
return tm == null ? "" : tm.getNetworkCountryIso();
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getCountryFromSimCard() {
|
private String getCountryFromSimCard() {
|
||||||
Object o = appContext.getSystemService(TELEPHONY_SERVICE);
|
Object o = appContext.getSystemService(TELEPHONY_SERVICE);
|
||||||
TelephonyManager tm = (TelephonyManager) o;
|
TelephonyManager tm = (TelephonyManager) o;
|
||||||
return tm.getSimCountryIso();
|
return tm == null ? "" : tm.getSimCountryIso();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,17 @@
|
|||||||
package org.briarproject.bramble.system;
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
import org.briarproject.bramble.api.event.EventExecutor;
|
import org.briarproject.bramble.api.event.EventExecutor;
|
||||||
|
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
|
||||||
import org.briarproject.bramble.api.system.AndroidExecutor;
|
import org.briarproject.bramble.api.system.AndroidExecutor;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
|
||||||
import org.briarproject.bramble.api.system.LocationUtils;
|
import org.briarproject.bramble.api.system.LocationUtils;
|
||||||
import org.briarproject.bramble.api.system.ResourceProvider;
|
import org.briarproject.bramble.api.system.ResourceProvider;
|
||||||
import org.briarproject.bramble.api.system.SecureRandomProvider;
|
import org.briarproject.bramble.api.system.SecureRandomProvider;
|
||||||
|
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.concurrent.RejectedExecutionHandler;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||||
|
|
||||||
import javax.inject.Singleton;
|
import javax.inject.Singleton;
|
||||||
|
|
||||||
@@ -16,6 +21,23 @@ import dagger.Provides;
|
|||||||
@Module
|
@Module
|
||||||
public class AndroidSystemModule {
|
public class AndroidSystemModule {
|
||||||
|
|
||||||
|
private final ScheduledExecutorService scheduledExecutorService;
|
||||||
|
|
||||||
|
public AndroidSystemModule() {
|
||||||
|
// Discard tasks that are submitted during shutdown
|
||||||
|
RejectedExecutionHandler policy =
|
||||||
|
new ScheduledThreadPoolExecutor.DiscardPolicy();
|
||||||
|
scheduledExecutorService = new ScheduledThreadPoolExecutor(1, policy);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
ScheduledExecutorService provideScheduledExecutorService(
|
||||||
|
LifecycleManager lifecycleManager) {
|
||||||
|
lifecycleManager.registerForShutdown(scheduledExecutorService);
|
||||||
|
return scheduledExecutorService;
|
||||||
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
SecureRandomProvider provideSecureRandomProvider(
|
SecureRandomProvider provideSecureRandomProvider(
|
||||||
@@ -47,4 +69,11 @@ public class AndroidSystemModule {
|
|||||||
ResourceProvider provideResourceProvider(AndroidResourceProvider provider) {
|
ResourceProvider provideResourceProvider(AndroidResourceProvider provider) {
|
||||||
return provider;
|
return provider;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
AndroidWakeLockManager provideWakeLockManager(
|
||||||
|
AndroidWakeLockManagerImpl wakeLockManager) {
|
||||||
|
return wakeLockManager;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,242 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import android.annotation.TargetApi;
|
||||||
|
import android.app.AlarmManager;
|
||||||
|
import android.app.Application;
|
||||||
|
import android.app.PendingIntent;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.os.Process;
|
||||||
|
import android.os.SystemClock;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.lifecycle.Service;
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.system.AlarmListener;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
|
import org.briarproject.bramble.api.system.Wakeful;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.PriorityQueue;
|
||||||
|
import java.util.Queue;
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import javax.annotation.concurrent.GuardedBy;
|
||||||
|
import javax.annotation.concurrent.ThreadSafe;
|
||||||
|
|
||||||
|
import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
|
||||||
|
import static android.app.AlarmManager.INTERVAL_FIFTEEN_MINUTES;
|
||||||
|
import static android.app.PendingIntent.FLAG_CANCEL_CURRENT;
|
||||||
|
import static android.content.Context.ALARM_SERVICE;
|
||||||
|
import static android.os.Build.VERSION.SDK_INT;
|
||||||
|
import static java.util.Objects.requireNonNull;
|
||||||
|
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||||
|
import static java.util.logging.Level.INFO;
|
||||||
|
import static java.util.logging.Logger.getLogger;
|
||||||
|
import static org.briarproject.bramble.system.AlarmConstants.EXTRA_PID;
|
||||||
|
import static org.briarproject.bramble.system.AlarmConstants.REQUEST_ALARM;
|
||||||
|
|
||||||
|
@ThreadSafe
|
||||||
|
@NotNullByDefault
|
||||||
|
class AndroidTaskScheduler implements TaskScheduler, Service, AlarmListener {
|
||||||
|
|
||||||
|
private static final Logger LOG =
|
||||||
|
getLogger(AndroidTaskScheduler.class.getName());
|
||||||
|
|
||||||
|
private static final long ALARM_MS = INTERVAL_FIFTEEN_MINUTES;
|
||||||
|
|
||||||
|
private final Application app;
|
||||||
|
private final AndroidWakeLockManager wakeLockManager;
|
||||||
|
private final ScheduledExecutorService scheduledExecutorService;
|
||||||
|
private final AlarmManager alarmManager;
|
||||||
|
|
||||||
|
private final Object lock = new Object();
|
||||||
|
@GuardedBy("lock")
|
||||||
|
private final Queue<ScheduledTask> tasks = new PriorityQueue<>();
|
||||||
|
|
||||||
|
AndroidTaskScheduler(Application app,
|
||||||
|
AndroidWakeLockManager wakeLockManager,
|
||||||
|
ScheduledExecutorService scheduledExecutorService) {
|
||||||
|
this.app = app;
|
||||||
|
this.wakeLockManager = wakeLockManager;
|
||||||
|
this.scheduledExecutorService = scheduledExecutorService;
|
||||||
|
alarmManager = (AlarmManager)
|
||||||
|
requireNonNull(app.getSystemService(ALARM_SERVICE));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void startService() {
|
||||||
|
scheduleAlarm();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void stopService() {
|
||||||
|
cancelAlarm();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Cancellable schedule(Runnable task, Executor executor, long delay,
|
||||||
|
TimeUnit unit) {
|
||||||
|
AtomicBoolean cancelled = new AtomicBoolean(false);
|
||||||
|
return schedule(task, executor, delay, unit, cancelled);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Cancellable scheduleWithFixedDelay(Runnable task, Executor executor,
|
||||||
|
long delay, long interval, TimeUnit unit) {
|
||||||
|
AtomicBoolean cancelled = new AtomicBoolean(false);
|
||||||
|
return scheduleWithFixedDelay(task, executor, delay, interval, unit,
|
||||||
|
cancelled);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onAlarm(Intent intent) {
|
||||||
|
wakeLockManager.runWakefully(() -> {
|
||||||
|
int extraPid = intent.getIntExtra(EXTRA_PID, -1);
|
||||||
|
int currentPid = Process.myPid();
|
||||||
|
if (extraPid == currentPid) {
|
||||||
|
LOG.info("Alarm");
|
||||||
|
rescheduleAlarm();
|
||||||
|
runDueTasks();
|
||||||
|
} else if (LOG.isLoggable(INFO)) {
|
||||||
|
LOG.info("Ignoring alarm with PID " + extraPid
|
||||||
|
+ ", current PID is " + currentPid);
|
||||||
|
}
|
||||||
|
}, "TaskAlarm");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Cancellable schedule(Runnable task, Executor executor, long delay,
|
||||||
|
TimeUnit unit, AtomicBoolean cancelled) {
|
||||||
|
long now = SystemClock.elapsedRealtime();
|
||||||
|
long dueMillis = now + MILLISECONDS.convert(delay, unit);
|
||||||
|
Runnable wakeful = () ->
|
||||||
|
wakeLockManager.executeWakefully(task, executor, "TaskHandoff");
|
||||||
|
Future<?> check = scheduleCheckForDueTasks(delay, unit);
|
||||||
|
ScheduledTask s = new ScheduledTask(wakeful, dueMillis, check,
|
||||||
|
cancelled);
|
||||||
|
synchronized (lock) {
|
||||||
|
tasks.add(s);
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Cancellable scheduleWithFixedDelay(Runnable task, Executor executor,
|
||||||
|
long delay, long interval, TimeUnit unit, AtomicBoolean cancelled) {
|
||||||
|
// All executions of this periodic task share a cancelled flag
|
||||||
|
Runnable wrapped = () -> {
|
||||||
|
task.run();
|
||||||
|
scheduleWithFixedDelay(task, executor, interval, interval, unit,
|
||||||
|
cancelled);
|
||||||
|
};
|
||||||
|
return schedule(wrapped, executor, delay, unit, cancelled);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Future<?> scheduleCheckForDueTasks(long delay, TimeUnit unit) {
|
||||||
|
Runnable wakeful = () -> wakeLockManager.runWakefully(
|
||||||
|
this::runDueTasks, "TaskScheduler");
|
||||||
|
return scheduledExecutorService.schedule(wakeful, delay, unit);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Wakeful
|
||||||
|
private void runDueTasks() {
|
||||||
|
long now = SystemClock.elapsedRealtime();
|
||||||
|
List<ScheduledTask> due = new ArrayList<>();
|
||||||
|
synchronized (lock) {
|
||||||
|
while (true) {
|
||||||
|
ScheduledTask s = tasks.peek();
|
||||||
|
if (s == null || s.dueMillis > now) break;
|
||||||
|
due.add(tasks.remove());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (LOG.isLoggable(INFO)) {
|
||||||
|
LOG.info("Running " + due.size() + " due tasks");
|
||||||
|
}
|
||||||
|
for (ScheduledTask s : due) {
|
||||||
|
if (LOG.isLoggable(INFO)) {
|
||||||
|
LOG.info("Task is " + (now - s.dueMillis) + " ms overdue");
|
||||||
|
}
|
||||||
|
s.run();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void scheduleAlarm() {
|
||||||
|
if (SDK_INT >= 23) scheduleIdleAlarm();
|
||||||
|
else scheduleInexactRepeatingAlarm();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void rescheduleAlarm() {
|
||||||
|
// If SDK_INT < 23 the alarm repeats automatically
|
||||||
|
if (SDK_INT >= 23) scheduleIdleAlarm();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cancelAlarm() {
|
||||||
|
alarmManager.cancel(getAlarmPendingIntent());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void scheduleInexactRepeatingAlarm() {
|
||||||
|
alarmManager.setInexactRepeating(ELAPSED_REALTIME_WAKEUP,
|
||||||
|
SystemClock.elapsedRealtime() + ALARM_MS, ALARM_MS,
|
||||||
|
getAlarmPendingIntent());
|
||||||
|
}
|
||||||
|
|
||||||
|
@TargetApi(23)
|
||||||
|
private void scheduleIdleAlarm() {
|
||||||
|
alarmManager.setAndAllowWhileIdle(ELAPSED_REALTIME_WAKEUP,
|
||||||
|
SystemClock.elapsedRealtime() + ALARM_MS,
|
||||||
|
getAlarmPendingIntent());
|
||||||
|
}
|
||||||
|
|
||||||
|
private PendingIntent getAlarmPendingIntent() {
|
||||||
|
Intent i = new Intent(app, AlarmReceiver.class);
|
||||||
|
i.putExtra(EXTRA_PID, android.os.Process.myPid());
|
||||||
|
return PendingIntent.getBroadcast(app, REQUEST_ALARM, i,
|
||||||
|
FLAG_CANCEL_CURRENT);
|
||||||
|
}
|
||||||
|
|
||||||
|
private class ScheduledTask
|
||||||
|
implements Runnable, Cancellable, Comparable<ScheduledTask> {
|
||||||
|
|
||||||
|
private final Runnable task;
|
||||||
|
private final long dueMillis;
|
||||||
|
private final Future<?> check;
|
||||||
|
private final AtomicBoolean cancelled;
|
||||||
|
|
||||||
|
public ScheduledTask(Runnable task, long dueMillis,
|
||||||
|
Future<?> check, AtomicBoolean cancelled) {
|
||||||
|
this.task = task;
|
||||||
|
this.dueMillis = dueMillis;
|
||||||
|
this.check = check;
|
||||||
|
this.cancelled = cancelled;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
if (!cancelled.get()) task.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void cancel() {
|
||||||
|
// Cancel any future executions of this task
|
||||||
|
cancelled.set(true);
|
||||||
|
// Cancel the scheduled check for due tasks
|
||||||
|
check.cancel(false);
|
||||||
|
// Remove the task from the queue
|
||||||
|
synchronized (lock) {
|
||||||
|
tasks.remove(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compareTo(ScheduledTask s) {
|
||||||
|
//noinspection UseCompareMethod
|
||||||
|
if (dueMillis < s.dueMillis) return -1;
|
||||||
|
if (dueMillis > s.dueMillis) return 1;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import android.app.Application;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
|
||||||
|
import org.briarproject.bramble.api.system.AlarmListener;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
|
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
|
||||||
|
import javax.inject.Inject;
|
||||||
|
import javax.inject.Singleton;
|
||||||
|
|
||||||
|
import dagger.Module;
|
||||||
|
import dagger.Provides;
|
||||||
|
|
||||||
|
@Module
|
||||||
|
public class AndroidTaskSchedulerModule {
|
||||||
|
|
||||||
|
public static class EagerSingletons {
|
||||||
|
@Inject
|
||||||
|
AndroidTaskScheduler scheduler;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
AndroidTaskScheduler provideAndroidTaskScheduler(
|
||||||
|
LifecycleManager lifecycleManager, Application app,
|
||||||
|
AndroidWakeLockManager wakeLockManager,
|
||||||
|
ScheduledExecutorService scheduledExecutorService) {
|
||||||
|
AndroidTaskScheduler scheduler = new AndroidTaskScheduler(app,
|
||||||
|
wakeLockManager, scheduledExecutorService);
|
||||||
|
lifecycleManager.registerService(scheduler);
|
||||||
|
return scheduler;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
AlarmListener provideAlarmListener(AndroidTaskScheduler scheduler) {
|
||||||
|
return scheduler;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
TaskScheduler provideTaskScheduler(AndroidTaskScheduler scheduler) {
|
||||||
|
return scheduler;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLock;
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import javax.annotation.concurrent.GuardedBy;
|
||||||
|
import javax.annotation.concurrent.ThreadSafe;
|
||||||
|
|
||||||
|
import static java.util.logging.Level.FINE;
|
||||||
|
import static java.util.logging.Logger.getLogger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A wrapper around a {@link SharedWakeLock} that provides the more convenient
|
||||||
|
* semantics of {@link AndroidWakeLock} (i.e. calls to acquire() and release()
|
||||||
|
* don't need to be balanced).
|
||||||
|
*/
|
||||||
|
@ThreadSafe
|
||||||
|
@NotNullByDefault
|
||||||
|
class AndroidWakeLockImpl implements AndroidWakeLock {
|
||||||
|
|
||||||
|
private static final Logger LOG =
|
||||||
|
getLogger(AndroidWakeLockImpl.class.getName());
|
||||||
|
|
||||||
|
private static final AtomicInteger INSTANCE_ID = new AtomicInteger(0);
|
||||||
|
|
||||||
|
private final SharedWakeLock sharedWakeLock;
|
||||||
|
private final String tag;
|
||||||
|
|
||||||
|
private final Object lock = new Object();
|
||||||
|
@GuardedBy("lock")
|
||||||
|
private boolean held = false;
|
||||||
|
|
||||||
|
AndroidWakeLockImpl(SharedWakeLock sharedWakeLock, String tag) {
|
||||||
|
this.sharedWakeLock = sharedWakeLock;
|
||||||
|
this.tag = tag + "_" + INSTANCE_ID.getAndIncrement();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void acquire() {
|
||||||
|
synchronized (lock) {
|
||||||
|
if (held) {
|
||||||
|
if (LOG.isLoggable(FINE)) {
|
||||||
|
LOG.fine(tag + " already acquired");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (LOG.isLoggable(FINE)) {
|
||||||
|
LOG.fine(tag + " acquiring shared wake lock");
|
||||||
|
}
|
||||||
|
held = true;
|
||||||
|
sharedWakeLock.acquire();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void release() {
|
||||||
|
synchronized (lock) {
|
||||||
|
if (held) {
|
||||||
|
if (LOG.isLoggable(FINE)) {
|
||||||
|
LOG.fine(tag + " releasing shared wake lock");
|
||||||
|
}
|
||||||
|
held = false;
|
||||||
|
sharedWakeLock.release();
|
||||||
|
} else {
|
||||||
|
if (LOG.isLoggable(FINE)) {
|
||||||
|
LOG.fine(tag + " already released");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import android.app.Application;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.pm.PackageInfo;
|
||||||
|
import android.content.pm.PackageManager;
|
||||||
|
import android.os.PowerManager;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLock;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
|
||||||
|
import javax.inject.Inject;
|
||||||
|
|
||||||
|
import static android.content.Context.POWER_SERVICE;
|
||||||
|
import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
|
||||||
|
import static java.util.concurrent.TimeUnit.MINUTES;
|
||||||
|
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||||
|
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
||||||
|
|
||||||
|
@NotNullByDefault
|
||||||
|
class AndroidWakeLockManagerImpl implements AndroidWakeLockManager {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How often to replace the wake lock.
|
||||||
|
*/
|
||||||
|
private static final long LOCK_DURATION_MS = MINUTES.toMillis(1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Automatically release the lock this many milliseconds after it's due
|
||||||
|
* to have been replaced and released.
|
||||||
|
*/
|
||||||
|
private static final long SAFETY_MARGIN_MS = SECONDS.toMillis(30);
|
||||||
|
|
||||||
|
private final SharedWakeLock sharedWakeLock;
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
AndroidWakeLockManagerImpl(Application app,
|
||||||
|
ScheduledExecutorService scheduledExecutorService) {
|
||||||
|
PowerManager powerManager = (PowerManager)
|
||||||
|
requireNonNull(app.getSystemService(POWER_SERVICE));
|
||||||
|
String tag = getWakeLockTag(app);
|
||||||
|
sharedWakeLock = new RenewableWakeLock(powerManager,
|
||||||
|
scheduledExecutorService, PARTIAL_WAKE_LOCK, tag,
|
||||||
|
LOCK_DURATION_MS, SAFETY_MARGIN_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AndroidWakeLock createWakeLock(String tag) {
|
||||||
|
return new AndroidWakeLockImpl(sharedWakeLock, tag);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void runWakefully(Runnable r, String tag) {
|
||||||
|
AndroidWakeLock wakeLock = createWakeLock(tag);
|
||||||
|
wakeLock.acquire();
|
||||||
|
try {
|
||||||
|
r.run();
|
||||||
|
} finally {
|
||||||
|
wakeLock.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void executeWakefully(Runnable r, Executor executor, String tag) {
|
||||||
|
AndroidWakeLock wakeLock = createWakeLock(tag);
|
||||||
|
wakeLock.acquire();
|
||||||
|
try {
|
||||||
|
executor.execute(() -> {
|
||||||
|
try {
|
||||||
|
r.run();
|
||||||
|
} finally {
|
||||||
|
// Release the wake lock if the task throws an exception
|
||||||
|
wakeLock.release();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (Exception e) {
|
||||||
|
// Release the wake lock if the executor throws an exception when
|
||||||
|
// we submit the task (in which case the release() call above won't
|
||||||
|
// happen)
|
||||||
|
wakeLock.release();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void executeWakefully(Runnable r, String tag) {
|
||||||
|
AndroidWakeLock wakeLock = createWakeLock(tag);
|
||||||
|
wakeLock.acquire();
|
||||||
|
try {
|
||||||
|
new Thread(() -> {
|
||||||
|
try {
|
||||||
|
r.run();
|
||||||
|
} finally {
|
||||||
|
wakeLock.release();
|
||||||
|
}
|
||||||
|
}).start();
|
||||||
|
} catch (Exception e) {
|
||||||
|
wakeLock.release();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getWakeLockTag(Context ctx) {
|
||||||
|
PackageManager pm = ctx.getPackageManager();
|
||||||
|
for (PackageInfo info : pm.getInstalledPackages(0)) {
|
||||||
|
String name = info.packageName.toLowerCase();
|
||||||
|
if (name.startsWith("com.huawei.powergenie")) {
|
||||||
|
return "LocationManagerService";
|
||||||
|
} else if (name.startsWith("com.evenwell.powermonitor")) {
|
||||||
|
return "AudioIn";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ctx.getPackageName();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLockManager;
|
||||||
|
import org.briarproject.bramble.api.system.WakefulIoExecutor;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
|
import dagger.Module;
|
||||||
|
import dagger.Provides;
|
||||||
|
|
||||||
|
@Module
|
||||||
|
public
|
||||||
|
class AndroidWakefulIoExecutorModule {
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@WakefulIoExecutor
|
||||||
|
Executor provideWakefulIoExecutor(@IoExecutor Executor ioExecutor,
|
||||||
|
AndroidWakeLockManager wakeLockManager) {
|
||||||
|
return r -> wakeLockManager.executeWakefully(r, ioExecutor,
|
||||||
|
"WakefulIoExecutor");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import android.os.PowerManager;
|
||||||
|
import android.os.PowerManager.WakeLock;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
|
||||||
|
import java.util.concurrent.Future;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import javax.annotation.Nullable;
|
||||||
|
import javax.annotation.concurrent.GuardedBy;
|
||||||
|
import javax.annotation.concurrent.ThreadSafe;
|
||||||
|
|
||||||
|
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||||
|
import static java.util.logging.Level.FINE;
|
||||||
|
import static java.util.logging.Level.INFO;
|
||||||
|
import static java.util.logging.Level.WARNING;
|
||||||
|
import static java.util.logging.Logger.getLogger;
|
||||||
|
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
||||||
|
|
||||||
|
@ThreadSafe
|
||||||
|
@NotNullByDefault
|
||||||
|
class RenewableWakeLock implements SharedWakeLock {
|
||||||
|
|
||||||
|
private static final Logger LOG =
|
||||||
|
getLogger(RenewableWakeLock.class.getName());
|
||||||
|
|
||||||
|
private final PowerManager powerManager;
|
||||||
|
private final ScheduledExecutorService scheduledExecutorService;
|
||||||
|
private final int levelAndFlags;
|
||||||
|
private final String tag;
|
||||||
|
private final long durationMs, safetyMarginMs;
|
||||||
|
|
||||||
|
private final Object lock = new Object();
|
||||||
|
@GuardedBy("lock")
|
||||||
|
@Nullable
|
||||||
|
private WakeLock wakeLock;
|
||||||
|
@GuardedBy("lock")
|
||||||
|
@Nullable
|
||||||
|
private Future<?> future;
|
||||||
|
@GuardedBy("lock")
|
||||||
|
private int refCount = 0;
|
||||||
|
@GuardedBy("lock")
|
||||||
|
private long acquired = 0;
|
||||||
|
|
||||||
|
RenewableWakeLock(PowerManager powerManager,
|
||||||
|
ScheduledExecutorService scheduledExecutorService,
|
||||||
|
int levelAndFlags,
|
||||||
|
String tag,
|
||||||
|
long durationMs,
|
||||||
|
long safetyMarginMs) {
|
||||||
|
this.powerManager = powerManager;
|
||||||
|
this.scheduledExecutorService = scheduledExecutorService;
|
||||||
|
this.levelAndFlags = levelAndFlags;
|
||||||
|
this.tag = tag;
|
||||||
|
this.durationMs = durationMs;
|
||||||
|
this.safetyMarginMs = safetyMarginMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void acquire() {
|
||||||
|
synchronized (lock) {
|
||||||
|
refCount++;
|
||||||
|
if (refCount == 1) {
|
||||||
|
if (LOG.isLoggable(INFO)) {
|
||||||
|
LOG.info("Acquiring wake lock " + tag);
|
||||||
|
}
|
||||||
|
wakeLock = powerManager.newWakeLock(levelAndFlags, tag);
|
||||||
|
// We do our own reference counting so we can replace the lock
|
||||||
|
// TODO: Check whether using a ref-counted wake lock affects
|
||||||
|
// power management apps
|
||||||
|
wakeLock.setReferenceCounted(false);
|
||||||
|
wakeLock.acquire(durationMs + safetyMarginMs);
|
||||||
|
future = scheduledExecutorService.schedule(this::renew,
|
||||||
|
durationMs, MILLISECONDS);
|
||||||
|
acquired = android.os.SystemClock.elapsedRealtime();
|
||||||
|
} else if (LOG.isLoggable(FINE)) {
|
||||||
|
LOG.fine("Wake lock " + tag + " has " + refCount + " holders");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void renew() {
|
||||||
|
if (LOG.isLoggable(INFO)) LOG.info("Renewing wake lock " + tag);
|
||||||
|
synchronized (lock) {
|
||||||
|
if (wakeLock == null) {
|
||||||
|
LOG.info("Already released");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (LOG.isLoggable(FINE)) {
|
||||||
|
LOG.fine("Wake lock " + tag + " has " + refCount + " holders");
|
||||||
|
}
|
||||||
|
long now = android.os.SystemClock.elapsedRealtime();
|
||||||
|
long expiry = acquired + durationMs + safetyMarginMs;
|
||||||
|
if (now > expiry && LOG.isLoggable(WARNING)) {
|
||||||
|
LOG.warning("Wake lock expired " + (now - expiry) + " ms ago");
|
||||||
|
}
|
||||||
|
WakeLock oldWakeLock = wakeLock;
|
||||||
|
wakeLock = powerManager.newWakeLock(levelAndFlags, tag);
|
||||||
|
wakeLock.setReferenceCounted(false);
|
||||||
|
wakeLock.acquire(durationMs + safetyMarginMs);
|
||||||
|
oldWakeLock.release();
|
||||||
|
future = scheduledExecutorService.schedule(this::renew, durationMs,
|
||||||
|
MILLISECONDS);
|
||||||
|
acquired = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void release() {
|
||||||
|
synchronized (lock) {
|
||||||
|
refCount--;
|
||||||
|
if (refCount == 0) {
|
||||||
|
if (LOG.isLoggable(INFO)) {
|
||||||
|
LOG.info("Releasing wake lock " + tag);
|
||||||
|
}
|
||||||
|
requireNonNull(future).cancel(false);
|
||||||
|
future = null;
|
||||||
|
requireNonNull(wakeLock).release();
|
||||||
|
wakeLock = null;
|
||||||
|
acquired = 0;
|
||||||
|
} else if (LOG.isLoggable(FINE)) {
|
||||||
|
LOG.fine("Wake lock " + tag + " has " + refCount + " holders");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.system.AndroidWakeLock;
|
||||||
|
|
||||||
|
@NotNullByDefault
|
||||||
|
interface SharedWakeLock {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Acquires the wake lock. This increments the wake lock's reference count,
|
||||||
|
* so unlike {@link AndroidWakeLock#acquire()} every call to this method
|
||||||
|
* must be followed by a balancing call to {@link #release()}.
|
||||||
|
*/
|
||||||
|
void acquire();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Releases the wake lock. This decrements the wake lock's reference count,
|
||||||
|
* so unlike {@link AndroidWakeLock#release()} every call to this method
|
||||||
|
* must follow a balancing call to {@link #acquire()}.
|
||||||
|
*/
|
||||||
|
void release();
|
||||||
|
}
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
package org.briarproject.bramble.util;
|
|
||||||
|
|
||||||
import android.os.PowerManager;
|
|
||||||
|
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
|
||||||
|
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.concurrent.ScheduledFuture;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
import java.util.logging.Logger;
|
|
||||||
|
|
||||||
import javax.annotation.Nullable;
|
|
||||||
import javax.annotation.concurrent.ThreadSafe;
|
|
||||||
|
|
||||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
|
||||||
import static java.util.logging.Level.INFO;
|
|
||||||
|
|
||||||
@ThreadSafe
|
|
||||||
@NotNullByDefault
|
|
||||||
public class RenewableWakeLock {
|
|
||||||
|
|
||||||
private static final Logger LOG =
|
|
||||||
Logger.getLogger(RenewableWakeLock.class.getName());
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Automatically release the lock this many milliseconds after it's due
|
|
||||||
* to have been replaced and released.
|
|
||||||
*/
|
|
||||||
private static final int SAFETY_MARGIN_MS = 10_000;
|
|
||||||
|
|
||||||
private final PowerManager powerManager;
|
|
||||||
private final ScheduledExecutorService scheduler;
|
|
||||||
private final int levelAndFlags;
|
|
||||||
private final String tag;
|
|
||||||
private final long durationMs;
|
|
||||||
private final Runnable renewTask;
|
|
||||||
|
|
||||||
private final Object lock = new Object();
|
|
||||||
@Nullable
|
|
||||||
private PowerManager.WakeLock wakeLock; // Locking: lock
|
|
||||||
@Nullable
|
|
||||||
private ScheduledFuture future; // Locking: lock
|
|
||||||
|
|
||||||
public RenewableWakeLock(PowerManager powerManager,
|
|
||||||
ScheduledExecutorService scheduler, int levelAndFlags, String tag,
|
|
||||||
long duration, TimeUnit timeUnit) {
|
|
||||||
this.powerManager = powerManager;
|
|
||||||
this.scheduler = scheduler;
|
|
||||||
this.levelAndFlags = levelAndFlags;
|
|
||||||
this.tag = tag;
|
|
||||||
durationMs = MILLISECONDS.convert(duration, timeUnit);
|
|
||||||
renewTask = this::renew;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void acquire() {
|
|
||||||
if (LOG.isLoggable(INFO)) LOG.info("Acquiring wake lock " + tag);
|
|
||||||
synchronized (lock) {
|
|
||||||
if (wakeLock != null) {
|
|
||||||
LOG.info("Already acquired");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
wakeLock = powerManager.newWakeLock(levelAndFlags, tag);
|
|
||||||
wakeLock.setReferenceCounted(false);
|
|
||||||
wakeLock.acquire(durationMs + SAFETY_MARGIN_MS);
|
|
||||||
future = scheduler.schedule(renewTask, durationMs, MILLISECONDS);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void renew() {
|
|
||||||
if (LOG.isLoggable(INFO)) LOG.info("Renewing wake lock " + tag);
|
|
||||||
synchronized (lock) {
|
|
||||||
if (wakeLock == null) {
|
|
||||||
LOG.info("Already released");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
PowerManager.WakeLock oldWakeLock = wakeLock;
|
|
||||||
wakeLock = powerManager.newWakeLock(levelAndFlags, tag);
|
|
||||||
wakeLock.setReferenceCounted(false);
|
|
||||||
wakeLock.acquire(durationMs + SAFETY_MARGIN_MS);
|
|
||||||
oldWakeLock.release();
|
|
||||||
future = scheduler.schedule(renewTask, durationMs, MILLISECONDS);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void release() {
|
|
||||||
if (LOG.isLoggable(INFO)) LOG.info("Releasing wake lock " + tag);
|
|
||||||
synchronized (lock) {
|
|
||||||
if (wakeLock == null) {
|
|
||||||
LOG.info("Already released");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (future == null) throw new AssertionError();
|
|
||||||
future.cancel(false);
|
|
||||||
future = null;
|
|
||||||
wakeLock.release();
|
|
||||||
wakeLock = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -18,6 +18,8 @@ public interface EventBus {
|
|||||||
/**
|
/**
|
||||||
* Asynchronously notifies all listeners of an event. Listeners are
|
* Asynchronously notifies all listeners of an event. Listeners are
|
||||||
* notified on the {@link EventExecutor}.
|
* notified on the {@link EventExecutor}.
|
||||||
|
* <p>
|
||||||
|
* This method can safely be called while holding a lock.
|
||||||
*/
|
*/
|
||||||
void broadcast(Event e);
|
void broadcast(Event e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,10 @@ public interface TimeoutMonitor {
|
|||||||
/**
|
/**
|
||||||
* Returns an {@link InputStream} that wraps the given stream and allows
|
* Returns an {@link InputStream} that wraps the given stream and allows
|
||||||
* read timeouts to be detected.
|
* read timeouts to be detected.
|
||||||
|
* <p>
|
||||||
|
* The returned stream must be {@link InputStream#close() closed} when it's
|
||||||
|
* no longer needed to ensure that resources held by the timeout monitor
|
||||||
|
* are released.
|
||||||
*
|
*
|
||||||
* @param timeoutMs The read timeout in milliseconds. Timeouts will be
|
* @param timeoutMs The read timeout in milliseconds. Timeouts will be
|
||||||
* detected eventually but are not guaranteed to be detected immediately.
|
* detected eventually but are not guaranteed to be detected immediately.
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import org.briarproject.bramble.api.db.DatabaseComponent;
|
|||||||
import org.briarproject.bramble.api.db.DbException;
|
import org.briarproject.bramble.api.db.DbException;
|
||||||
import org.briarproject.bramble.api.db.Transaction;
|
import org.briarproject.bramble.api.db.Transaction;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.system.Wakeful;
|
||||||
|
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
|
|
||||||
@@ -65,6 +66,7 @@ public interface LifecycleManager {
|
|||||||
* Opens the {@link DatabaseComponent} using the given key and starts any
|
* Opens the {@link DatabaseComponent} using the given key and starts any
|
||||||
* registered {@link Service Services}.
|
* registered {@link Service Services}.
|
||||||
*/
|
*/
|
||||||
|
@Wakeful
|
||||||
StartResult startServices(SecretKey dbKey);
|
StartResult startServices(SecretKey dbKey);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -72,6 +74,7 @@ public interface LifecycleManager {
|
|||||||
* registered {@link ExecutorService ExecutorServices}, and closes the
|
* registered {@link ExecutorService ExecutorServices}, and closes the
|
||||||
* {@link DatabaseComponent}.
|
* {@link DatabaseComponent}.
|
||||||
*/
|
*/
|
||||||
|
@Wakeful
|
||||||
void stopServices();
|
void stopServices();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -104,6 +107,7 @@ public interface LifecycleManager {
|
|||||||
*
|
*
|
||||||
* @param txn A read-write transaction
|
* @param txn A read-write transaction
|
||||||
*/
|
*/
|
||||||
|
@Wakeful
|
||||||
void onDatabaseOpened(Transaction txn) throws DbException;
|
void onDatabaseOpened(Transaction txn) throws DbException;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,20 @@
|
|||||||
package org.briarproject.bramble.api.lifecycle;
|
package org.briarproject.bramble.api.lifecycle;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.system.Wakeful;
|
||||||
|
|
||||||
public interface Service {
|
public interface Service {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts the service.This method must not be called concurrently with
|
* Starts the service. This method must not be called concurrently with
|
||||||
* {@link #stopService()}.
|
* {@link #stopService()}.
|
||||||
*/
|
*/
|
||||||
|
@Wakeful
|
||||||
void startService() throws ServiceException;
|
void startService() throws ServiceException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stops the service. This method must not be called concurrently with
|
* Stops the service. This method must not be called concurrently with
|
||||||
* {@link #startService()}.
|
* {@link #startService()}.
|
||||||
*/
|
*/
|
||||||
|
@Wakeful
|
||||||
void stopService() throws ServiceException;
|
void stopService() throws ServiceException;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,16 @@ public interface BluetoothConstants {
|
|||||||
|
|
||||||
int UUID_BYTES = 16;
|
int UUID_BYTES = 16;
|
||||||
|
|
||||||
|
// Transport properties
|
||||||
String PROP_ADDRESS = "address";
|
String PROP_ADDRESS = "address";
|
||||||
String PROP_UUID = "uuid";
|
String PROP_UUID = "uuid";
|
||||||
|
|
||||||
String PREF_BT_ENABLE = "enable";
|
// Local settings (not shared with contacts)
|
||||||
|
String PREF_ADDRESS_IS_REFLECTED = "addressIsReflected";
|
||||||
|
String PREF_EVER_CONNECTED = "everConnected";
|
||||||
|
|
||||||
|
// Default values for local settings
|
||||||
|
boolean DEFAULT_PREF_PLUGIN_ENABLE = false;
|
||||||
|
boolean DEFAULT_PREF_ADDRESS_IS_REFLECTED = false;
|
||||||
|
boolean DEFAULT_PREF_EVER_CONNECTED = false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,12 @@ public interface LanTcpConstants {
|
|||||||
// Transport properties (shared with contacts)
|
// Transport properties (shared with contacts)
|
||||||
String PROP_IP_PORTS = "ipPorts";
|
String PROP_IP_PORTS = "ipPorts";
|
||||||
String PROP_PORT = "port";
|
String PROP_PORT = "port";
|
||||||
|
String PROP_IPV6 = "ipv6";
|
||||||
|
|
||||||
// A local setting
|
// Local settings (not shared with contacts)
|
||||||
String PREF_LAN_IP_PORTS = "ipPorts";
|
String PREF_LAN_IP_PORTS = "ipPorts";
|
||||||
|
String PREF_IPV6 = "ipv6";
|
||||||
|
|
||||||
|
// Default value for PREF_PLUGIN_ENABLE
|
||||||
|
boolean DEFAULT_PREF_PLUGIN_ENABLE = true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,56 @@ package org.briarproject.bramble.api.plugin;
|
|||||||
import org.briarproject.bramble.api.Pair;
|
import org.briarproject.bramble.api.Pair;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
|
import org.briarproject.bramble.api.settings.SettingsManager;
|
||||||
|
import org.briarproject.bramble.api.system.Wakeful;
|
||||||
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
|
|
||||||
@NotNullByDefault
|
@NotNullByDefault
|
||||||
public interface Plugin {
|
public interface Plugin {
|
||||||
|
|
||||||
|
enum State {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The plugin has not finished starting or has been stopped.
|
||||||
|
*/
|
||||||
|
STARTING_STOPPING,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The plugin is disabled by settings. Use {@link #getReasonsDisabled()}
|
||||||
|
* to find out which settings are responsible.
|
||||||
|
*/
|
||||||
|
DISABLED,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The plugin is being enabled and can't yet make or receive
|
||||||
|
* connections.
|
||||||
|
*/
|
||||||
|
ENABLING,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The plugin is enabled and can make or receive connections.
|
||||||
|
*/
|
||||||
|
ACTIVE,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The plugin is enabled but can't make or receive connections
|
||||||
|
*/
|
||||||
|
INACTIVE
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The string for the boolean preference
|
||||||
|
* to use with the {@link SettingsManager} to enable or disable the plugin.
|
||||||
|
*/
|
||||||
|
String PREF_PLUGIN_ENABLE = "enable";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reason flag returned by {@link #getReasonsDisabled()} to indicate that
|
||||||
|
* the plugin has been disabled by the user.
|
||||||
|
*/
|
||||||
|
int REASON_USER = 1;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the plugin's transport identifier.
|
* Returns the plugin's transport identifier.
|
||||||
*/
|
*/
|
||||||
@@ -27,17 +71,28 @@ public interface Plugin {
|
|||||||
/**
|
/**
|
||||||
* Starts the plugin.
|
* Starts the plugin.
|
||||||
*/
|
*/
|
||||||
|
@Wakeful
|
||||||
void start() throws PluginException;
|
void start() throws PluginException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stops the plugin.
|
* Stops the plugin.
|
||||||
*/
|
*/
|
||||||
|
@Wakeful
|
||||||
void stop() throws PluginException;
|
void stop() throws PluginException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns true if the plugin is running.
|
* Returns the current state of the plugin.
|
||||||
*/
|
*/
|
||||||
boolean isRunning();
|
State getState();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a set of flags indicating why the plugin is
|
||||||
|
* {@link State#DISABLED disabled}, or 0 if the plugin is not disabled.
|
||||||
|
* <p>
|
||||||
|
* The flags used are plugin-specific, except the generic flag
|
||||||
|
* {@link #REASON_USER}, which may be used by any plugin.
|
||||||
|
*/
|
||||||
|
int getReasonsDisabled();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns true if the plugin should be polled periodically to attempt to
|
* Returns true if the plugin should be polled periodically to attempt to
|
||||||
@@ -54,6 +109,7 @@ public interface Plugin {
|
|||||||
* Attempts to create connections using the given transport properties,
|
* Attempts to create connections using the given transport properties,
|
||||||
* passing any created connections to the corresponding handlers.
|
* passing any created connections to the corresponding handlers.
|
||||||
*/
|
*/
|
||||||
|
@Wakeful
|
||||||
void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
||||||
properties);
|
properties);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
package org.briarproject.bramble.api.plugin;
|
package org.briarproject.bramble.api.plugin;
|
||||||
|
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.plugin.Plugin.State;
|
||||||
|
import org.briarproject.bramble.api.plugin.event.TransportActiveEvent;
|
||||||
|
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||||
|
import org.briarproject.bramble.api.plugin.event.TransportStateEvent;
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
import org.briarproject.bramble.api.settings.Settings;
|
import org.briarproject.bramble.api.settings.Settings;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An interface through which a transport plugin interacts with the rest of
|
* An interface through which a transport plugin interacts with the rest of
|
||||||
* the application.
|
* the application.
|
||||||
@@ -21,6 +27,11 @@ public interface PluginCallback extends ConnectionHandler {
|
|||||||
*/
|
*/
|
||||||
TransportProperties getLocalProperties();
|
TransportProperties getLocalProperties();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the plugin's remote transport properties.
|
||||||
|
*/
|
||||||
|
Collection<TransportProperties> getRemoteProperties();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Merges the given settings with the plugin's settings
|
* Merges the given settings with the plugin's settings
|
||||||
*/
|
*/
|
||||||
@@ -32,12 +43,17 @@ public interface PluginCallback extends ConnectionHandler {
|
|||||||
void mergeLocalProperties(TransportProperties p);
|
void mergeLocalProperties(TransportProperties p);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Signals that the transport is enabled.
|
* Informs the callback of the plugin's current state.
|
||||||
|
* <p>
|
||||||
|
* If the current state is different from the previous state, the callback
|
||||||
|
* will broadcast a {@link TransportStateEvent}. If the current state is
|
||||||
|
* {@link State#ACTIVE} and the previous state was not
|
||||||
|
* {@link State#ACTIVE}, the callback will broadcast a
|
||||||
|
* {@link TransportActiveEvent}. If the current state is not
|
||||||
|
* {@link State#ACTIVE} and the previous state was {@link State#ACTIVE},
|
||||||
|
* the callback will broadcast a {@link TransportInactiveEvent}.
|
||||||
|
* <p>
|
||||||
|
* This method can safely be called while holding a lock.
|
||||||
*/
|
*/
|
||||||
void transportEnabled();
|
void pluginStateChanged(State state);
|
||||||
|
|
||||||
/**
|
|
||||||
* Signals that the transport is disabled.
|
|
||||||
*/
|
|
||||||
void transportDisabled();
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,4 +41,17 @@ public interface PluginManager {
|
|||||||
* Returns any duplex plugins that support rendezvous.
|
* Returns any duplex plugins that support rendezvous.
|
||||||
*/
|
*/
|
||||||
Collection<DuplexPlugin> getRendezvousPlugins();
|
Collection<DuplexPlugin> getRendezvousPlugins();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enables or disables the plugin
|
||||||
|
* identified by the given {@link TransportId}.
|
||||||
|
* <p>
|
||||||
|
* Note that this applies the change asynchronously
|
||||||
|
* and there are no order guarantees.
|
||||||
|
* <p>
|
||||||
|
* If no plugin with the given {@link TransportId} is registered,
|
||||||
|
* this is a no-op.
|
||||||
|
*/
|
||||||
|
void setPluginEnabled(TransportId t, boolean enabled);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
package org.briarproject.bramble.api.plugin;
|
package org.briarproject.bramble.api.plugin;
|
||||||
|
|
||||||
|
import static java.util.concurrent.TimeUnit.DAYS;
|
||||||
|
|
||||||
public interface TorConstants {
|
public interface TorConstants {
|
||||||
|
|
||||||
TransportId ID = new TransportId("org.briarproject.bramble.tor");
|
TransportId ID = new TransportId("org.briarproject.bramble.tor");
|
||||||
|
|
||||||
|
// Transport properties
|
||||||
String PROP_ONION_V2 = "onion";
|
String PROP_ONION_V2 = "onion";
|
||||||
String PROP_ONION_V3 = "onion3";
|
String PROP_ONION_V3 = "onion3";
|
||||||
|
|
||||||
@@ -13,14 +16,45 @@ public interface TorConstants {
|
|||||||
int CONNECT_TO_PROXY_TIMEOUT = 5000; // Milliseconds
|
int CONNECT_TO_PROXY_TIMEOUT = 5000; // Milliseconds
|
||||||
int EXTRA_SOCKET_TIMEOUT = 30000; // Milliseconds
|
int EXTRA_SOCKET_TIMEOUT = 30000; // Milliseconds
|
||||||
|
|
||||||
|
// Local settings (not shared with contacts)
|
||||||
String PREF_TOR_NETWORK = "network2";
|
String PREF_TOR_NETWORK = "network2";
|
||||||
String PREF_TOR_PORT = "port";
|
String PREF_TOR_PORT = "port";
|
||||||
String PREF_TOR_MOBILE = "useMobileData";
|
String PREF_TOR_MOBILE = "useMobileData";
|
||||||
String PREF_TOR_ONLY_WHEN_CHARGING = "onlyWhenCharging";
|
String PREF_TOR_ONLY_WHEN_CHARGING = "onlyWhenCharging";
|
||||||
|
String HS_PRIVATE_KEY_V2 = "onionPrivKey";
|
||||||
|
String HS_PRIVATE_KEY_V3 = "onionPrivKey3";
|
||||||
|
String HS_V3_CREATED = "onionPrivKey3Created";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How long to publish a v3 hidden service before retiring the v2 service.
|
||||||
|
*/
|
||||||
|
long V3_MIGRATION_PERIOD_MS = DAYS.toMillis(180);
|
||||||
|
|
||||||
|
// Values for PREF_TOR_NETWORK
|
||||||
int PREF_TOR_NETWORK_AUTOMATIC = 0;
|
int PREF_TOR_NETWORK_AUTOMATIC = 0;
|
||||||
int PREF_TOR_NETWORK_WITHOUT_BRIDGES = 1;
|
int PREF_TOR_NETWORK_WITHOUT_BRIDGES = 1;
|
||||||
int PREF_TOR_NETWORK_WITH_BRIDGES = 2;
|
int PREF_TOR_NETWORK_WITH_BRIDGES = 2;
|
||||||
|
// TODO: Remove when settings migration code is removed
|
||||||
int PREF_TOR_NETWORK_NEVER = 3;
|
int PREF_TOR_NETWORK_NEVER = 3;
|
||||||
|
|
||||||
|
// Default values for local settings
|
||||||
|
boolean DEFAULT_PREF_PLUGIN_ENABLE = true;
|
||||||
|
int DEFAULT_PREF_TOR_NETWORK = PREF_TOR_NETWORK_AUTOMATIC;
|
||||||
|
boolean DEFAULT_PREF_TOR_MOBILE = true;
|
||||||
|
boolean DEFAULT_PREF_TOR_ONLY_WHEN_CHARGING = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reason flag returned by {@link Plugin#getReasonsDisabled()}.
|
||||||
|
*/
|
||||||
|
int REASON_BATTERY = 2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reason flag returned by {@link Plugin#getReasonsDisabled()}.
|
||||||
|
*/
|
||||||
|
int REASON_MOBILE_DATA = 4;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reason flag returned by {@link Plugin#getReasonsDisabled()}.
|
||||||
|
*/
|
||||||
|
int REASON_COUNTRY_BLOCKED = 8;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package org.briarproject.bramble.api.system;
|
package org.briarproject.bramble.api.plugin;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
import java.lang.annotation.Retention;
|
import java.lang.annotation.Retention;
|
||||||
import java.lang.annotation.Target;
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
@@ -11,15 +12,11 @@ import static java.lang.annotation.ElementType.PARAMETER;
|
|||||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Annotation for injecting a scheduled executor service
|
* Annotation for injecting the {@link File directory} where the Tor plugin
|
||||||
* that can be used to schedule the execution of tasks.
|
* should store its state.
|
||||||
* <p>
|
|
||||||
* The service should <b>only</b> be used for running tasks on other executors
|
|
||||||
* at scheduled times.
|
|
||||||
* No significant work should be run by the service itself!
|
|
||||||
*/
|
*/
|
||||||
@Qualifier
|
@Qualifier
|
||||||
@Target({FIELD, METHOD, PARAMETER})
|
@Target({FIELD, METHOD, PARAMETER})
|
||||||
@Retention(RUNTIME)
|
@Retention(RUNTIME)
|
||||||
public @interface Scheduler {
|
public @interface TorDirectory {
|
||||||
}
|
}
|
||||||
@@ -4,4 +4,7 @@ public interface WanTcpConstants {
|
|||||||
|
|
||||||
TransportId ID = new TransportId("org.briarproject.bramble.wan");
|
TransportId ID = new TransportId("org.briarproject.bramble.wan");
|
||||||
|
|
||||||
|
// Default value for PREF_PLUGIN_ENABLE
|
||||||
|
boolean DEFAULT_PREF_PLUGIN_ENABLE = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import org.briarproject.bramble.api.plugin.Plugin;
|
|||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
||||||
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
||||||
|
import org.briarproject.bramble.api.system.Wakeful;
|
||||||
|
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
|
|
||||||
@@ -21,6 +22,7 @@ public interface DuplexPlugin extends Plugin {
|
|||||||
* Attempts to create and return a connection using the given transport
|
* Attempts to create and return a connection using the given transport
|
||||||
* properties. Returns null if a connection cannot be created.
|
* properties. Returns null if a connection cannot be created.
|
||||||
*/
|
*/
|
||||||
|
@Wakeful
|
||||||
@Nullable
|
@Nullable
|
||||||
DuplexTransportConnection createConnection(TransportProperties p);
|
DuplexTransportConnection createConnection(TransportProperties p);
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
package org.briarproject.bramble.api.plugin.event;
|
|
||||||
|
|
||||||
import org.briarproject.bramble.api.event.Event;
|
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
|
||||||
|
|
||||||
import javax.annotation.concurrent.Immutable;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An event that informs the Bluetooth plugin that we have enabled the
|
|
||||||
* Bluetooth adapter.
|
|
||||||
*/
|
|
||||||
@Immutable
|
|
||||||
@NotNullByDefault
|
|
||||||
public class BluetoothEnabledEvent extends Event {
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package org.briarproject.bramble.api.plugin.event;
|
|
||||||
|
|
||||||
import org.briarproject.bramble.api.event.Event;
|
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
|
||||||
|
|
||||||
import javax.annotation.concurrent.Immutable;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An event that asks the Bluetooth plugin to disable the Bluetooth adapter if
|
|
||||||
* we previously enabled it.
|
|
||||||
*/
|
|
||||||
@Immutable
|
|
||||||
@NotNullByDefault
|
|
||||||
public class DisableBluetoothEvent extends Event {
|
|
||||||
}
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package org.briarproject.bramble.api.plugin.event;
|
|
||||||
|
|
||||||
import org.briarproject.bramble.api.event.Event;
|
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
|
||||||
|
|
||||||
import javax.annotation.concurrent.Immutable;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* An event that asks the Bluetooth plugin to enable the Bluetooth adapter.
|
|
||||||
*/
|
|
||||||
@Immutable
|
|
||||||
@NotNullByDefault
|
|
||||||
public class EnableBluetoothEvent extends Event {
|
|
||||||
}
|
|
||||||
@@ -2,20 +2,22 @@ package org.briarproject.bramble.api.plugin.event;
|
|||||||
|
|
||||||
import org.briarproject.bramble.api.event.Event;
|
import org.briarproject.bramble.api.event.Event;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.plugin.Plugin.State;
|
||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
|
|
||||||
import javax.annotation.concurrent.Immutable;
|
import javax.annotation.concurrent.Immutable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An event that is broadcast when a transport is disabled.
|
* An event that is broadcast when a plugin enters the {@link State#ACTIVE}
|
||||||
|
* state.
|
||||||
*/
|
*/
|
||||||
@Immutable
|
@Immutable
|
||||||
@NotNullByDefault
|
@NotNullByDefault
|
||||||
public class TransportDisabledEvent extends Event {
|
public class TransportActiveEvent extends Event {
|
||||||
|
|
||||||
private final TransportId transportId;
|
private final TransportId transportId;
|
||||||
|
|
||||||
public TransportDisabledEvent(TransportId transportId) {
|
public TransportActiveEvent(TransportId transportId) {
|
||||||
this.transportId = transportId;
|
this.transportId = transportId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2,20 +2,22 @@ package org.briarproject.bramble.api.plugin.event;
|
|||||||
|
|
||||||
import org.briarproject.bramble.api.event.Event;
|
import org.briarproject.bramble.api.event.Event;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.plugin.Plugin.State;
|
||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
|
|
||||||
import javax.annotation.concurrent.Immutable;
|
import javax.annotation.concurrent.Immutable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An event that is broadcast when a transport is enabled.
|
* An event that is broadcast when a plugin leaves the {@link State#ACTIVE}
|
||||||
|
* state.
|
||||||
*/
|
*/
|
||||||
@Immutable
|
@Immutable
|
||||||
@NotNullByDefault
|
@NotNullByDefault
|
||||||
public class TransportEnabledEvent extends Event {
|
public class TransportInactiveEvent extends Event {
|
||||||
|
|
||||||
private final TransportId transportId;
|
private final TransportId transportId;
|
||||||
|
|
||||||
public TransportEnabledEvent(TransportId transportId) {
|
public TransportInactiveEvent(TransportId transportId) {
|
||||||
this.transportId = transportId;
|
this.transportId = transportId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package org.briarproject.bramble.api.plugin.event;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.event.Event;
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.plugin.Plugin.State;
|
||||||
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
|
|
||||||
|
import javax.annotation.concurrent.Immutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An event that is broadcast when the {@link State state} of a plugin changes.
|
||||||
|
*/
|
||||||
|
@Immutable
|
||||||
|
@NotNullByDefault
|
||||||
|
public class TransportStateEvent extends Event {
|
||||||
|
|
||||||
|
private final TransportId transportId;
|
||||||
|
private final State state;
|
||||||
|
|
||||||
|
public TransportStateEvent(TransportId transportId, State state) {
|
||||||
|
this.transportId = transportId;
|
||||||
|
this.state = state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TransportId getTransportId() {
|
||||||
|
return transportId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public State getState() {
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import org.briarproject.bramble.api.plugin.Plugin;
|
|||||||
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
|
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
|
||||||
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
|
import org.briarproject.bramble.api.system.Wakeful;
|
||||||
|
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
|
|
||||||
@@ -18,6 +19,7 @@ public interface SimplexPlugin extends Plugin {
|
|||||||
* Attempts to create and return a reader for the given transport
|
* Attempts to create and return a reader for the given transport
|
||||||
* properties. Returns null if a reader cannot be created.
|
* properties. Returns null if a reader cannot be created.
|
||||||
*/
|
*/
|
||||||
|
@Wakeful
|
||||||
@Nullable
|
@Nullable
|
||||||
TransportConnectionReader createReader(TransportProperties p);
|
TransportConnectionReader createReader(TransportProperties p);
|
||||||
|
|
||||||
@@ -25,6 +27,7 @@ public interface SimplexPlugin extends Plugin {
|
|||||||
* Attempts to create and return a writer for the given transport
|
* Attempts to create and return a writer for the given transport
|
||||||
* properties. Returns null if a writer cannot be created.
|
* properties. Returns null if a writer cannot be created.
|
||||||
*/
|
*/
|
||||||
|
@Wakeful
|
||||||
@Nullable
|
@Nullable
|
||||||
TransportConnectionWriter createWriter(TransportProperties p);
|
TransportConnectionWriter createWriter(TransportProperties p);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,11 @@ public interface TransportPropertyConstants {
|
|||||||
*/
|
*/
|
||||||
int MAX_PROPERTY_LENGTH = 100;
|
int MAX_PROPERTY_LENGTH = 100;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prefix for keys that represent reflected properties.
|
||||||
|
*/
|
||||||
|
String REFLECTED_PROPERTY_PREFIX = "u:";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Message metadata key for the transport ID of a local or remote update,
|
* Message metadata key for the transport ID of a local or remote update,
|
||||||
* as a BDF string.
|
* as a BDF string.
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package org.briarproject.bramble.api.properties.event;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.event.Event;
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
|
|
||||||
|
import javax.annotation.concurrent.Immutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An event that is broadcast when {@link TransportProperties} are received
|
||||||
|
* from a contact.
|
||||||
|
*/
|
||||||
|
@Immutable
|
||||||
|
@NotNullByDefault
|
||||||
|
public class RemoteTransportPropertiesUpdatedEvent extends Event {
|
||||||
|
|
||||||
|
private final TransportId transportId;
|
||||||
|
|
||||||
|
public RemoteTransportPropertiesUpdatedEvent(TransportId transportId) {
|
||||||
|
this.transportId = transportId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public TransportId getTransportId() {
|
||||||
|
return transportId;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package org.briarproject.bramble.api.system;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A service that can be used to schedule the execution of tasks.
|
||||||
|
*/
|
||||||
|
@NotNullByDefault
|
||||||
|
public interface TaskScheduler {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Submits the given task to the given executor after the given delay.
|
||||||
|
* <p>
|
||||||
|
* If the platform supports wake locks, a wake lock will be held while
|
||||||
|
* submitting and running the task.
|
||||||
|
*/
|
||||||
|
Cancellable schedule(Runnable task, Executor executor, long delay,
|
||||||
|
TimeUnit unit);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Submits the given task to the given executor after the given delay,
|
||||||
|
* and then repeatedly with the given interval between executions
|
||||||
|
* (measured from the end of one execution to the beginning of the next).
|
||||||
|
* <p>
|
||||||
|
* If the platform supports wake locks, a wake lock will be held while
|
||||||
|
* submitting and running the task.
|
||||||
|
*/
|
||||||
|
Cancellable scheduleWithFixedDelay(Runnable task, Executor executor,
|
||||||
|
long delay, long interval, TimeUnit unit);
|
||||||
|
|
||||||
|
interface Cancellable {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancels the task if it has not already started running. If the task
|
||||||
|
* is {@link #scheduleWithFixedDelay(Runnable, Executor, long, long, TimeUnit) periodic},
|
||||||
|
* all future executions of the task are cancelled.
|
||||||
|
*/
|
||||||
|
void cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package org.briarproject.bramble.api.system;
|
||||||
|
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
import javax.inject.Qualifier;
|
||||||
|
|
||||||
|
import static java.lang.annotation.ElementType.METHOD;
|
||||||
|
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Annotation for methods that must be called while holding a wake lock, if
|
||||||
|
* the platform supports wake locks.
|
||||||
|
*/
|
||||||
|
@Qualifier
|
||||||
|
@Target(METHOD)
|
||||||
|
@Retention(RUNTIME)
|
||||||
|
public @interface Wakeful {
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package org.briarproject.bramble.api.system;
|
||||||
|
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
import javax.inject.Qualifier;
|
||||||
|
|
||||||
|
import static java.lang.annotation.ElementType.FIELD;
|
||||||
|
import static java.lang.annotation.ElementType.METHOD;
|
||||||
|
import static java.lang.annotation.ElementType.PARAMETER;
|
||||||
|
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Annotation for injecting the executor for long-running IO tasks that should
|
||||||
|
* run without sleeping. Also used for annotating methods that should run on
|
||||||
|
* this executor.
|
||||||
|
* <p>
|
||||||
|
* The contract of this executor is that tasks may be run concurrently, and
|
||||||
|
* submitting a task will never block. Tasks must not run indefinitely. Tasks
|
||||||
|
* submitted during shutdown are discarded.
|
||||||
|
*/
|
||||||
|
@Qualifier
|
||||||
|
@Target({FIELD, METHOD, PARAMETER})
|
||||||
|
@Retention(RUNTIME)
|
||||||
|
public @interface WakefulIoExecutor {
|
||||||
|
}
|
||||||
@@ -2,13 +2,17 @@ package org.briarproject.bramble.util;
|
|||||||
|
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
|
||||||
import java.net.Inet6Address;
|
import java.net.Inet4Address;
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
import java.net.SocketAddress;
|
import java.net.SocketAddress;
|
||||||
|
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
|
|
||||||
|
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
||||||
|
import static org.briarproject.bramble.util.StringUtils.isValidMac;
|
||||||
|
import static org.briarproject.bramble.util.StringUtils.toHexString;
|
||||||
|
|
||||||
@NotNullByDefault
|
@NotNullByDefault
|
||||||
public class PrivacyUtils {
|
public class PrivacyUtils {
|
||||||
|
|
||||||
@@ -19,7 +23,7 @@ public class PrivacyUtils {
|
|||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
public static String scrubMacAddress(@Nullable String address) {
|
public static String scrubMacAddress(@Nullable String address) {
|
||||||
if (address == null || address.length() == 0) return null;
|
if (isNullOrEmpty(address) || !isValidMac(address)) return address;
|
||||||
// this is a fake address we need to know about
|
// this is a fake address we need to know about
|
||||||
if (address.equals("02:00:00:00:00:00")) return address;
|
if (address.equals("02:00:00:00:00:00")) return address;
|
||||||
// keep first and last octet of MAC address
|
// keep first and last octet of MAC address
|
||||||
@@ -27,39 +31,37 @@ public class PrivacyUtils {
|
|||||||
+ address.substring(14, 17);
|
+ address.substring(14, 17);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
|
||||||
public static String scrubInetAddress(InetAddress address) {
|
public static String scrubInetAddress(InetAddress address) {
|
||||||
// don't scrub link and site local addresses
|
if (address instanceof Inet4Address) {
|
||||||
if (address.isLinkLocalAddress() || address.isSiteLocalAddress())
|
// Don't scrub local IPv4 addresses
|
||||||
return address.toString();
|
if (address.isLoopbackAddress() || address.isLinkLocalAddress() ||
|
||||||
// completely scrub IPv6 addresses
|
address.isSiteLocalAddress()) {
|
||||||
if (address instanceof Inet6Address) return "[scrubbed]";
|
return address.getHostAddress();
|
||||||
// keep first and last octet of IPv4 addresses
|
}
|
||||||
return scrubInetAddress(address.toString());
|
// Keep first and last octet of non-local IPv4 addresses
|
||||||
|
return scrubIpv4Address(address.getAddress());
|
||||||
|
} else {
|
||||||
|
// Keep first and last octet of IPv6 addresses
|
||||||
|
return scrubIpv6Address(address.getAddress());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
private static String scrubIpv4Address(byte[] ipv4) {
|
||||||
public static String scrubInetAddress(@Nullable String address) {
|
return (ipv4[0] & 0xFF) + ".[scrubbed]." + (ipv4[3] & 0xFF);
|
||||||
if (address == null) return null;
|
}
|
||||||
|
|
||||||
int firstDot = address.indexOf(".");
|
private static String scrubIpv6Address(byte[] ipv6) {
|
||||||
if (firstDot == -1) return "[scrubbed]";
|
String hex = toHexString(ipv6).toLowerCase();
|
||||||
String prefix = address.substring(0, firstDot + 1);
|
return hex.substring(0, 2) + "[scrubbed]" + hex.substring(30);
|
||||||
int lastDot = address.lastIndexOf(".");
|
|
||||||
String suffix = address.substring(lastDot, address.length());
|
|
||||||
return prefix + "[scrubbed]" + suffix;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
|
||||||
public static String scrubSocketAddress(InetSocketAddress address) {
|
public static String scrubSocketAddress(InetSocketAddress address) {
|
||||||
InetAddress inetAddress = address.getAddress();
|
return scrubInetAddress(address.getAddress());
|
||||||
return scrubInetAddress(inetAddress);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nullable
|
|
||||||
public static String scrubSocketAddress(SocketAddress address) {
|
public static String scrubSocketAddress(SocketAddress address) {
|
||||||
if (address instanceof InetSocketAddress)
|
if (address instanceof InetSocketAddress)
|
||||||
return scrubSocketAddress((InetSocketAddress) address);
|
return scrubSocketAddress((InetSocketAddress) address);
|
||||||
return scrubInetAddress(address.toString());
|
return "[scrubbed]";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import org.briarproject.bramble.plugin.PluginModule;
|
|||||||
import org.briarproject.bramble.properties.PropertiesModule;
|
import org.briarproject.bramble.properties.PropertiesModule;
|
||||||
import org.briarproject.bramble.rendezvous.RendezvousModule;
|
import org.briarproject.bramble.rendezvous.RendezvousModule;
|
||||||
import org.briarproject.bramble.sync.validation.ValidationModule;
|
import org.briarproject.bramble.sync.validation.ValidationModule;
|
||||||
import org.briarproject.bramble.system.SystemModule;
|
|
||||||
import org.briarproject.bramble.transport.TransportModule;
|
import org.briarproject.bramble.transport.TransportModule;
|
||||||
import org.briarproject.bramble.versioning.VersioningModule;
|
import org.briarproject.bramble.versioning.VersioningModule;
|
||||||
|
|
||||||
@@ -31,8 +30,6 @@ public interface BrambleCoreEagerSingletons {
|
|||||||
|
|
||||||
void inject(RendezvousModule.EagerSingletons init);
|
void inject(RendezvousModule.EagerSingletons init);
|
||||||
|
|
||||||
void inject(SystemModule.EagerSingletons init);
|
|
||||||
|
|
||||||
void inject(TransportModule.EagerSingletons init);
|
void inject(TransportModule.EagerSingletons init);
|
||||||
|
|
||||||
void inject(ValidationModule.EagerSingletons init);
|
void inject(ValidationModule.EagerSingletons init);
|
||||||
@@ -50,7 +47,6 @@ public interface BrambleCoreEagerSingletons {
|
|||||||
c.inject(new RendezvousModule.EagerSingletons());
|
c.inject(new RendezvousModule.EagerSingletons());
|
||||||
c.inject(new PluginModule.EagerSingletons());
|
c.inject(new PluginModule.EagerSingletons());
|
||||||
c.inject(new PropertiesModule.EagerSingletons());
|
c.inject(new PropertiesModule.EagerSingletons());
|
||||||
c.inject(new SystemModule.EagerSingletons());
|
|
||||||
c.inject(new TransportModule.EagerSingletons());
|
c.inject(new TransportModule.EagerSingletons());
|
||||||
c.inject(new ValidationModule.EagerSingletons());
|
c.inject(new ValidationModule.EagerSingletons());
|
||||||
c.inject(new VersioningModule.EagerSingletons());
|
c.inject(new VersioningModule.EagerSingletons());
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import org.briarproject.bramble.rendezvous.RendezvousModule;
|
|||||||
import org.briarproject.bramble.settings.SettingsModule;
|
import org.briarproject.bramble.settings.SettingsModule;
|
||||||
import org.briarproject.bramble.sync.SyncModule;
|
import org.briarproject.bramble.sync.SyncModule;
|
||||||
import org.briarproject.bramble.sync.validation.ValidationModule;
|
import org.briarproject.bramble.sync.validation.ValidationModule;
|
||||||
import org.briarproject.bramble.system.SystemModule;
|
import org.briarproject.bramble.system.ClockModule;
|
||||||
import org.briarproject.bramble.transport.TransportModule;
|
import org.briarproject.bramble.transport.TransportModule;
|
||||||
import org.briarproject.bramble.versioning.VersioningModule;
|
import org.briarproject.bramble.versioning.VersioningModule;
|
||||||
|
|
||||||
@@ -29,6 +29,7 @@ import dagger.Module;
|
|||||||
|
|
||||||
@Module(includes = {
|
@Module(includes = {
|
||||||
ClientModule.class,
|
ClientModule.class,
|
||||||
|
ClockModule.class,
|
||||||
ConnectionModule.class,
|
ConnectionModule.class,
|
||||||
ContactModule.class,
|
ContactModule.class,
|
||||||
CryptoModule.class,
|
CryptoModule.class,
|
||||||
@@ -48,7 +49,6 @@ import dagger.Module;
|
|||||||
RendezvousModule.class,
|
RendezvousModule.class,
|
||||||
SettingsModule.class,
|
SettingsModule.class,
|
||||||
SyncModule.class,
|
SyncModule.class,
|
||||||
SystemModule.class,
|
|
||||||
TransportModule.class,
|
TransportModule.class,
|
||||||
ValidationModule.class,
|
ValidationModule.class,
|
||||||
VersioningModule.class
|
VersioningModule.class
|
||||||
|
|||||||
@@ -63,18 +63,12 @@ class ConnectionRegistryImpl implements ConnectionRegistry {
|
|||||||
@Override
|
@Override
|
||||||
public void registerIncomingConnection(ContactId c, TransportId t,
|
public void registerIncomingConnection(ContactId c, TransportId t,
|
||||||
InterruptibleConnection conn) {
|
InterruptibleConnection conn) {
|
||||||
if (LOG.isLoggable(INFO)) {
|
|
||||||
LOG.info("Incoming connection registered: " + t);
|
|
||||||
}
|
|
||||||
registerConnection(c, t, conn, true);
|
registerConnection(c, t, conn, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void registerOutgoingConnection(ContactId c, TransportId t,
|
public void registerOutgoingConnection(ContactId c, TransportId t,
|
||||||
InterruptibleConnection conn, Priority priority) {
|
InterruptibleConnection conn, Priority priority) {
|
||||||
if (LOG.isLoggable(INFO)) {
|
|
||||||
LOG.info("Outgoing connection registered: " + t);
|
|
||||||
}
|
|
||||||
registerConnection(c, t, conn, false);
|
registerConnection(c, t, conn, false);
|
||||||
setPriority(c, t, conn, priority);
|
setPriority(c, t, conn, priority);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,15 +3,15 @@ package org.briarproject.bramble.io;
|
|||||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
import org.briarproject.bramble.api.system.Scheduler;
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler.Cancellable;
|
||||||
|
import org.briarproject.bramble.api.system.Wakeful;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.Future;
|
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
import javax.annotation.concurrent.GuardedBy;
|
import javax.annotation.concurrent.GuardedBy;
|
||||||
@@ -30,7 +30,7 @@ class TimeoutMonitorImpl implements TimeoutMonitor {
|
|||||||
|
|
||||||
private static final long CHECK_INTERVAL_MS = SECONDS.toMillis(10);
|
private static final long CHECK_INTERVAL_MS = SECONDS.toMillis(10);
|
||||||
|
|
||||||
private final ScheduledExecutorService scheduler;
|
private final TaskScheduler scheduler;
|
||||||
private final Executor ioExecutor;
|
private final Executor ioExecutor;
|
||||||
private final Clock clock;
|
private final Clock clock;
|
||||||
private final Object lock = new Object();
|
private final Object lock = new Object();
|
||||||
@@ -38,10 +38,10 @@ class TimeoutMonitorImpl implements TimeoutMonitor {
|
|||||||
private final List<TimeoutInputStream> streams = new ArrayList<>();
|
private final List<TimeoutInputStream> streams = new ArrayList<>();
|
||||||
|
|
||||||
@GuardedBy("lock")
|
@GuardedBy("lock")
|
||||||
private Future<?> task = null;
|
private Cancellable cancellable = null;
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
TimeoutMonitorImpl(@Scheduler ScheduledExecutorService scheduler,
|
TimeoutMonitorImpl(TaskScheduler scheduler,
|
||||||
@IoExecutor Executor ioExecutor, Clock clock) {
|
@IoExecutor Executor ioExecutor, Clock clock) {
|
||||||
this.scheduler = scheduler;
|
this.scheduler = scheduler;
|
||||||
this.ioExecutor = ioExecutor;
|
this.ioExecutor = ioExecutor;
|
||||||
@@ -55,8 +55,9 @@ class TimeoutMonitorImpl implements TimeoutMonitor {
|
|||||||
timeoutMs, this::removeStream);
|
timeoutMs, this::removeStream);
|
||||||
synchronized (lock) {
|
synchronized (lock) {
|
||||||
if (streams.isEmpty()) {
|
if (streams.isEmpty()) {
|
||||||
task = scheduler.scheduleWithFixedDelay(this::checkTimeouts,
|
cancellable = scheduler.scheduleWithFixedDelay(
|
||||||
CHECK_INTERVAL_MS, CHECK_INTERVAL_MS, MILLISECONDS);
|
this::checkTimeouts, ioExecutor, CHECK_INTERVAL_MS,
|
||||||
|
CHECK_INTERVAL_MS, MILLISECONDS);
|
||||||
}
|
}
|
||||||
streams.add(stream);
|
streams.add(stream);
|
||||||
}
|
}
|
||||||
@@ -64,33 +65,35 @@ class TimeoutMonitorImpl implements TimeoutMonitor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void removeStream(TimeoutInputStream stream) {
|
private void removeStream(TimeoutInputStream stream) {
|
||||||
Future<?> toCancel = null;
|
Cancellable toCancel = null;
|
||||||
synchronized (lock) {
|
synchronized (lock) {
|
||||||
if (streams.remove(stream) && streams.isEmpty()) {
|
if (streams.remove(stream) && streams.isEmpty()) {
|
||||||
toCancel = task;
|
toCancel = cancellable;
|
||||||
task = null;
|
cancellable = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (toCancel != null) toCancel.cancel(false);
|
if (toCancel != null) {
|
||||||
|
LOG.info("Cancelling timeout monitor task");
|
||||||
|
toCancel.cancel();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Scheduler
|
@IoExecutor
|
||||||
|
@Wakeful
|
||||||
private void checkTimeouts() {
|
private void checkTimeouts() {
|
||||||
ioExecutor.execute(() -> {
|
List<TimeoutInputStream> snapshot;
|
||||||
List<TimeoutInputStream> snapshot;
|
synchronized (lock) {
|
||||||
synchronized (lock) {
|
snapshot = new ArrayList<>(streams);
|
||||||
snapshot = new ArrayList<>(streams);
|
}
|
||||||
}
|
for (TimeoutInputStream stream : snapshot) {
|
||||||
for (TimeoutInputStream stream : snapshot) {
|
if (stream.hasTimedOut()) {
|
||||||
if (stream.hasTimedOut()) {
|
LOG.info("Input stream has timed out");
|
||||||
LOG.info("Input stream has timed out");
|
try {
|
||||||
try {
|
stream.close();
|
||||||
stream.close();
|
} catch (IOException e) {
|
||||||
} catch (IOException e) {
|
logException(LOG, INFO, e);
|
||||||
logException(LOG, INFO, e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package org.briarproject.bramble.plugin;
|
package org.briarproject.bramble.plugin;
|
||||||
|
|
||||||
import org.briarproject.bramble.api.connection.ConnectionManager;
|
import org.briarproject.bramble.api.connection.ConnectionManager;
|
||||||
|
import org.briarproject.bramble.api.contact.ContactId;
|
||||||
import org.briarproject.bramble.api.db.DbException;
|
import org.briarproject.bramble.api.db.DbException;
|
||||||
import org.briarproject.bramble.api.event.EventBus;
|
import org.briarproject.bramble.api.event.EventBus;
|
||||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
@@ -8,6 +9,7 @@ import org.briarproject.bramble.api.lifecycle.Service;
|
|||||||
import org.briarproject.bramble.api.lifecycle.ServiceException;
|
import org.briarproject.bramble.api.lifecycle.ServiceException;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Plugin;
|
import org.briarproject.bramble.api.plugin.Plugin;
|
||||||
|
import org.briarproject.bramble.api.plugin.Plugin.State;
|
||||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||||
import org.briarproject.bramble.api.plugin.PluginConfig;
|
import org.briarproject.bramble.api.plugin.PluginConfig;
|
||||||
import org.briarproject.bramble.api.plugin.PluginException;
|
import org.briarproject.bramble.api.plugin.PluginException;
|
||||||
@@ -18,14 +20,16 @@ import org.briarproject.bramble.api.plugin.TransportId;
|
|||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||||
import org.briarproject.bramble.api.plugin.event.TransportDisabledEvent;
|
import org.briarproject.bramble.api.plugin.event.TransportActiveEvent;
|
||||||
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
|
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||||
|
import org.briarproject.bramble.api.plugin.event.TransportStateEvent;
|
||||||
import org.briarproject.bramble.api.plugin.simplex.SimplexPlugin;
|
import org.briarproject.bramble.api.plugin.simplex.SimplexPlugin;
|
||||||
import org.briarproject.bramble.api.plugin.simplex.SimplexPluginFactory;
|
import org.briarproject.bramble.api.plugin.simplex.SimplexPluginFactory;
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
||||||
import org.briarproject.bramble.api.settings.Settings;
|
import org.briarproject.bramble.api.settings.Settings;
|
||||||
import org.briarproject.bramble.api.settings.SettingsManager;
|
import org.briarproject.bramble.api.settings.SettingsManager;
|
||||||
|
import org.briarproject.bramble.api.system.WakefulIoExecutor;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
@@ -36,15 +40,21 @@ import java.util.concurrent.CopyOnWriteArrayList;
|
|||||||
import java.util.concurrent.CountDownLatch;
|
import java.util.concurrent.CountDownLatch;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
import javax.annotation.concurrent.ThreadSafe;
|
import javax.annotation.concurrent.ThreadSafe;
|
||||||
import javax.inject.Inject;
|
import javax.inject.Inject;
|
||||||
|
|
||||||
|
import static java.util.Collections.emptyList;
|
||||||
import static java.util.logging.Level.FINE;
|
import static java.util.logging.Level.FINE;
|
||||||
import static java.util.logging.Level.INFO;
|
import static java.util.logging.Level.INFO;
|
||||||
import static java.util.logging.Level.WARNING;
|
import static java.util.logging.Level.WARNING;
|
||||||
import static java.util.logging.Logger.getLogger;
|
import static java.util.logging.Logger.getLogger;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.PREF_PLUGIN_ENABLE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.ACTIVE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.DISABLED;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.STARTING_STOPPING;
|
||||||
import static org.briarproject.bramble.util.LogUtils.logDuration;
|
import static org.briarproject.bramble.util.LogUtils.logDuration;
|
||||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||||
import static org.briarproject.bramble.util.LogUtils.now;
|
import static org.briarproject.bramble.util.LogUtils.now;
|
||||||
@@ -56,7 +66,7 @@ class PluginManagerImpl implements PluginManager, Service {
|
|||||||
private static final Logger LOG =
|
private static final Logger LOG =
|
||||||
getLogger(PluginManagerImpl.class.getName());
|
getLogger(PluginManagerImpl.class.getName());
|
||||||
|
|
||||||
private final Executor ioExecutor;
|
private final Executor ioExecutor, wakefulIoExecutor;
|
||||||
private final EventBus eventBus;
|
private final EventBus eventBus;
|
||||||
private final PluginConfig pluginConfig;
|
private final PluginConfig pluginConfig;
|
||||||
private final ConnectionManager connectionManager;
|
private final ConnectionManager connectionManager;
|
||||||
@@ -69,11 +79,15 @@ class PluginManagerImpl implements PluginManager, Service {
|
|||||||
private final AtomicBoolean used = new AtomicBoolean(false);
|
private final AtomicBoolean used = new AtomicBoolean(false);
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
PluginManagerImpl(@IoExecutor Executor ioExecutor, EventBus eventBus,
|
PluginManagerImpl(@IoExecutor Executor ioExecutor,
|
||||||
PluginConfig pluginConfig, ConnectionManager connectionManager,
|
@WakefulIoExecutor Executor wakefulIoExecutor,
|
||||||
|
EventBus eventBus,
|
||||||
|
PluginConfig pluginConfig,
|
||||||
|
ConnectionManager connectionManager,
|
||||||
SettingsManager settingsManager,
|
SettingsManager settingsManager,
|
||||||
TransportPropertyManager transportPropertyManager) {
|
TransportPropertyManager transportPropertyManager) {
|
||||||
this.ioExecutor = ioExecutor;
|
this.ioExecutor = ioExecutor;
|
||||||
|
this.wakefulIoExecutor = wakefulIoExecutor;
|
||||||
this.eventBus = eventBus;
|
this.eventBus = eventBus;
|
||||||
this.pluginConfig = pluginConfig;
|
this.pluginConfig = pluginConfig;
|
||||||
this.connectionManager = connectionManager;
|
this.connectionManager = connectionManager;
|
||||||
@@ -101,7 +115,7 @@ class PluginManagerImpl implements PluginManager, Service {
|
|||||||
simplexPlugins.add(s);
|
simplexPlugins.add(s);
|
||||||
CountDownLatch startLatch = new CountDownLatch(1);
|
CountDownLatch startLatch = new CountDownLatch(1);
|
||||||
startLatches.put(t, startLatch);
|
startLatches.put(t, startLatch);
|
||||||
ioExecutor.execute(new PluginStarter(s, startLatch));
|
wakefulIoExecutor.execute(new PluginStarter(s, startLatch));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Instantiate the duplex plugins and start them asynchronously
|
// Instantiate the duplex plugins and start them asynchronously
|
||||||
@@ -117,7 +131,7 @@ class PluginManagerImpl implements PluginManager, Service {
|
|||||||
duplexPlugins.add(d);
|
duplexPlugins.add(d);
|
||||||
CountDownLatch startLatch = new CountDownLatch(1);
|
CountDownLatch startLatch = new CountDownLatch(1);
|
||||||
startLatches.put(t, startLatch);
|
startLatches.put(t, startLatch);
|
||||||
ioExecutor.execute(new PluginStarter(d, startLatch));
|
wakefulIoExecutor.execute(new PluginStarter(d, startLatch));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,12 +143,16 @@ class PluginManagerImpl implements PluginManager, Service {
|
|||||||
LOG.info("Stopping simplex plugins");
|
LOG.info("Stopping simplex plugins");
|
||||||
for (SimplexPlugin s : simplexPlugins) {
|
for (SimplexPlugin s : simplexPlugins) {
|
||||||
CountDownLatch startLatch = startLatches.get(s.getId());
|
CountDownLatch startLatch = startLatches.get(s.getId());
|
||||||
|
// Don't need the wakeful executor here as we wait for the plugin
|
||||||
|
// to stop before returning
|
||||||
ioExecutor.execute(new PluginStopper(s, startLatch, stopLatch));
|
ioExecutor.execute(new PluginStopper(s, startLatch, stopLatch));
|
||||||
}
|
}
|
||||||
// Stop the duplex plugins
|
// Stop the duplex plugins
|
||||||
LOG.info("Stopping duplex plugins");
|
LOG.info("Stopping duplex plugins");
|
||||||
for (DuplexPlugin d : duplexPlugins) {
|
for (DuplexPlugin d : duplexPlugins) {
|
||||||
CountDownLatch startLatch = startLatches.get(d.getId());
|
CountDownLatch startLatch = startLatches.get(d.getId());
|
||||||
|
// Don't need the wakeful executor here as we wait for the plugin
|
||||||
|
// to stop before returning
|
||||||
ioExecutor.execute(new PluginStopper(d, startLatch, stopLatch));
|
ioExecutor.execute(new PluginStopper(d, startLatch, stopLatch));
|
||||||
}
|
}
|
||||||
// Wait for all the plugins to stop
|
// Wait for all the plugins to stop
|
||||||
@@ -177,7 +195,27 @@ class PluginManagerImpl implements PluginManager, Service {
|
|||||||
return supported;
|
return supported;
|
||||||
}
|
}
|
||||||
|
|
||||||
private class PluginStarter implements Runnable {
|
@Override
|
||||||
|
public void setPluginEnabled(TransportId t, boolean enabled) {
|
||||||
|
Plugin plugin = plugins.get(t);
|
||||||
|
if (plugin == null) return;
|
||||||
|
|
||||||
|
Settings s = new Settings();
|
||||||
|
s.putBoolean(PREF_PLUGIN_ENABLE, enabled);
|
||||||
|
ioExecutor.execute(() -> mergeSettings(s, t.getString()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void mergeSettings(Settings s, String namespace) {
|
||||||
|
try {
|
||||||
|
long start = now();
|
||||||
|
settingsManager.mergeSettings(s, namespace);
|
||||||
|
logDuration(LOG, "Merging settings", start);
|
||||||
|
} catch (DbException e) {
|
||||||
|
logException(LOG, WARNING, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class PluginStarter implements Runnable {
|
||||||
|
|
||||||
private final Plugin plugin;
|
private final Plugin plugin;
|
||||||
private final CountDownLatch startLatch;
|
private final CountDownLatch startLatch;
|
||||||
@@ -207,7 +245,7 @@ class PluginManagerImpl implements PluginManager, Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private class PluginStopper implements Runnable {
|
private static class PluginStopper implements Runnable {
|
||||||
|
|
||||||
private final Plugin plugin;
|
private final Plugin plugin;
|
||||||
private final CountDownLatch startLatch, stopLatch;
|
private final CountDownLatch startLatch, stopLatch;
|
||||||
@@ -250,7 +288,8 @@ class PluginManagerImpl implements PluginManager, Service {
|
|||||||
private class Callback implements PluginCallback {
|
private class Callback implements PluginCallback {
|
||||||
|
|
||||||
private final TransportId id;
|
private final TransportId id;
|
||||||
private final AtomicBoolean enabled = new AtomicBoolean(false);
|
private final AtomicReference<State> state =
|
||||||
|
new AtomicReference<>(STARTING_STOPPING);
|
||||||
|
|
||||||
private Callback(TransportId id) {
|
private Callback(TransportId id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
@@ -277,14 +316,22 @@ class PluginManagerImpl implements PluginManager, Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void mergeSettings(Settings s) {
|
public Collection<TransportProperties> getRemoteProperties() {
|
||||||
try {
|
try {
|
||||||
settingsManager.mergeSettings(s, id.getString());
|
Map<ContactId, TransportProperties> remote =
|
||||||
|
transportPropertyManager.getRemoteProperties(id);
|
||||||
|
return remote.values();
|
||||||
} catch (DbException e) {
|
} catch (DbException e) {
|
||||||
logException(LOG, WARNING, e);
|
logException(LOG, WARNING, e);
|
||||||
|
return emptyList();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void mergeSettings(Settings s) {
|
||||||
|
PluginManagerImpl.this.mergeSettings(s, id.getString());
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void mergeLocalProperties(TransportProperties p) {
|
public void mergeLocalProperties(TransportProperties p) {
|
||||||
try {
|
try {
|
||||||
@@ -295,15 +342,24 @@ class PluginManagerImpl implements PluginManager, Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void transportEnabled() {
|
public void pluginStateChanged(State newState) {
|
||||||
if (!enabled.getAndSet(true))
|
State oldState = state.getAndSet(newState);
|
||||||
eventBus.broadcast(new TransportEnabledEvent(id));
|
if (newState != oldState) {
|
||||||
}
|
if (LOG.isLoggable(INFO)) {
|
||||||
|
LOG.info(id + " changed from state " + oldState
|
||||||
@Override
|
+ " to " + newState);
|
||||||
public void transportDisabled() {
|
}
|
||||||
if (enabled.getAndSet(false))
|
eventBus.broadcast(new TransportStateEvent(id, newState));
|
||||||
eventBus.broadcast(new TransportDisabledEvent(id));
|
if (newState == ACTIVE) {
|
||||||
|
eventBus.broadcast(new TransportActiveEvent(id));
|
||||||
|
} else if (oldState == ACTIVE) {
|
||||||
|
eventBus.broadcast(new TransportInactiveEvent(id));
|
||||||
|
}
|
||||||
|
} else if (newState == DISABLED) {
|
||||||
|
// Broadcast an event even though the state hasn't changed, as
|
||||||
|
// the reasons for the plugin being disabled may have changed
|
||||||
|
eventBus.broadcast(new TransportStateEvent(id, newState));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -20,13 +20,16 @@ import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
|||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||||
import org.briarproject.bramble.api.plugin.event.ConnectionClosedEvent;
|
import org.briarproject.bramble.api.plugin.event.ConnectionClosedEvent;
|
||||||
import org.briarproject.bramble.api.plugin.event.ConnectionOpenedEvent;
|
import org.briarproject.bramble.api.plugin.event.ConnectionOpenedEvent;
|
||||||
import org.briarproject.bramble.api.plugin.event.TransportDisabledEvent;
|
import org.briarproject.bramble.api.plugin.event.TransportActiveEvent;
|
||||||
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
|
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||||
import org.briarproject.bramble.api.plugin.simplex.SimplexPlugin;
|
import org.briarproject.bramble.api.plugin.simplex.SimplexPlugin;
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
import org.briarproject.bramble.api.system.Scheduler;
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler.Cancellable;
|
||||||
|
import org.briarproject.bramble.api.system.Wakeful;
|
||||||
|
import org.briarproject.bramble.api.system.WakefulIoExecutor;
|
||||||
|
|
||||||
import java.security.SecureRandom;
|
import java.security.SecureRandom;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -35,8 +38,6 @@ import java.util.HashMap;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Map.Entry;
|
import java.util.Map.Entry;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.Future;
|
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.concurrent.locks.Lock;
|
import java.util.concurrent.locks.Lock;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
@@ -57,8 +58,8 @@ class PollerImpl implements Poller, EventListener {
|
|||||||
|
|
||||||
private static final Logger LOG = getLogger(PollerImpl.class.getName());
|
private static final Logger LOG = getLogger(PollerImpl.class.getName());
|
||||||
|
|
||||||
private final Executor ioExecutor;
|
private final Executor ioExecutor, wakefulIoExecutor;
|
||||||
private final ScheduledExecutorService scheduler;
|
private final TaskScheduler scheduler;
|
||||||
private final ConnectionManager connectionManager;
|
private final ConnectionManager connectionManager;
|
||||||
private final ConnectionRegistry connectionRegistry;
|
private final ConnectionRegistry connectionRegistry;
|
||||||
private final PluginManager pluginManager;
|
private final PluginManager pluginManager;
|
||||||
@@ -71,12 +72,16 @@ class PollerImpl implements Poller, EventListener {
|
|||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
PollerImpl(@IoExecutor Executor ioExecutor,
|
PollerImpl(@IoExecutor Executor ioExecutor,
|
||||||
@Scheduler ScheduledExecutorService scheduler,
|
@WakefulIoExecutor Executor wakefulIoExecutor,
|
||||||
|
TaskScheduler scheduler,
|
||||||
ConnectionManager connectionManager,
|
ConnectionManager connectionManager,
|
||||||
ConnectionRegistry connectionRegistry, PluginManager pluginManager,
|
ConnectionRegistry connectionRegistry,
|
||||||
|
PluginManager pluginManager,
|
||||||
TransportPropertyManager transportPropertyManager,
|
TransportPropertyManager transportPropertyManager,
|
||||||
SecureRandom random, Clock clock) {
|
SecureRandom random,
|
||||||
|
Clock clock) {
|
||||||
this.ioExecutor = ioExecutor;
|
this.ioExecutor = ioExecutor;
|
||||||
|
this.wakefulIoExecutor = wakefulIoExecutor;
|
||||||
this.scheduler = scheduler;
|
this.scheduler = scheduler;
|
||||||
this.connectionManager = connectionManager;
|
this.connectionManager = connectionManager;
|
||||||
this.connectionRegistry = connectionRegistry;
|
this.connectionRegistry = connectionRegistry;
|
||||||
@@ -106,13 +111,13 @@ class PollerImpl implements Poller, EventListener {
|
|||||||
ConnectionOpenedEvent c = (ConnectionOpenedEvent) e;
|
ConnectionOpenedEvent c = (ConnectionOpenedEvent) e;
|
||||||
// Reschedule polling, the polling interval may have decreased
|
// Reschedule polling, the polling interval may have decreased
|
||||||
reschedule(c.getTransportId());
|
reschedule(c.getTransportId());
|
||||||
} else if (e instanceof TransportEnabledEvent) {
|
} else if (e instanceof TransportActiveEvent) {
|
||||||
TransportEnabledEvent t = (TransportEnabledEvent) e;
|
TransportActiveEvent t = (TransportActiveEvent) e;
|
||||||
// Poll the newly enabled transport
|
// Poll the newly activated transport
|
||||||
pollNow(t.getTransportId());
|
pollNow(t.getTransportId());
|
||||||
} else if (e instanceof TransportDisabledEvent) {
|
} else if (e instanceof TransportInactiveEvent) {
|
||||||
TransportDisabledEvent t = (TransportDisabledEvent) e;
|
TransportInactiveEvent t = (TransportInactiveEvent) e;
|
||||||
// Cancel polling for the disabled transport
|
// Cancel polling for the deactivated transport
|
||||||
cancel(t.getTransportId());
|
cancel(t.getTransportId());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -133,7 +138,7 @@ class PollerImpl implements Poller, EventListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void connectToContact(ContactId c, SimplexPlugin p) {
|
private void connectToContact(ContactId c, SimplexPlugin p) {
|
||||||
ioExecutor.execute(() -> {
|
wakefulIoExecutor.execute(() -> {
|
||||||
TransportId t = p.getId();
|
TransportId t = p.getId();
|
||||||
if (connectionRegistry.isConnected(c, t)) return;
|
if (connectionRegistry.isConnected(c, t)) return;
|
||||||
try {
|
try {
|
||||||
@@ -149,7 +154,7 @@ class PollerImpl implements Poller, EventListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void connectToContact(ContactId c, DuplexPlugin p) {
|
private void connectToContact(ContactId c, DuplexPlugin p) {
|
||||||
ioExecutor.execute(() -> {
|
wakefulIoExecutor.execute(() -> {
|
||||||
TransportId t = p.getId();
|
TransportId t = p.getId();
|
||||||
if (connectionRegistry.isConnected(c, t)) return;
|
if (connectionRegistry.isConnected(c, t)) return;
|
||||||
try {
|
try {
|
||||||
@@ -186,11 +191,11 @@ class PollerImpl implements Poller, EventListener {
|
|||||||
if (scheduled == null || due < scheduled.task.due) {
|
if (scheduled == null || due < scheduled.task.due) {
|
||||||
// If a later task exists, cancel it. If it's already started
|
// If a later task exists, cancel it. If it's already started
|
||||||
// it will abort safely when it finds it's been replaced
|
// it will abort safely when it finds it's been replaced
|
||||||
if (scheduled != null) scheduled.future.cancel(false);
|
if (scheduled != null) scheduled.cancellable.cancel();
|
||||||
PollTask task = new PollTask(p, due, randomiseNext);
|
PollTask task = new PollTask(p, due, randomiseNext);
|
||||||
Future future = scheduler.schedule(() ->
|
Cancellable cancellable = scheduler.schedule(task, ioExecutor,
|
||||||
ioExecutor.execute(task), delay, MILLISECONDS);
|
delay, MILLISECONDS);
|
||||||
tasks.put(t, new ScheduledPollTask(task, future));
|
tasks.put(t, new ScheduledPollTask(task, cancellable));
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
@@ -201,7 +206,7 @@ class PollerImpl implements Poller, EventListener {
|
|||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
ScheduledPollTask scheduled = tasks.remove(t);
|
ScheduledPollTask scheduled = tasks.remove(t);
|
||||||
if (scheduled != null) scheduled.future.cancel(false);
|
if (scheduled != null) scheduled.cancellable.cancel();
|
||||||
} finally {
|
} finally {
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
}
|
}
|
||||||
@@ -232,11 +237,11 @@ class PollerImpl implements Poller, EventListener {
|
|||||||
private class ScheduledPollTask {
|
private class ScheduledPollTask {
|
||||||
|
|
||||||
private final PollTask task;
|
private final PollTask task;
|
||||||
private final Future future;
|
private final Cancellable cancellable;
|
||||||
|
|
||||||
private ScheduledPollTask(PollTask task, Future future) {
|
private ScheduledPollTask(PollTask task, Cancellable cancellable) {
|
||||||
this.task = task;
|
this.task = task;
|
||||||
this.future = future;
|
this.cancellable = cancellable;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,6 +259,7 @@ class PollerImpl implements Poller, EventListener {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
@IoExecutor
|
@IoExecutor
|
||||||
|
@Wakeful
|
||||||
public void run() {
|
public void run() {
|
||||||
lock.lock();
|
lock.lock();
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package org.briarproject.bramble.plugin.bluetooth;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||||
|
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@NotNullByDefault
|
||||||
|
interface BluetoothConnectionFactory<S> {
|
||||||
|
|
||||||
|
DuplexTransportConnection wrapSocket(DuplexPlugin plugin, S socket)
|
||||||
|
throws IOException;
|
||||||
|
}
|
||||||
@@ -3,16 +3,9 @@ package org.briarproject.bramble.plugin.bluetooth;
|
|||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||||
|
|
||||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
|
||||||
|
|
||||||
@NotNullByDefault
|
@NotNullByDefault
|
||||||
interface BluetoothConnectionLimiter {
|
interface BluetoothConnectionLimiter {
|
||||||
|
|
||||||
/**
|
|
||||||
* How long a connection must remain open before it's considered stable.
|
|
||||||
*/
|
|
||||||
long STABILITY_PERIOD_MS = SECONDS.toMillis(90);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Informs the limiter that key agreement has started.
|
* Informs the limiter that key agreement has started.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -4,9 +4,7 @@ import org.briarproject.bramble.api.event.EventBus;
|
|||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||||
import org.briarproject.bramble.api.sync.event.CloseSyncConnectionsEvent;
|
import org.briarproject.bramble.api.sync.event.CloseSyncConnectionsEvent;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
|
||||||
|
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
@@ -26,19 +24,16 @@ class BluetoothConnectionLimiterImpl implements BluetoothConnectionLimiter {
|
|||||||
getLogger(BluetoothConnectionLimiterImpl.class.getName());
|
getLogger(BluetoothConnectionLimiterImpl.class.getName());
|
||||||
|
|
||||||
private final EventBus eventBus;
|
private final EventBus eventBus;
|
||||||
private final Clock clock;
|
|
||||||
|
|
||||||
private final Object lock = new Object();
|
private final Object lock = new Object();
|
||||||
@GuardedBy("lock")
|
@GuardedBy("lock")
|
||||||
private final List<ConnectionRecord> connections = new LinkedList<>();
|
private final List<DuplexTransportConnection> connections =
|
||||||
|
new LinkedList<>();
|
||||||
@GuardedBy("lock")
|
@GuardedBy("lock")
|
||||||
private boolean keyAgreementInProgress = false;
|
private boolean keyAgreementInProgress = false;
|
||||||
@GuardedBy("lock")
|
|
||||||
private int connectionLimit = 2;
|
|
||||||
|
|
||||||
BluetoothConnectionLimiterImpl(EventBus eventBus, Clock clock) {
|
BluetoothConnectionLimiterImpl(EventBus eventBus) {
|
||||||
this.eventBus = eventBus;
|
this.eventBus = eventBus;
|
||||||
this.clock = clock;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -64,15 +59,9 @@ class BluetoothConnectionLimiterImpl implements BluetoothConnectionLimiter {
|
|||||||
if (keyAgreementInProgress) {
|
if (keyAgreementInProgress) {
|
||||||
LOG.info("Can't open contact connection during key agreement");
|
LOG.info("Can't open contact connection during key agreement");
|
||||||
return false;
|
return false;
|
||||||
}
|
} else {
|
||||||
long now = clock.currentTimeMillis();
|
|
||||||
countStableConnections(now);
|
|
||||||
if (connections.size() < connectionLimit) {
|
|
||||||
LOG.info("Can open contact connection");
|
LOG.info("Can open contact connection");
|
||||||
return true;
|
return true;
|
||||||
} else {
|
|
||||||
LOG.info("Can't open contact connection due to limit");
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -80,9 +69,7 @@ class BluetoothConnectionLimiterImpl implements BluetoothConnectionLimiter {
|
|||||||
@Override
|
@Override
|
||||||
public void connectionOpened(DuplexTransportConnection conn) {
|
public void connectionOpened(DuplexTransportConnection conn) {
|
||||||
synchronized (lock) {
|
synchronized (lock) {
|
||||||
long now = clock.currentTimeMillis();
|
connections.add(conn);
|
||||||
countStableConnections(now);
|
|
||||||
connections.add(new ConnectionRecord(conn, now));
|
|
||||||
if (LOG.isLoggable(INFO)) {
|
if (LOG.isLoggable(INFO)) {
|
||||||
LOG.info("Connection opened, " + connections.size() + " open");
|
LOG.info("Connection opened, " + connections.size() + " open");
|
||||||
}
|
}
|
||||||
@@ -92,14 +79,7 @@ class BluetoothConnectionLimiterImpl implements BluetoothConnectionLimiter {
|
|||||||
@Override
|
@Override
|
||||||
public void connectionClosed(DuplexTransportConnection conn) {
|
public void connectionClosed(DuplexTransportConnection conn) {
|
||||||
synchronized (lock) {
|
synchronized (lock) {
|
||||||
countStableConnections(clock.currentTimeMillis());
|
connections.remove(conn);
|
||||||
Iterator<ConnectionRecord> it = connections.iterator();
|
|
||||||
while (it.hasNext()) {
|
|
||||||
if (it.next().conn == conn) {
|
|
||||||
it.remove();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (LOG.isLoggable(INFO)) {
|
if (LOG.isLoggable(INFO)) {
|
||||||
LOG.info("Connection closed, " + connections.size() + " open");
|
LOG.info("Connection closed, " + connections.size() + " open");
|
||||||
}
|
}
|
||||||
@@ -109,36 +89,8 @@ class BluetoothConnectionLimiterImpl implements BluetoothConnectionLimiter {
|
|||||||
@Override
|
@Override
|
||||||
public void allConnectionsClosed() {
|
public void allConnectionsClosed() {
|
||||||
synchronized (lock) {
|
synchronized (lock) {
|
||||||
long now = clock.currentTimeMillis();
|
|
||||||
countStableConnections(now);
|
|
||||||
connections.clear();
|
connections.clear();
|
||||||
LOG.info("All connections closed");
|
LOG.info("All connections closed");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@GuardedBy("lock")
|
|
||||||
private void countStableConnections(long now) {
|
|
||||||
int stable = 0;
|
|
||||||
for (ConnectionRecord rec : connections) {
|
|
||||||
if (now - rec.timeOpened >= STABILITY_PERIOD_MS) stable++;
|
|
||||||
}
|
|
||||||
if (stable > connectionLimit) {
|
|
||||||
connectionLimit = stable;
|
|
||||||
if (LOG.isLoggable(INFO)) {
|
|
||||||
LOG.info("Raising connection limit to " + connectionLimit);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static class ConnectionRecord {
|
|
||||||
|
|
||||||
private final DuplexTransportConnection conn;
|
|
||||||
private final long timeOpened;
|
|
||||||
|
|
||||||
private ConnectionRecord(DuplexTransportConnection conn,
|
|
||||||
long timeOpened) {
|
|
||||||
this.conn = conn;
|
|
||||||
this.timeOpened = timeOpened;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
package org.briarproject.bramble.plugin.bluetooth;
|
package org.briarproject.bramble.plugin.bluetooth;
|
||||||
|
|
||||||
import org.briarproject.bramble.api.FormatException;
|
import org.briarproject.bramble.api.FormatException;
|
||||||
|
import org.briarproject.bramble.api.Multiset;
|
||||||
import org.briarproject.bramble.api.Pair;
|
import org.briarproject.bramble.api.Pair;
|
||||||
import org.briarproject.bramble.api.data.BdfList;
|
import org.briarproject.bramble.api.data.BdfList;
|
||||||
import org.briarproject.bramble.api.event.Event;
|
import org.briarproject.bramble.api.event.Event;
|
||||||
import org.briarproject.bramble.api.event.EventListener;
|
import org.briarproject.bramble.api.event.EventListener;
|
||||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
|
||||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementConnection;
|
import org.briarproject.bramble.api.keyagreement.KeyAgreementConnection;
|
||||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
|
import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
|
||||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementListeningEvent;
|
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementListeningEvent;
|
||||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementStoppedListeningEvent;
|
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementStoppedListeningEvent;
|
||||||
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
import org.briarproject.bramble.api.plugin.ConnectionHandler;
|
import org.briarproject.bramble.api.plugin.ConnectionHandler;
|
||||||
@@ -19,10 +21,8 @@ import org.briarproject.bramble.api.plugin.PluginException;
|
|||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||||
import org.briarproject.bramble.api.plugin.event.BluetoothEnabledEvent;
|
|
||||||
import org.briarproject.bramble.api.plugin.event.DisableBluetoothEvent;
|
|
||||||
import org.briarproject.bramble.api.plugin.event.EnableBluetoothEvent;
|
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
|
import org.briarproject.bramble.api.properties.event.RemoteTransportPropertiesUpdatedEvent;
|
||||||
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
||||||
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
||||||
import org.briarproject.bramble.api.settings.Settings;
|
import org.briarproject.bramble.api.settings.Settings;
|
||||||
@@ -37,16 +37,27 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
|||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
|
import javax.annotation.concurrent.GuardedBy;
|
||||||
|
import javax.annotation.concurrent.ThreadSafe;
|
||||||
|
|
||||||
import static java.util.logging.Level.INFO;
|
import static java.util.logging.Level.INFO;
|
||||||
import static java.util.logging.Level.WARNING;
|
import static java.util.logging.Level.WARNING;
|
||||||
import static java.util.logging.Logger.getLogger;
|
import static java.util.logging.Logger.getLogger;
|
||||||
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TRANSPORT_ID_BLUETOOTH;
|
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TRANSPORT_ID_BLUETOOTH;
|
||||||
|
import static org.briarproject.bramble.api.plugin.BluetoothConstants.DEFAULT_PREF_ADDRESS_IS_REFLECTED;
|
||||||
|
import static org.briarproject.bramble.api.plugin.BluetoothConstants.DEFAULT_PREF_EVER_CONNECTED;
|
||||||
|
import static org.briarproject.bramble.api.plugin.BluetoothConstants.DEFAULT_PREF_PLUGIN_ENABLE;
|
||||||
import static org.briarproject.bramble.api.plugin.BluetoothConstants.ID;
|
import static org.briarproject.bramble.api.plugin.BluetoothConstants.ID;
|
||||||
import static org.briarproject.bramble.api.plugin.BluetoothConstants.PREF_BT_ENABLE;
|
import static org.briarproject.bramble.api.plugin.BluetoothConstants.PREF_ADDRESS_IS_REFLECTED;
|
||||||
|
import static org.briarproject.bramble.api.plugin.BluetoothConstants.PREF_EVER_CONNECTED;
|
||||||
import static org.briarproject.bramble.api.plugin.BluetoothConstants.PROP_ADDRESS;
|
import static org.briarproject.bramble.api.plugin.BluetoothConstants.PROP_ADDRESS;
|
||||||
import static org.briarproject.bramble.api.plugin.BluetoothConstants.PROP_UUID;
|
import static org.briarproject.bramble.api.plugin.BluetoothConstants.PROP_UUID;
|
||||||
import static org.briarproject.bramble.api.plugin.BluetoothConstants.UUID_BYTES;
|
import static org.briarproject.bramble.api.plugin.BluetoothConstants.UUID_BYTES;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.ACTIVE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.DISABLED;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.INACTIVE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.STARTING_STOPPING;
|
||||||
|
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.REFLECTED_PROPERTY_PREFIX;
|
||||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||||
import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress;
|
import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress;
|
||||||
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
||||||
@@ -55,35 +66,30 @@ import static org.briarproject.bramble.util.StringUtils.macToString;
|
|||||||
|
|
||||||
@MethodsNotNullByDefault
|
@MethodsNotNullByDefault
|
||||||
@ParametersNotNullByDefault
|
@ParametersNotNullByDefault
|
||||||
abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
abstract class BluetoothPlugin<S, SS> implements DuplexPlugin, EventListener {
|
||||||
|
|
||||||
private static final Logger LOG =
|
private static final Logger LOG =
|
||||||
getLogger(BluetoothPlugin.class.getName());
|
getLogger(BluetoothPlugin.class.getName());
|
||||||
|
|
||||||
final BluetoothConnectionLimiter connectionLimiter;
|
final BluetoothConnectionLimiter connectionLimiter;
|
||||||
final TimeoutMonitor timeoutMonitor;
|
final BluetoothConnectionFactory<S> connectionFactory;
|
||||||
|
|
||||||
private final Executor ioExecutor;
|
private final Executor ioExecutor, wakefulIoExecutor;
|
||||||
private final SecureRandom secureRandom;
|
private final SecureRandom secureRandom;
|
||||||
private final Backoff backoff;
|
private final Backoff backoff;
|
||||||
private final PluginCallback callback;
|
private final PluginCallback callback;
|
||||||
private final int maxLatency, maxIdleTime;
|
private final int maxLatency, maxIdleTime;
|
||||||
private final AtomicBoolean used = new AtomicBoolean(false);
|
private final AtomicBoolean used = new AtomicBoolean(false);
|
||||||
|
private final AtomicBoolean everConnected = new AtomicBoolean(false);
|
||||||
|
|
||||||
|
protected final PluginState state = new PluginState();
|
||||||
|
|
||||||
private volatile boolean running = false, contactConnections = false;
|
|
||||||
private volatile String contactConnectionsUuid = null;
|
private volatile String contactConnectionsUuid = null;
|
||||||
private volatile SS socket = null;
|
|
||||||
|
|
||||||
abstract void initialiseAdapter() throws IOException;
|
abstract void initialiseAdapter() throws IOException;
|
||||||
|
|
||||||
abstract boolean isAdapterEnabled();
|
abstract boolean isAdapterEnabled();
|
||||||
|
|
||||||
abstract void enableAdapter();
|
|
||||||
|
|
||||||
abstract void disableAdapterIfEnabledByUs();
|
|
||||||
|
|
||||||
abstract void setEnabledByUs();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the local Bluetooth address, or null if no valid address can
|
* Returns the local Bluetooth address, or null if no valid address can
|
||||||
* be found.
|
* be found.
|
||||||
@@ -107,12 +113,18 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
abstract DuplexTransportConnection discoverAndConnect(String uuid);
|
abstract DuplexTransportConnection discoverAndConnect(String uuid);
|
||||||
|
|
||||||
BluetoothPlugin(BluetoothConnectionLimiter connectionLimiter,
|
BluetoothPlugin(BluetoothConnectionLimiter connectionLimiter,
|
||||||
TimeoutMonitor timeoutMonitor, Executor ioExecutor,
|
BluetoothConnectionFactory<S> connectionFactory,
|
||||||
SecureRandom secureRandom, Backoff backoff,
|
Executor ioExecutor,
|
||||||
PluginCallback callback, int maxLatency, int maxIdleTime) {
|
Executor wakefulIoExecutor,
|
||||||
|
SecureRandom secureRandom,
|
||||||
|
Backoff backoff,
|
||||||
|
PluginCallback callback,
|
||||||
|
int maxLatency,
|
||||||
|
int maxIdleTime) {
|
||||||
this.connectionLimiter = connectionLimiter;
|
this.connectionLimiter = connectionLimiter;
|
||||||
this.timeoutMonitor = timeoutMonitor;
|
this.connectionFactory = connectionFactory;
|
||||||
this.ioExecutor = ioExecutor;
|
this.ioExecutor = ioExecutor;
|
||||||
|
this.wakefulIoExecutor = wakefulIoExecutor;
|
||||||
this.secureRandom = secureRandom;
|
this.secureRandom = secureRandom;
|
||||||
this.backoff = backoff;
|
this.backoff = backoff;
|
||||||
this.callback = callback;
|
this.callback = callback;
|
||||||
@@ -124,14 +136,18 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
LOG.info("Bluetooth enabled");
|
LOG.info("Bluetooth enabled");
|
||||||
// We may not have been able to get the local address before
|
// We may not have been able to get the local address before
|
||||||
ioExecutor.execute(this::updateProperties);
|
ioExecutor.execute(this::updateProperties);
|
||||||
if (shouldAllowContactConnections()) bind();
|
if (getState() == INACTIVE) bind();
|
||||||
}
|
}
|
||||||
|
|
||||||
void onAdapterDisabled() {
|
void onAdapterDisabled() {
|
||||||
LOG.info("Bluetooth disabled");
|
LOG.info("Bluetooth disabled");
|
||||||
tryToClose(socket);
|
|
||||||
connectionLimiter.allConnectionsClosed();
|
connectionLimiter.allConnectionsClosed();
|
||||||
callback.transportDisabled();
|
// The server socket may not have been closed automatically
|
||||||
|
SS ss = state.clearServerSocket();
|
||||||
|
if (ss != null) {
|
||||||
|
LOG.info("Closing server socket");
|
||||||
|
tryToClose(ss);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -152,31 +168,24 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
@Override
|
@Override
|
||||||
public void start() throws PluginException {
|
public void start() throws PluginException {
|
||||||
if (used.getAndSet(true)) throw new IllegalStateException();
|
if (used.getAndSet(true)) throw new IllegalStateException();
|
||||||
|
Settings settings = callback.getSettings();
|
||||||
|
boolean enabledByUser = settings.getBoolean(PREF_PLUGIN_ENABLE,
|
||||||
|
DEFAULT_PREF_PLUGIN_ENABLE);
|
||||||
|
everConnected.set(settings.getBoolean(PREF_EVER_CONNECTED,
|
||||||
|
DEFAULT_PREF_EVER_CONNECTED));
|
||||||
|
state.setStarted(enabledByUser);
|
||||||
try {
|
try {
|
||||||
initialiseAdapter();
|
initialiseAdapter();
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new PluginException(e);
|
throw new PluginException(e);
|
||||||
}
|
}
|
||||||
updateProperties();
|
updateProperties();
|
||||||
running = true;
|
if (enabledByUser && isAdapterEnabled()) bind();
|
||||||
loadSettings(callback.getSettings());
|
|
||||||
if (shouldAllowContactConnections()) {
|
|
||||||
if (isAdapterEnabled()) bind();
|
|
||||||
else enableAdapter();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void loadSettings(Settings settings) {
|
|
||||||
contactConnections = settings.getBoolean(PREF_BT_ENABLE, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean shouldAllowContactConnections() {
|
|
||||||
return contactConnections;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void bind() {
|
private void bind() {
|
||||||
ioExecutor.execute(() -> {
|
ioExecutor.execute(() -> {
|
||||||
if (!isRunning() || !shouldAllowContactConnections()) return;
|
if (getState() != INACTIVE) return;
|
||||||
// Bind a server socket to accept connections from contacts
|
// Bind a server socket to accept connections from contacts
|
||||||
SS ss;
|
SS ss;
|
||||||
try {
|
try {
|
||||||
@@ -185,14 +194,13 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
logException(LOG, WARNING, e);
|
logException(LOG, WARNING, e);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!isRunning() || !shouldAllowContactConnections()) {
|
if (!state.setServerSocket(ss)) {
|
||||||
|
LOG.info("Closing redundant server socket");
|
||||||
tryToClose(ss);
|
tryToClose(ss);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
socket = ss;
|
|
||||||
backoff.reset();
|
backoff.reset();
|
||||||
callback.transportEnabled();
|
acceptContactConnections(ss);
|
||||||
acceptContactConnections();
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -200,56 +208,115 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
TransportProperties p = callback.getLocalProperties();
|
TransportProperties p = callback.getLocalProperties();
|
||||||
String address = p.get(PROP_ADDRESS);
|
String address = p.get(PROP_ADDRESS);
|
||||||
String uuid = p.get(PROP_UUID);
|
String uuid = p.get(PROP_UUID);
|
||||||
|
Settings s = callback.getSettings();
|
||||||
|
boolean isReflected = s.getBoolean(PREF_ADDRESS_IS_REFLECTED,
|
||||||
|
DEFAULT_PREF_ADDRESS_IS_REFLECTED);
|
||||||
boolean changed = false;
|
boolean changed = false;
|
||||||
if (address == null) {
|
if (address == null || isReflected) {
|
||||||
address = getBluetoothAddress();
|
address = getBluetoothAddress();
|
||||||
if (LOG.isLoggable(INFO))
|
if (LOG.isLoggable(INFO)) {
|
||||||
LOG.info("Local address " + scrubMacAddress(address));
|
LOG.info("Local address " + scrubMacAddress(address));
|
||||||
if (!isNullOrEmpty(address)) {
|
}
|
||||||
p.put(PROP_ADDRESS, address);
|
if (address == null) {
|
||||||
|
if (everConnected.get()) {
|
||||||
|
address = getReflectedAddress();
|
||||||
|
if (LOG.isLoggable(INFO)) {
|
||||||
|
LOG.info("Reflected address " +
|
||||||
|
scrubMacAddress(address));
|
||||||
|
}
|
||||||
|
if (address != null) {
|
||||||
|
changed = true;
|
||||||
|
isReflected = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
changed = true;
|
changed = true;
|
||||||
|
isReflected = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (uuid == null) {
|
if (uuid == null) {
|
||||||
byte[] random = new byte[UUID_BYTES];
|
byte[] random = new byte[UUID_BYTES];
|
||||||
secureRandom.nextBytes(random);
|
secureRandom.nextBytes(random);
|
||||||
uuid = UUID.nameUUIDFromBytes(random).toString();
|
uuid = UUID.nameUUIDFromBytes(random).toString();
|
||||||
p.put(PROP_UUID, uuid);
|
|
||||||
changed = true;
|
changed = true;
|
||||||
}
|
}
|
||||||
contactConnectionsUuid = uuid;
|
contactConnectionsUuid = uuid;
|
||||||
if (changed) callback.mergeLocalProperties(p);
|
if (changed) {
|
||||||
|
p = new TransportProperties();
|
||||||
|
// If we previously used a reflected address and there's no longer
|
||||||
|
// a reflected address with enough votes to be used, we'll continue
|
||||||
|
// to use the old reflected address until there's a new winner
|
||||||
|
if (address != null) p.put(PROP_ADDRESS, address);
|
||||||
|
p.put(PROP_UUID, uuid);
|
||||||
|
callback.mergeLocalProperties(p);
|
||||||
|
s = new Settings();
|
||||||
|
s.putBoolean(PREF_ADDRESS_IS_REFLECTED, isReflected);
|
||||||
|
callback.mergeSettings(s);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void acceptContactConnections() {
|
@Nullable
|
||||||
|
private String getReflectedAddress() {
|
||||||
|
// Count the number of votes for each reflected address
|
||||||
|
String key = REFLECTED_PROPERTY_PREFIX + PROP_ADDRESS;
|
||||||
|
Multiset<String> votes = new Multiset<>();
|
||||||
|
for (TransportProperties p : callback.getRemoteProperties()) {
|
||||||
|
String address = p.get(key);
|
||||||
|
if (address != null && isValidAddress(address)) votes.add(address);
|
||||||
|
}
|
||||||
|
// If an address gets more than half of the votes, accept it
|
||||||
|
int total = votes.getTotal();
|
||||||
|
for (String address : votes.keySet()) {
|
||||||
|
if (votes.getCount(address) * 2 > total) return address;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void acceptContactConnections(SS ss) {
|
||||||
while (true) {
|
while (true) {
|
||||||
DuplexTransportConnection conn;
|
DuplexTransportConnection conn;
|
||||||
try {
|
try {
|
||||||
conn = acceptConnection(socket);
|
conn = acceptConnection(ss);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
// This is expected when the socket is closed
|
// This is expected when the server socket is closed
|
||||||
if (LOG.isLoggable(INFO)) LOG.info(e.toString());
|
LOG.info("Server socket closed");
|
||||||
|
state.clearServerSocket();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
LOG.info("Connection received");
|
LOG.info("Connection received");
|
||||||
connectionLimiter.connectionOpened(conn);
|
connectionLimiter.connectionOpened(conn);
|
||||||
backoff.reset();
|
backoff.reset();
|
||||||
|
setEverConnected();
|
||||||
callback.handleConnection(conn);
|
callback.handleConnection(conn);
|
||||||
if (!running) return;
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setEverConnected() {
|
||||||
|
if (!everConnected.getAndSet(true)) {
|
||||||
|
ioExecutor.execute(() -> {
|
||||||
|
Settings s = new Settings();
|
||||||
|
s.putBoolean(PREF_EVER_CONNECTED, true);
|
||||||
|
callback.mergeSettings(s);
|
||||||
|
// Contacts may already have sent a reflected address
|
||||||
|
updateProperties();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void stop() {
|
public void stop() {
|
||||||
running = false;
|
SS ss = state.setStopped();
|
||||||
tryToClose(socket);
|
tryToClose(ss);
|
||||||
callback.transportDisabled();
|
|
||||||
disableAdapterIfEnabledByUs();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isRunning() {
|
public State getState() {
|
||||||
return running && isAdapterEnabled();
|
return state.getState();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getReasonsDisabled() {
|
||||||
|
return state.getReasonsDisabled();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -265,7 +332,7 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
@Override
|
@Override
|
||||||
public void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
public void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
||||||
properties) {
|
properties) {
|
||||||
if (!isRunning() || !shouldAllowContactConnections()) return;
|
if (getState() != ACTIVE) return;
|
||||||
backoff.increment();
|
backoff.increment();
|
||||||
for (Pair<TransportProperties, ConnectionHandler> p : properties) {
|
for (Pair<TransportProperties, ConnectionHandler> p : properties) {
|
||||||
connect(p.getFirst(), p.getSecond());
|
connect(p.getFirst(), p.getSecond());
|
||||||
@@ -277,10 +344,11 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
if (isNullOrEmpty(address)) return;
|
if (isNullOrEmpty(address)) return;
|
||||||
String uuid = p.get(PROP_UUID);
|
String uuid = p.get(PROP_UUID);
|
||||||
if (isNullOrEmpty(uuid)) return;
|
if (isNullOrEmpty(uuid)) return;
|
||||||
ioExecutor.execute(() -> {
|
wakefulIoExecutor.execute(() -> {
|
||||||
DuplexTransportConnection d = createConnection(p);
|
DuplexTransportConnection d = createConnection(p);
|
||||||
if (d != null) {
|
if (d != null) {
|
||||||
backoff.reset();
|
backoff.reset();
|
||||||
|
setEverConnected();
|
||||||
h.handleConnection(d);
|
h.handleConnection(d);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -319,7 +387,7 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DuplexTransportConnection createConnection(TransportProperties p) {
|
public DuplexTransportConnection createConnection(TransportProperties p) {
|
||||||
if (!isRunning() || !shouldAllowContactConnections()) return null;
|
if (getState() != ACTIVE) return null;
|
||||||
if (!connectionLimiter.canOpenContactConnection()) return null;
|
if (!connectionLimiter.canOpenContactConnection()) return null;
|
||||||
String address = p.get(PROP_ADDRESS);
|
String address = p.get(PROP_ADDRESS);
|
||||||
if (isNullOrEmpty(address)) return null;
|
if (isNullOrEmpty(address)) return null;
|
||||||
@@ -337,7 +405,7 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public KeyAgreementListener createKeyAgreementListener(byte[] commitment) {
|
public KeyAgreementListener createKeyAgreementListener(byte[] commitment) {
|
||||||
if (!isRunning()) return null;
|
if (getState() != ACTIVE) return null;
|
||||||
// No truncation necessary because COMMIT_LENGTH = 16
|
// No truncation necessary because COMMIT_LENGTH = 16
|
||||||
String uuid = UUID.nameUUIDFromBytes(commitment).toString();
|
String uuid = UUID.nameUUIDFromBytes(commitment).toString();
|
||||||
if (LOG.isLoggable(INFO)) LOG.info("Key agreement UUID " + uuid);
|
if (LOG.isLoggable(INFO)) LOG.info("Key agreement UUID " + uuid);
|
||||||
@@ -349,7 +417,7 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
logException(LOG, WARNING, e);
|
logException(LOG, WARNING, e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (!isRunning()) {
|
if (getState() != ACTIVE) {
|
||||||
tryToClose(ss);
|
tryToClose(ss);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -363,7 +431,7 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
@Override
|
@Override
|
||||||
public DuplexTransportConnection createKeyAgreementConnection(
|
public DuplexTransportConnection createKeyAgreementConnection(
|
||||||
byte[] commitment, BdfList descriptor) {
|
byte[] commitment, BdfList descriptor) {
|
||||||
if (!isRunning()) return null;
|
if (getState() != ACTIVE) return null;
|
||||||
// No truncation necessary because COMMIT_LENGTH = 16
|
// No truncation necessary because COMMIT_LENGTH = 16
|
||||||
String uuid = UUID.nameUUIDFromBytes(commitment).toString();
|
String uuid = UUID.nameUUIDFromBytes(commitment).toString();
|
||||||
DuplexTransportConnection conn;
|
DuplexTransportConnection conn;
|
||||||
@@ -383,7 +451,10 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
LOG.info("Connecting to key agreement UUID " + uuid);
|
LOG.info("Connecting to key agreement UUID " + uuid);
|
||||||
conn = connect(address, uuid);
|
conn = connect(address, uuid);
|
||||||
}
|
}
|
||||||
if (conn != null) connectionLimiter.connectionOpened(conn);
|
if (conn != null) {
|
||||||
|
connectionLimiter.connectionOpened(conn);
|
||||||
|
setEverConnected();
|
||||||
|
}
|
||||||
return conn;
|
return conn;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -406,13 +477,7 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void eventOccurred(Event e) {
|
public void eventOccurred(Event e) {
|
||||||
if (e instanceof EnableBluetoothEvent) {
|
if (e instanceof SettingsUpdatedEvent) {
|
||||||
ioExecutor.execute(this::enableAdapter);
|
|
||||||
} else if (e instanceof DisableBluetoothEvent) {
|
|
||||||
ioExecutor.execute(this::disableAdapterIfEnabledByUs);
|
|
||||||
} else if (e instanceof BluetoothEnabledEvent) {
|
|
||||||
setEnabledByUs();
|
|
||||||
} else if (e instanceof SettingsUpdatedEvent) {
|
|
||||||
SettingsUpdatedEvent s = (SettingsUpdatedEvent) e;
|
SettingsUpdatedEvent s = (SettingsUpdatedEvent) e;
|
||||||
if (s.getNamespace().equals(ID.getString()))
|
if (s.getNamespace().equals(ID.getString()))
|
||||||
ioExecutor.execute(() -> onSettingsUpdated(s.getSettings()));
|
ioExecutor.execute(() -> onSettingsUpdated(s.getSettings()));
|
||||||
@@ -420,22 +485,31 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
ioExecutor.execute(connectionLimiter::keyAgreementStarted);
|
ioExecutor.execute(connectionLimiter::keyAgreementStarted);
|
||||||
} else if (e instanceof KeyAgreementStoppedListeningEvent) {
|
} else if (e instanceof KeyAgreementStoppedListeningEvent) {
|
||||||
ioExecutor.execute(connectionLimiter::keyAgreementEnded);
|
ioExecutor.execute(connectionLimiter::keyAgreementEnded);
|
||||||
|
} else if (e instanceof RemoteTransportPropertiesUpdatedEvent) {
|
||||||
|
RemoteTransportPropertiesUpdatedEvent r =
|
||||||
|
(RemoteTransportPropertiesUpdatedEvent) e;
|
||||||
|
if (r.getTransportId().equals(ID)) {
|
||||||
|
ioExecutor.execute(this::updateProperties);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@IoExecutor
|
||||||
private void onSettingsUpdated(Settings settings) {
|
private void onSettingsUpdated(Settings settings) {
|
||||||
boolean wasAllowed = shouldAllowContactConnections();
|
boolean enabledByUser = settings.getBoolean(PREF_PLUGIN_ENABLE,
|
||||||
loadSettings(settings);
|
DEFAULT_PREF_PLUGIN_ENABLE);
|
||||||
boolean isAllowed = shouldAllowContactConnections();
|
SS ss = state.setEnabledByUser(enabledByUser);
|
||||||
if (wasAllowed && !isAllowed) {
|
State s = getState();
|
||||||
LOG.info("Contact connections disabled");
|
if (ss != null) {
|
||||||
tryToClose(socket);
|
LOG.info("Disabled by user, closing server socket");
|
||||||
callback.transportDisabled();
|
tryToClose(ss);
|
||||||
disableAdapterIfEnabledByUs();
|
} else if (s == INACTIVE) {
|
||||||
} else if (!wasAllowed && isAllowed) {
|
if (isAdapterEnabled()) {
|
||||||
LOG.info("Contact connections enabled");
|
LOG.info("Enabled by user, opening server socket");
|
||||||
if (isAdapterEnabled()) bind();
|
bind();
|
||||||
else enableAdapter();
|
} else {
|
||||||
|
LOG.info("Enabled by user but adapter is disabled");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -461,4 +535,70 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
|||||||
tryToClose(ss);
|
tryToClose(ss);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ThreadSafe
|
||||||
|
@NotNullByDefault
|
||||||
|
protected class PluginState {
|
||||||
|
|
||||||
|
@GuardedBy("this")
|
||||||
|
private boolean started = false,
|
||||||
|
stopped = false,
|
||||||
|
enabledByUser = false;
|
||||||
|
|
||||||
|
@GuardedBy("this")
|
||||||
|
@Nullable
|
||||||
|
private SS serverSocket = null;
|
||||||
|
|
||||||
|
synchronized void setStarted(boolean enabledByUser) {
|
||||||
|
started = true;
|
||||||
|
this.enabledByUser = enabledByUser;
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
synchronized SS setStopped() {
|
||||||
|
stopped = true;
|
||||||
|
SS ss = serverSocket;
|
||||||
|
serverSocket = null;
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
return ss;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
synchronized SS setEnabledByUser(boolean enabledByUser) {
|
||||||
|
this.enabledByUser = enabledByUser;
|
||||||
|
SS ss = null;
|
||||||
|
if (!enabledByUser) {
|
||||||
|
ss = serverSocket;
|
||||||
|
serverSocket = null;
|
||||||
|
}
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
return ss;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized boolean setServerSocket(SS ss) {
|
||||||
|
if (stopped || serverSocket != null) return false;
|
||||||
|
serverSocket = ss;
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
synchronized SS clearServerSocket() {
|
||||||
|
SS ss = serverSocket;
|
||||||
|
serverSocket = null;
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
return ss;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized State getState() {
|
||||||
|
if (!started || stopped) return STARTING_STOPPING;
|
||||||
|
if (!enabledByUser) return DISABLED;
|
||||||
|
return serverSocket == null ? INACTIVE : ACTIVE;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized int getReasonsDisabled() {
|
||||||
|
return getState() == DISABLED ? REASON_USER : 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import java.util.logging.Logger;
|
|||||||
import static java.util.logging.Level.WARNING;
|
import static java.util.logging.Level.WARNING;
|
||||||
import static java.util.logging.Logger.getLogger;
|
import static java.util.logging.Logger.getLogger;
|
||||||
import static org.briarproject.bramble.api.plugin.FileConstants.PROP_PATH;
|
import static org.briarproject.bramble.api.plugin.FileConstants.PROP_PATH;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.ACTIVE;
|
||||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||||
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
||||||
|
|
||||||
@@ -45,7 +46,7 @@ abstract class FilePlugin implements SimplexPlugin {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TransportConnectionReader createReader(TransportProperties p) {
|
public TransportConnectionReader createReader(TransportProperties p) {
|
||||||
if (!isRunning()) return null;
|
if (getState() != ACTIVE) return null;
|
||||||
String path = p.get(PROP_PATH);
|
String path = p.get(PROP_PATH);
|
||||||
if (isNullOrEmpty(path)) return null;
|
if (isNullOrEmpty(path)) return null;
|
||||||
try {
|
try {
|
||||||
@@ -60,7 +61,7 @@ abstract class FilePlugin implements SimplexPlugin {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TransportConnectionWriter createWriter(TransportProperties p) {
|
public TransportConnectionWriter createWriter(TransportProperties p) {
|
||||||
if (!isRunning()) return null;
|
if (getState() != ACTIVE) return null;
|
||||||
String path = p.get(PROP_PATH);
|
String path = p.get(PROP_PATH);
|
||||||
if (isNullOrEmpty(path)) return null;
|
if (isNullOrEmpty(path)) return null;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ import org.briarproject.bramble.api.plugin.TransportId;
|
|||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
import org.briarproject.bramble.api.settings.Settings;
|
import org.briarproject.bramble.api.settings.Settings;
|
||||||
import org.briarproject.bramble.util.IoUtils;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.Inet4Address;
|
import java.net.Inet4Address;
|
||||||
|
import java.net.Inet6Address;
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
import java.net.InetSocketAddress;
|
import java.net.InetSocketAddress;
|
||||||
import java.net.InterfaceAddress;
|
import java.net.InterfaceAddress;
|
||||||
@@ -22,8 +22,9 @@ import java.net.ServerSocket;
|
|||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
import java.net.UnknownHostException;
|
import java.net.UnknownHostException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Deque;
|
||||||
|
import java.util.LinkedList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Random;
|
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
@@ -31,38 +32,49 @@ import javax.annotation.Nullable;
|
|||||||
|
|
||||||
import static java.lang.Integer.parseInt;
|
import static java.lang.Integer.parseInt;
|
||||||
import static java.util.Collections.addAll;
|
import static java.util.Collections.addAll;
|
||||||
|
import static java.util.Collections.emptyList;
|
||||||
import static java.util.Collections.sort;
|
import static java.util.Collections.sort;
|
||||||
import static java.util.logging.Level.INFO;
|
import static java.util.logging.Level.INFO;
|
||||||
import static java.util.logging.Level.WARNING;
|
import static java.util.logging.Level.WARNING;
|
||||||
import static java.util.logging.Logger.getLogger;
|
import static java.util.logging.Logger.getLogger;
|
||||||
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TRANSPORT_ID_LAN;
|
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TRANSPORT_ID_LAN;
|
||||||
|
import static org.briarproject.bramble.api.plugin.LanTcpConstants.DEFAULT_PREF_PLUGIN_ENABLE;
|
||||||
import static org.briarproject.bramble.api.plugin.LanTcpConstants.ID;
|
import static org.briarproject.bramble.api.plugin.LanTcpConstants.ID;
|
||||||
|
import static org.briarproject.bramble.api.plugin.LanTcpConstants.PREF_IPV6;
|
||||||
import static org.briarproject.bramble.api.plugin.LanTcpConstants.PREF_LAN_IP_PORTS;
|
import static org.briarproject.bramble.api.plugin.LanTcpConstants.PREF_LAN_IP_PORTS;
|
||||||
|
import static org.briarproject.bramble.api.plugin.LanTcpConstants.PROP_IPV6;
|
||||||
import static org.briarproject.bramble.api.plugin.LanTcpConstants.PROP_IP_PORTS;
|
import static org.briarproject.bramble.api.plugin.LanTcpConstants.PROP_IP_PORTS;
|
||||||
import static org.briarproject.bramble.api.plugin.LanTcpConstants.PROP_PORT;
|
import static org.briarproject.bramble.api.plugin.LanTcpConstants.PROP_PORT;
|
||||||
|
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.MAX_PROPERTY_LENGTH;
|
||||||
import static org.briarproject.bramble.util.ByteUtils.MAX_16_BIT_UNSIGNED;
|
import static org.briarproject.bramble.util.ByteUtils.MAX_16_BIT_UNSIGNED;
|
||||||
|
import static org.briarproject.bramble.util.IoUtils.tryToClose;
|
||||||
import static org.briarproject.bramble.util.PrivacyUtils.scrubSocketAddress;
|
import static org.briarproject.bramble.util.PrivacyUtils.scrubSocketAddress;
|
||||||
|
import static org.briarproject.bramble.util.StringUtils.fromHexString;
|
||||||
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
||||||
import static org.briarproject.bramble.util.StringUtils.join;
|
import static org.briarproject.bramble.util.StringUtils.join;
|
||||||
|
import static org.briarproject.bramble.util.StringUtils.toHexString;
|
||||||
|
import static org.briarproject.bramble.util.StringUtils.utf8IsTooLong;
|
||||||
|
|
||||||
@NotNullByDefault
|
@NotNullByDefault
|
||||||
class LanTcpPlugin extends TcpPlugin {
|
class LanTcpPlugin extends TcpPlugin {
|
||||||
|
|
||||||
private static final Logger LOG = getLogger(LanTcpPlugin.class.getName());
|
private static final Logger LOG = getLogger(LanTcpPlugin.class.getName());
|
||||||
|
|
||||||
private static final int MAX_ADDRESSES = 4;
|
|
||||||
private static final String SEPARATOR = ",";
|
private static final String SEPARATOR = ",";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The IP address of an Android device providing a wifi access point.
|
* The IP address of an Android device providing a wifi access point.
|
||||||
|
* <p>
|
||||||
|
* Most devices use this address, but at least one device (Honor 8A) may
|
||||||
|
* use other addresses in the range 192.168.43.0/24.
|
||||||
*/
|
*/
|
||||||
protected static final InetAddress WIFI_AP_ADDRESS;
|
private static final InetAddress WIFI_AP_ADDRESS;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The IP address of an Android device providing a wifi direct
|
* The IP address of an Android device providing a wifi direct
|
||||||
* legacy mode access point.
|
* legacy mode access point.
|
||||||
*/
|
*/
|
||||||
protected static final InetAddress WIFI_DIRECT_AP_ADDRESS;
|
private static final InetAddress WIFI_DIRECT_AP_ADDRESS;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
try {
|
try {
|
||||||
@@ -76,10 +88,15 @@ class LanTcpPlugin extends TcpPlugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
LanTcpPlugin(Executor ioExecutor, Backoff backoff, PluginCallback callback,
|
LanTcpPlugin(Executor ioExecutor,
|
||||||
int maxLatency, int maxIdleTime, int connectionTimeout) {
|
Executor wakefulIoExecutor,
|
||||||
super(ioExecutor, backoff, callback, maxLatency, maxIdleTime,
|
Backoff backoff,
|
||||||
connectionTimeout);
|
PluginCallback callback,
|
||||||
|
int maxLatency,
|
||||||
|
int maxIdleTime,
|
||||||
|
int connectionTimeout) {
|
||||||
|
super(ioExecutor, wakefulIoExecutor, backoff, callback, maxLatency,
|
||||||
|
maxIdleTime, connectionTimeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -91,29 +108,36 @@ class LanTcpPlugin extends TcpPlugin {
|
|||||||
public void start() {
|
public void start() {
|
||||||
if (used.getAndSet(true)) throw new IllegalStateException();
|
if (used.getAndSet(true)) throw new IllegalStateException();
|
||||||
initialisePortProperty();
|
initialisePortProperty();
|
||||||
running = true;
|
Settings settings = callback.getSettings();
|
||||||
|
state.setStarted(settings.getBoolean(PREF_PLUGIN_ENABLE,
|
||||||
|
DEFAULT_PREF_PLUGIN_ENABLE));
|
||||||
bind();
|
bind();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void initialisePortProperty() {
|
protected void initialisePortProperty() {
|
||||||
TransportProperties p = callback.getLocalProperties();
|
TransportProperties p = callback.getLocalProperties();
|
||||||
if (isNullOrEmpty(p.get(PROP_PORT))) {
|
if (isNullOrEmpty(p.get(PROP_PORT))) {
|
||||||
int port = new Random().nextInt(32768) + 32768;
|
int port = chooseEphemeralPort();
|
||||||
p.put(PROP_PORT, String.valueOf(port));
|
p.put(PROP_PORT, String.valueOf(port));
|
||||||
callback.mergeLocalProperties(p);
|
callback.mergeLocalProperties(p);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected List<InetSocketAddress> getLocalSocketAddresses() {
|
protected boolean isEnabledByDefault() {
|
||||||
|
return DEFAULT_PREF_PLUGIN_ENABLE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected List<InetSocketAddress> getLocalSocketAddresses(boolean ipv4) {
|
||||||
TransportProperties p = callback.getLocalProperties();
|
TransportProperties p = callback.getLocalProperties();
|
||||||
int preferredPort = parsePortProperty(p.get(PROP_PORT));
|
int preferredPort = parsePortProperty(p.get(PROP_PORT));
|
||||||
String oldIpPorts = p.get(PROP_IP_PORTS);
|
String oldIpPorts = p.get(PROP_IP_PORTS);
|
||||||
List<InetSocketAddress> olds = parseSocketAddresses(oldIpPorts);
|
List<InetSocketAddress> olds = parseIpv4SocketAddresses(oldIpPorts);
|
||||||
|
|
||||||
List<InetSocketAddress> locals = new ArrayList<>();
|
List<InetSocketAddress> locals = new ArrayList<>();
|
||||||
List<InetSocketAddress> fallbacks = new ArrayList<>();
|
List<InetSocketAddress> fallbacks = new ArrayList<>();
|
||||||
for (InetAddress local : getUsableLocalInetAddresses()) {
|
for (InetAddress local : getUsableLocalInetAddresses(ipv4)) {
|
||||||
// If we've used this address before, try to use the same port
|
// If we've used this address before, try to use the same port
|
||||||
int port = preferredPort;
|
int port = preferredPort;
|
||||||
for (InetSocketAddress old : olds) {
|
for (InetSocketAddress old : olds) {
|
||||||
@@ -139,17 +163,17 @@ class LanTcpPlugin extends TcpPlugin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<InetSocketAddress> parseSocketAddresses(String ipPorts) {
|
private List<InetSocketAddress> parseIpv4SocketAddresses(String ipPorts) {
|
||||||
List<InetSocketAddress> addresses = new ArrayList<>();
|
List<InetSocketAddress> addresses = new ArrayList<>();
|
||||||
if (isNullOrEmpty(ipPorts)) return addresses;
|
if (isNullOrEmpty(ipPorts)) return addresses;
|
||||||
for (String ipPort : ipPorts.split(SEPARATOR)) {
|
for (String ipPort : ipPorts.split(SEPARATOR)) {
|
||||||
InetSocketAddress a = parseSocketAddress(ipPort);
|
InetSocketAddress a = parseIpv4SocketAddress(ipPort);
|
||||||
if (a != null) addresses.add(a);
|
if (a != null) addresses.add(a);
|
||||||
}
|
}
|
||||||
return addresses;
|
return addresses;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected List<InetAddress> getUsableLocalInetAddresses() {
|
protected List<InetAddress> getUsableLocalInetAddresses(boolean ipv4) {
|
||||||
List<InterfaceAddress> ifAddrs =
|
List<InterfaceAddress> ifAddrs =
|
||||||
new ArrayList<>(getLocalInterfaceAddresses());
|
new ArrayList<>(getLocalInterfaceAddresses());
|
||||||
// Prefer longer network prefixes
|
// Prefer longer network prefixes
|
||||||
@@ -158,50 +182,74 @@ class LanTcpPlugin extends TcpPlugin {
|
|||||||
List<InetAddress> addrs = new ArrayList<>();
|
List<InetAddress> addrs = new ArrayList<>();
|
||||||
for (InterfaceAddress ifAddr : ifAddrs) {
|
for (InterfaceAddress ifAddr : ifAddrs) {
|
||||||
InetAddress addr = ifAddr.getAddress();
|
InetAddress addr = ifAddr.getAddress();
|
||||||
if (isAcceptableAddress(addr)) addrs.add(addr);
|
if (isAcceptableAddress(addr, ipv4)) addrs.add(addr);
|
||||||
}
|
}
|
||||||
return addrs;
|
return addrs;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void setLocalSocketAddress(InetSocketAddress a) {
|
protected void setLocalSocketAddress(InetSocketAddress a, boolean ipv4) {
|
||||||
|
if (ipv4) setLocalIpv4SocketAddress(a);
|
||||||
|
else setLocalIpv6SocketAddress(a);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setLocalIpv4SocketAddress(InetSocketAddress a) {
|
||||||
String ipPort = getIpPortString(a);
|
String ipPort = getIpPortString(a);
|
||||||
|
updateRecentAddresses(PREF_LAN_IP_PORTS, PROP_IP_PORTS, ipPort);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setLocalIpv6SocketAddress(InetSocketAddress a) {
|
||||||
|
String hex = toHexString(a.getAddress().getAddress());
|
||||||
|
updateRecentAddresses(PREF_IPV6, PROP_IPV6, hex);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateRecentAddresses(String settingKey, String propertyKey,
|
||||||
|
String item) {
|
||||||
// Get the list of recently used addresses
|
// Get the list of recently used addresses
|
||||||
String setting = callback.getSettings().get(PREF_LAN_IP_PORTS);
|
String setting = callback.getSettings().get(settingKey);
|
||||||
List<String> recent = new ArrayList<>();
|
Deque<String> recent = new LinkedList<>();
|
||||||
if (!isNullOrEmpty(setting))
|
if (!isNullOrEmpty(setting)) {
|
||||||
addAll(recent, setting.split(SEPARATOR));
|
addAll(recent, setting.split(SEPARATOR));
|
||||||
// Is the address already in the list?
|
}
|
||||||
if (recent.remove(ipPort)) {
|
if (recent.remove(item)) {
|
||||||
// Move the address to the start of the list
|
// Move the item to the start of the list
|
||||||
recent.add(0, ipPort);
|
recent.addFirst(item);
|
||||||
setting = join(recent, SEPARATOR);
|
setting = join(recent, SEPARATOR);
|
||||||
} else {
|
} else {
|
||||||
// Add the address to the start of the list
|
// Add the item to the start of the list
|
||||||
recent.add(0, ipPort);
|
recent.addFirst(item);
|
||||||
// Drop the least recently used address if the list is full
|
// Drop items from the end of the list if it's too long to encode
|
||||||
if (recent.size() > MAX_ADDRESSES)
|
|
||||||
recent = recent.subList(0, MAX_ADDRESSES);
|
|
||||||
setting = join(recent, SEPARATOR);
|
setting = join(recent, SEPARATOR);
|
||||||
|
while (utf8IsTooLong(setting, MAX_PROPERTY_LENGTH)) {
|
||||||
|
recent.removeLast();
|
||||||
|
setting = join(recent, SEPARATOR);
|
||||||
|
}
|
||||||
// Update the list of addresses shared with contacts
|
// Update the list of addresses shared with contacts
|
||||||
List<String> shared = new ArrayList<>(recent);
|
|
||||||
sort(shared);
|
|
||||||
String property = join(shared, SEPARATOR);
|
|
||||||
TransportProperties properties = new TransportProperties();
|
TransportProperties properties = new TransportProperties();
|
||||||
properties.put(PROP_IP_PORTS, property);
|
properties.put(propertyKey, setting);
|
||||||
callback.mergeLocalProperties(properties);
|
callback.mergeLocalProperties(properties);
|
||||||
}
|
}
|
||||||
// Save the setting
|
// Save the setting
|
||||||
Settings settings = new Settings();
|
Settings settings = new Settings();
|
||||||
settings.put(PREF_LAN_IP_PORTS, setting);
|
settings.put(settingKey, setting);
|
||||||
callback.mergeSettings(settings);
|
callback.mergeSettings(settings);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected boolean isIpv6LinkLocalAddress(InetAddress a) {
|
||||||
|
return a instanceof Inet6Address && a.isLinkLocalAddress();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected List<InetSocketAddress> getRemoteSocketAddresses(
|
protected List<InetSocketAddress> getRemoteSocketAddresses(
|
||||||
|
TransportProperties p, boolean ipv4) {
|
||||||
|
if (ipv4) return getRemoteIpv4SocketAddresses(p);
|
||||||
|
else return getRemoteIpv6SocketAddresses(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<InetSocketAddress> getRemoteIpv4SocketAddresses(
|
||||||
TransportProperties p) {
|
TransportProperties p) {
|
||||||
String ipPorts = p.get(PROP_IP_PORTS);
|
String ipPorts = p.get(PROP_IP_PORTS);
|
||||||
List<InetSocketAddress> remotes = parseSocketAddresses(ipPorts);
|
List<InetSocketAddress> remotes = parseIpv4SocketAddresses(ipPorts);
|
||||||
int port = parsePortProperty(p.get(PROP_PORT));
|
int port = parsePortProperty(p.get(PROP_PORT));
|
||||||
// If the contact has a preferred port, we can guess their IP:port when
|
// If the contact has a preferred port, we can guess their IP:port when
|
||||||
// they're providing a wifi access point
|
// they're providing a wifi access point
|
||||||
@@ -216,20 +264,52 @@ class LanTcpPlugin extends TcpPlugin {
|
|||||||
return remotes;
|
return remotes;
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isAcceptableAddress(InetAddress a) {
|
private List<InetSocketAddress> getRemoteIpv6SocketAddresses(
|
||||||
// Accept link-local and site-local IPv4 addresses
|
TransportProperties p) {
|
||||||
boolean ipv4 = a instanceof Inet4Address;
|
List<InetAddress> addrs = parseIpv6Addresses(p.get(PROP_IPV6));
|
||||||
boolean loop = a.isLoopbackAddress();
|
int port = parsePortProperty(p.get(PROP_PORT));
|
||||||
boolean link = a.isLinkLocalAddress();
|
if (addrs.isEmpty() || port == 0) return emptyList();
|
||||||
boolean site = a.isSiteLocalAddress();
|
List<InetSocketAddress> remotes = new ArrayList<>();
|
||||||
return ipv4 && !loop && (link || site);
|
for (InetAddress addr : addrs) {
|
||||||
|
remotes.add(new InetSocketAddress(addr, port));
|
||||||
|
}
|
||||||
|
return remotes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<InetAddress> parseIpv6Addresses(String property) {
|
||||||
|
if (isNullOrEmpty(property)) return emptyList();
|
||||||
|
try {
|
||||||
|
List<InetAddress> addrs = new ArrayList<>();
|
||||||
|
for (String hex : property.split(SEPARATOR)) {
|
||||||
|
byte[] ip = fromHexString(hex);
|
||||||
|
if (ip.length == 16) addrs.add(InetAddress.getByAddress(ip));
|
||||||
|
}
|
||||||
|
return addrs;
|
||||||
|
} catch (IllegalArgumentException | UnknownHostException e) {
|
||||||
|
return emptyList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isAcceptableAddress(InetAddress a, boolean ipv4) {
|
||||||
|
if (ipv4) {
|
||||||
|
// Accept link-local and site-local IPv4 addresses
|
||||||
|
boolean isIpv4 = a instanceof Inet4Address;
|
||||||
|
boolean link = a.isLinkLocalAddress();
|
||||||
|
boolean site = a.isSiteLocalAddress();
|
||||||
|
return isIpv4 && (link || site);
|
||||||
|
} else {
|
||||||
|
// Accept link-local IPv6 addresses
|
||||||
|
return isIpv6LinkLocalAddress(a);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected boolean isConnectable(InterfaceAddress local,
|
protected boolean isConnectable(InterfaceAddress local,
|
||||||
InetSocketAddress remote) {
|
InetSocketAddress remote) {
|
||||||
if (remote.getPort() == 0) return false;
|
if (remote.getPort() == 0) return false;
|
||||||
if (!isAcceptableAddress(remote.getAddress())) return false;
|
InetAddress remoteAddress = remote.getAddress();
|
||||||
|
boolean ipv4 = local.getAddress() instanceof Inet4Address;
|
||||||
|
if (!isAcceptableAddress(remoteAddress, ipv4)) return false;
|
||||||
// Try to determine whether the address is on the same LAN as us
|
// Try to determine whether the address is on the same LAN as us
|
||||||
byte[] localIp = local.getAddress().getAddress();
|
byte[] localIp = local.getAddress().getAddress();
|
||||||
byte[] remoteIp = remote.getAddress().getAddress();
|
byte[] remoteIp = remote.getAddress().getAddress();
|
||||||
@@ -271,7 +351,7 @@ class LanTcpPlugin extends TcpPlugin {
|
|||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
if (LOG.isLoggable(INFO))
|
if (LOG.isLoggable(INFO))
|
||||||
LOG.info("Failed to bind " + scrubSocketAddress(addr));
|
LOG.info("Failed to bind " + scrubSocketAddress(addr));
|
||||||
tryToClose(ss);
|
tryToClose(ss, LOG, WARNING);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (ss == null || !ss.isBound()) {
|
if (ss == null || !ss.isBound()) {
|
||||||
@@ -287,11 +367,18 @@ class LanTcpPlugin extends TcpPlugin {
|
|||||||
return new LanKeyAgreementListener(descriptor, ss);
|
return new LanKeyAgreementListener(descriptor, ss);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private List<InetSocketAddress> getLocalSocketAddresses() {
|
||||||
|
List<InetSocketAddress> addrs = new ArrayList<>();
|
||||||
|
addrs.addAll(getLocalSocketAddresses(true));
|
||||||
|
addrs.addAll(getLocalSocketAddresses(false));
|
||||||
|
return addrs;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DuplexTransportConnection createKeyAgreementConnection(
|
public DuplexTransportConnection createKeyAgreementConnection(
|
||||||
byte[] commitment, BdfList descriptor) {
|
byte[] commitment, BdfList descriptor) {
|
||||||
if (!isRunning()) return null;
|
ServerSocket ss = state.getServerSocket(true);
|
||||||
ServerSocket ss = socket;
|
if (ss == null) return null;
|
||||||
InterfaceAddress local = getLocalInterfaceAddress(ss.getInetAddress());
|
InterfaceAddress local = getLocalInterfaceAddress(ss.getInetAddress());
|
||||||
if (local == null) {
|
if (local == null) {
|
||||||
LOG.warning("No interface for key agreement server socket");
|
LOG.warning("No interface for key agreement server socket");
|
||||||
@@ -363,7 +450,7 @@ class LanTcpPlugin extends TcpPlugin {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() {
|
public void close() {
|
||||||
IoUtils.tryToClose(ss, LOG, WARNING);
|
tryToClose(ss, LOG, WARNING);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package org.briarproject.bramble.plugin.tcp;
|
package org.briarproject.bramble.plugin.tcp;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.event.EventBus;
|
||||||
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
||||||
@@ -7,10 +9,12 @@ import org.briarproject.bramble.api.plugin.PluginCallback;
|
|||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||||
|
import org.briarproject.bramble.api.system.WakefulIoExecutor;
|
||||||
|
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
import javax.annotation.concurrent.Immutable;
|
import javax.annotation.concurrent.Immutable;
|
||||||
|
import javax.inject.Inject;
|
||||||
|
|
||||||
import static org.briarproject.bramble.api.plugin.LanTcpConstants.ID;
|
import static org.briarproject.bramble.api.plugin.LanTcpConstants.ID;
|
||||||
|
|
||||||
@@ -25,12 +29,18 @@ public class LanTcpPluginFactory implements DuplexPluginFactory {
|
|||||||
private static final int MAX_POLLING_INTERVAL = 600_000; // 10 mins
|
private static final int MAX_POLLING_INTERVAL = 600_000; // 10 mins
|
||||||
private static final double BACKOFF_BASE = 1.2;
|
private static final double BACKOFF_BASE = 1.2;
|
||||||
|
|
||||||
private final Executor ioExecutor;
|
private final Executor ioExecutor, wakefulIoExecutor;
|
||||||
|
private final EventBus eventBus;
|
||||||
private final BackoffFactory backoffFactory;
|
private final BackoffFactory backoffFactory;
|
||||||
|
|
||||||
public LanTcpPluginFactory(Executor ioExecutor,
|
@Inject
|
||||||
|
public LanTcpPluginFactory(@IoExecutor Executor ioExecutor,
|
||||||
|
@WakefulIoExecutor Executor wakefulIoExecutor,
|
||||||
|
EventBus eventBus,
|
||||||
BackoffFactory backoffFactory) {
|
BackoffFactory backoffFactory) {
|
||||||
this.ioExecutor = ioExecutor;
|
this.ioExecutor = ioExecutor;
|
||||||
|
this.wakefulIoExecutor = wakefulIoExecutor;
|
||||||
|
this.eventBus = eventBus;
|
||||||
this.backoffFactory = backoffFactory;
|
this.backoffFactory = backoffFactory;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,7 +58,10 @@ public class LanTcpPluginFactory implements DuplexPluginFactory {
|
|||||||
public DuplexPlugin createPlugin(PluginCallback callback) {
|
public DuplexPlugin createPlugin(PluginCallback callback) {
|
||||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||||
return new LanTcpPlugin(ioExecutor, backoff, callback, MAX_LATENCY,
|
LanTcpPlugin plugin = new LanTcpPlugin(ioExecutor, wakefulIoExecutor,
|
||||||
MAX_IDLE_TIME, CONNECTION_TIMEOUT);
|
backoff, callback, MAX_LATENCY, MAX_IDLE_TIME,
|
||||||
|
CONNECTION_TIMEOUT);
|
||||||
|
eventBus.addListener(plugin);
|
||||||
|
return plugin;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,11 +54,13 @@ class PortMapperImpl implements PortMapper {
|
|||||||
shutdownManager.addShutdownHook(() -> deleteMapping(port));
|
shutdownManager.addShutdownHook(() -> deleteMapping(port));
|
||||||
}
|
}
|
||||||
String externalString = gateway.getExternalIPAddress();
|
String externalString = gateway.getExternalIPAddress();
|
||||||
if (LOG.isLoggable(INFO))
|
if (externalString == null) {
|
||||||
LOG.info(
|
LOG.info("External address not available");
|
||||||
"External address " + scrubInetAddress(externalString));
|
} else {
|
||||||
if (externalString != null)
|
|
||||||
external = InetAddress.getByName(externalString);
|
external = InetAddress.getByName(externalString);
|
||||||
|
if (LOG.isLoggable(INFO))
|
||||||
|
LOG.info("External address " + scrubInetAddress(external));
|
||||||
|
}
|
||||||
} catch (IOException | SAXException e) {
|
} catch (IOException | SAXException e) {
|
||||||
logException(LOG, WARNING, e);
|
logException(LOG, WARNING, e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,12 @@ package org.briarproject.bramble.plugin.tcp;
|
|||||||
import org.briarproject.bramble.PoliteExecutor;
|
import org.briarproject.bramble.PoliteExecutor;
|
||||||
import org.briarproject.bramble.api.Pair;
|
import org.briarproject.bramble.api.Pair;
|
||||||
import org.briarproject.bramble.api.data.BdfList;
|
import org.briarproject.bramble.api.data.BdfList;
|
||||||
|
import org.briarproject.bramble.api.event.Event;
|
||||||
|
import org.briarproject.bramble.api.event.EventListener;
|
||||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
|
import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
|
||||||
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
import org.briarproject.bramble.api.plugin.ConnectionHandler;
|
import org.briarproject.bramble.api.plugin.ConnectionHandler;
|
||||||
@@ -14,7 +18,8 @@ import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
|||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
||||||
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
||||||
import org.briarproject.bramble.util.IoUtils;
|
import org.briarproject.bramble.api.settings.Settings;
|
||||||
|
import org.briarproject.bramble.api.settings.event.SettingsUpdatedEvent;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.InetAddress;
|
import java.net.InetAddress;
|
||||||
@@ -35,53 +40,60 @@ import java.util.logging.Logger;
|
|||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
import javax.annotation.Nullable;
|
import javax.annotation.Nullable;
|
||||||
|
import javax.annotation.concurrent.GuardedBy;
|
||||||
|
import javax.annotation.concurrent.ThreadSafe;
|
||||||
|
|
||||||
import static java.util.Collections.emptyList;
|
import static java.util.Collections.emptyList;
|
||||||
import static java.util.Collections.list;
|
import static java.util.Collections.list;
|
||||||
import static java.util.logging.Level.INFO;
|
import static java.util.logging.Level.INFO;
|
||||||
import static java.util.logging.Level.WARNING;
|
import static java.util.logging.Level.WARNING;
|
||||||
import static java.util.logging.Logger.getLogger;
|
import static java.util.logging.Logger.getLogger;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.ACTIVE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.DISABLED;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.INACTIVE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.STARTING_STOPPING;
|
||||||
|
import static org.briarproject.bramble.util.IoUtils.tryToClose;
|
||||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||||
import static org.briarproject.bramble.util.PrivacyUtils.scrubSocketAddress;
|
import static org.briarproject.bramble.util.PrivacyUtils.scrubSocketAddress;
|
||||||
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
||||||
|
|
||||||
@MethodsNotNullByDefault
|
@MethodsNotNullByDefault
|
||||||
@ParametersNotNullByDefault
|
@ParametersNotNullByDefault
|
||||||
abstract class TcpPlugin implements DuplexPlugin {
|
abstract class TcpPlugin implements DuplexPlugin, EventListener {
|
||||||
|
|
||||||
private static final Logger LOG = getLogger(TcpPlugin.class.getName());
|
private static final Logger LOG = getLogger(TcpPlugin.class.getName());
|
||||||
|
|
||||||
private static final Pattern DOTTED_QUAD =
|
private static final Pattern DOTTED_QUAD =
|
||||||
Pattern.compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
|
Pattern.compile("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$");
|
||||||
|
|
||||||
protected final Executor ioExecutor, bindExecutor;
|
protected final Executor ioExecutor, wakefulIoExecutor, bindExecutor;
|
||||||
protected final Backoff backoff;
|
protected final Backoff backoff;
|
||||||
protected final PluginCallback callback;
|
protected final PluginCallback callback;
|
||||||
protected final int maxLatency, maxIdleTime;
|
protected final int maxLatency, maxIdleTime;
|
||||||
protected final int connectionTimeout, socketTimeout;
|
protected final int connectionTimeout, socketTimeout;
|
||||||
protected final AtomicBoolean used = new AtomicBoolean(false);
|
protected final AtomicBoolean used = new AtomicBoolean(false);
|
||||||
|
protected final PluginState state = new PluginState();
|
||||||
protected volatile boolean running = false;
|
|
||||||
protected volatile ServerSocket socket = null;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns zero or more socket addresses on which the plugin should listen,
|
* Returns zero or more socket addresses on which the plugin should listen,
|
||||||
* in order of preference. At most one of the addresses will be bound.
|
* in order of preference. At most one of the addresses will be bound.
|
||||||
*/
|
*/
|
||||||
protected abstract List<InetSocketAddress> getLocalSocketAddresses();
|
protected abstract List<InetSocketAddress> getLocalSocketAddresses(
|
||||||
|
boolean ipv4);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds the address on which the plugin is listening to the transport
|
* Adds the address on which the plugin is listening to the transport
|
||||||
* properties.
|
* properties.
|
||||||
*/
|
*/
|
||||||
protected abstract void setLocalSocketAddress(InetSocketAddress a);
|
protected abstract void setLocalSocketAddress(InetSocketAddress a,
|
||||||
|
boolean ipv4);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns zero or more socket addresses for connecting to a contact with
|
* Returns zero or more socket addresses for connecting to a contact with
|
||||||
* the given transport properties.
|
* the given transport properties.
|
||||||
*/
|
*/
|
||||||
protected abstract List<InetSocketAddress> getRemoteSocketAddresses(
|
protected abstract List<InetSocketAddress> getRemoteSocketAddresses(
|
||||||
TransportProperties p);
|
TransportProperties p, boolean ipv4);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns true if connections to the given address can be attempted.
|
* Returns true if connections to the given address can be attempted.
|
||||||
@@ -90,9 +102,20 @@ abstract class TcpPlugin implements DuplexPlugin {
|
|||||||
protected abstract boolean isConnectable(InterfaceAddress local,
|
protected abstract boolean isConnectable(InterfaceAddress local,
|
||||||
InetSocketAddress remote);
|
InetSocketAddress remote);
|
||||||
|
|
||||||
TcpPlugin(Executor ioExecutor, Backoff backoff, PluginCallback callback,
|
/**
|
||||||
int maxLatency, int maxIdleTime, int connectionTimeout) {
|
* Returns true if the plugin is enabled by default.
|
||||||
|
*/
|
||||||
|
protected abstract boolean isEnabledByDefault();
|
||||||
|
|
||||||
|
TcpPlugin(Executor ioExecutor,
|
||||||
|
Executor wakefulIoExecutor,
|
||||||
|
Backoff backoff,
|
||||||
|
PluginCallback callback,
|
||||||
|
int maxLatency,
|
||||||
|
int maxIdleTime,
|
||||||
|
int connectionTimeout) {
|
||||||
this.ioExecutor = ioExecutor;
|
this.ioExecutor = ioExecutor;
|
||||||
|
this.wakefulIoExecutor = wakefulIoExecutor;
|
||||||
this.backoff = backoff;
|
this.backoff = backoff;
|
||||||
this.callback = callback;
|
this.callback = callback;
|
||||||
this.maxLatency = maxLatency;
|
this.maxLatency = maxLatency;
|
||||||
@@ -118,49 +141,56 @@ abstract class TcpPlugin implements DuplexPlugin {
|
|||||||
@Override
|
@Override
|
||||||
public void start() {
|
public void start() {
|
||||||
if (used.getAndSet(true)) throw new IllegalStateException();
|
if (used.getAndSet(true)) throw new IllegalStateException();
|
||||||
running = true;
|
Settings settings = callback.getSettings();
|
||||||
|
state.setStarted(
|
||||||
|
settings.getBoolean(PREF_PLUGIN_ENABLE, isEnabledByDefault()));
|
||||||
bind();
|
bind();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void bind() {
|
protected void bind() {
|
||||||
bindExecutor.execute(() -> {
|
bindExecutor.execute(() -> {
|
||||||
if (!running) return;
|
State s = getState();
|
||||||
if (socket != null && !socket.isClosed()) return;
|
if (s != ACTIVE && s != INACTIVE) return;
|
||||||
ServerSocket ss = null;
|
bind(true);
|
||||||
for (InetSocketAddress addr : getLocalSocketAddresses()) {
|
bind(false);
|
||||||
try {
|
|
||||||
ss = new ServerSocket();
|
|
||||||
ss.bind(addr);
|
|
||||||
break;
|
|
||||||
} catch (IOException e) {
|
|
||||||
if (LOG.isLoggable(INFO))
|
|
||||||
LOG.info("Failed to bind " + scrubSocketAddress(addr));
|
|
||||||
tryToClose(ss);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (ss == null || !ss.isBound()) {
|
|
||||||
LOG.info("Could not bind server socket");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!running) {
|
|
||||||
tryToClose(ss);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
socket = ss;
|
|
||||||
backoff.reset();
|
|
||||||
InetSocketAddress local =
|
|
||||||
(InetSocketAddress) ss.getLocalSocketAddress();
|
|
||||||
setLocalSocketAddress(local);
|
|
||||||
if (LOG.isLoggable(INFO))
|
|
||||||
LOG.info("Listening on " + scrubSocketAddress(local));
|
|
||||||
callback.transportEnabled();
|
|
||||||
acceptContactConnections();
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
protected void tryToClose(@Nullable ServerSocket ss) {
|
private void bind(boolean ipv4) {
|
||||||
IoUtils.tryToClose(ss, LOG, WARNING);
|
ServerSocket old = state.getServerSocket(ipv4);
|
||||||
callback.transportDisabled();
|
ServerSocket ss = null;
|
||||||
|
for (InetSocketAddress addr : getLocalSocketAddresses(ipv4)) {
|
||||||
|
if (old != null && addr.equals(old.getLocalSocketAddress())) {
|
||||||
|
LOG.info("Server socket already bound");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
ss = new ServerSocket();
|
||||||
|
ss.bind(addr);
|
||||||
|
break;
|
||||||
|
} catch (IOException e) {
|
||||||
|
if (LOG.isLoggable(INFO))
|
||||||
|
LOG.info("Failed to bind " + scrubSocketAddress(addr));
|
||||||
|
tryToClose(ss, LOG, WARNING);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ss == null || !ss.isBound()) {
|
||||||
|
LOG.info("Could not bind server socket");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!state.setServerSocket(ss, ipv4)) {
|
||||||
|
LOG.info("Closing redundant server socket");
|
||||||
|
tryToClose(ss, LOG, WARNING);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
backoff.reset();
|
||||||
|
InetSocketAddress local =
|
||||||
|
(InetSocketAddress) ss.getLocalSocketAddress();
|
||||||
|
setLocalSocketAddress(local, ipv4);
|
||||||
|
if (LOG.isLoggable(INFO))
|
||||||
|
LOG.info("Listening on " + scrubSocketAddress(local));
|
||||||
|
ServerSocket finalSocket = ss;
|
||||||
|
ioExecutor.execute(() -> acceptContactConnections(finalSocket, ipv4));
|
||||||
}
|
}
|
||||||
|
|
||||||
String getIpPortString(InetSocketAddress a) {
|
String getIpPortString(InetSocketAddress a) {
|
||||||
@@ -170,20 +200,22 @@ abstract class TcpPlugin implements DuplexPlugin {
|
|||||||
return addr + ":" + a.getPort();
|
return addr + ":" + a.getPort();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void acceptContactConnections() {
|
private void acceptContactConnections(ServerSocket ss, boolean ipv4) {
|
||||||
while (isRunning()) {
|
while (true) {
|
||||||
Socket s;
|
Socket s;
|
||||||
try {
|
try {
|
||||||
s = socket.accept();
|
s = ss.accept();
|
||||||
s.setSoTimeout(socketTimeout);
|
s.setSoTimeout(socketTimeout);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
// This is expected when the socket is closed
|
// This is expected when the server socket is closed
|
||||||
if (LOG.isLoggable(INFO)) LOG.info(e.toString());
|
LOG.info("Server socket closed");
|
||||||
|
state.clearServerSocket(ss, ipv4);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (LOG.isLoggable(INFO))
|
if (LOG.isLoggable(INFO)) {
|
||||||
LOG.info("Connection from " +
|
LOG.info("Connection from " +
|
||||||
scrubSocketAddress(s.getRemoteSocketAddress()));
|
scrubSocketAddress(s.getRemoteSocketAddress()));
|
||||||
|
}
|
||||||
backoff.reset();
|
backoff.reset();
|
||||||
callback.handleConnection(new TcpTransportConnection(this, s));
|
callback.handleConnection(new TcpTransportConnection(this, s));
|
||||||
}
|
}
|
||||||
@@ -191,13 +223,17 @@ abstract class TcpPlugin implements DuplexPlugin {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void stop() {
|
public void stop() {
|
||||||
running = false;
|
for (ServerSocket ss : state.setStopped()) tryToClose(ss, LOG, WARNING);
|
||||||
tryToClose(socket);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isRunning() {
|
public State getState() {
|
||||||
return running && socket != null && !socket.isClosed();
|
return state.getState();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getReasonsDisabled() {
|
||||||
|
return state.getReasonsDisabled();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -213,7 +249,7 @@ abstract class TcpPlugin implements DuplexPlugin {
|
|||||||
@Override
|
@Override
|
||||||
public void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
public void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
||||||
properties) {
|
properties) {
|
||||||
if (!isRunning()) return;
|
if (getState() != ACTIVE) return;
|
||||||
backoff.increment();
|
backoff.increment();
|
||||||
for (Pair<TransportProperties, ConnectionHandler> p : properties) {
|
for (Pair<TransportProperties, ConnectionHandler> p : properties) {
|
||||||
connect(p.getFirst(), p.getSecond());
|
connect(p.getFirst(), p.getSecond());
|
||||||
@@ -221,7 +257,7 @@ abstract class TcpPlugin implements DuplexPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void connect(TransportProperties p, ConnectionHandler h) {
|
private void connect(TransportProperties p, ConnectionHandler h) {
|
||||||
ioExecutor.execute(() -> {
|
wakefulIoExecutor.execute(() -> {
|
||||||
DuplexTransportConnection d = createConnection(p);
|
DuplexTransportConnection d = createConnection(p);
|
||||||
if (d != null) {
|
if (d != null) {
|
||||||
backoff.reset();
|
backoff.reset();
|
||||||
@@ -232,14 +268,22 @@ abstract class TcpPlugin implements DuplexPlugin {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DuplexTransportConnection createConnection(TransportProperties p) {
|
public DuplexTransportConnection createConnection(TransportProperties p) {
|
||||||
if (!isRunning()) return null;
|
DuplexTransportConnection c = createConnection(p, true);
|
||||||
ServerSocket ss = socket;
|
if (c != null) return c;
|
||||||
|
return createConnection(p, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
private DuplexTransportConnection createConnection(TransportProperties p,
|
||||||
|
boolean ipv4) {
|
||||||
|
ServerSocket ss = state.getServerSocket(ipv4);
|
||||||
|
if (ss == null) return null;
|
||||||
InterfaceAddress local = getLocalInterfaceAddress(ss.getInetAddress());
|
InterfaceAddress local = getLocalInterfaceAddress(ss.getInetAddress());
|
||||||
if (local == null) {
|
if (local == null) {
|
||||||
LOG.warning("No interface for server socket");
|
LOG.warning("No interface for server socket");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
for (InetSocketAddress remote : getRemoteSocketAddresses(p)) {
|
for (InetSocketAddress remote : getRemoteSocketAddresses(p, ipv4)) {
|
||||||
// Don't try to connect to our own address
|
// Don't try to connect to our own address
|
||||||
if (!canConnectToOwnAddress() &&
|
if (!canConnectToOwnAddress() &&
|
||||||
remote.getAddress().equals(ss.getInetAddress())) {
|
remote.getAddress().equals(ss.getInetAddress())) {
|
||||||
@@ -264,9 +308,10 @@ abstract class TcpPlugin implements DuplexPlugin {
|
|||||||
LOG.info("Connected to " + scrubSocketAddress(remote));
|
LOG.info("Connected to " + scrubSocketAddress(remote));
|
||||||
return new TcpTransportConnection(this, s);
|
return new TcpTransportConnection(this, s);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
if (LOG.isLoggable(INFO))
|
if (LOG.isLoggable(INFO)) {
|
||||||
LOG.info("Could not connect to " +
|
LOG.info("Could not connect to " +
|
||||||
scrubSocketAddress(remote));
|
scrubSocketAddress(remote));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
@@ -289,8 +334,12 @@ abstract class TcpPlugin implements DuplexPlugin {
|
|||||||
return new Socket();
|
return new Socket();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int chooseEphemeralPort() {
|
||||||
|
return 32768 + (int) (Math.random() * 32768);
|
||||||
|
}
|
||||||
|
|
||||||
@Nullable
|
@Nullable
|
||||||
InetSocketAddress parseSocketAddress(String ipPort) {
|
InetSocketAddress parseIpv4SocketAddress(String ipPort) {
|
||||||
if (isNullOrEmpty(ipPort)) return null;
|
if (isNullOrEmpty(ipPort)) return null;
|
||||||
String[] split = ipPort.split(":");
|
String[] split = ipPort.split(":");
|
||||||
if (split.length != 2) return null;
|
if (split.length != 2) return null;
|
||||||
@@ -301,14 +350,7 @@ abstract class TcpPlugin implements DuplexPlugin {
|
|||||||
InetAddress a = InetAddress.getByName(addr);
|
InetAddress a = InetAddress.getByName(addr);
|
||||||
int p = Integer.parseInt(port);
|
int p = Integer.parseInt(port);
|
||||||
return new InetSocketAddress(a, p);
|
return new InetSocketAddress(a, p);
|
||||||
} catch (UnknownHostException e) {
|
} catch (UnknownHostException | NumberFormatException e) {
|
||||||
if (LOG.isLoggable(WARNING))
|
|
||||||
// not scrubbing to enable us to find the problem
|
|
||||||
LOG.warning("Invalid address: " + addr);
|
|
||||||
return null;
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
if (LOG.isLoggable(WARNING))
|
|
||||||
LOG.warning("Invalid port: " + port);
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -366,4 +408,114 @@ abstract class TcpPlugin implements DuplexPlugin {
|
|||||||
return emptyList();
|
return emptyList();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void eventOccurred(Event e) {
|
||||||
|
if (e instanceof SettingsUpdatedEvent) {
|
||||||
|
SettingsUpdatedEvent s = (SettingsUpdatedEvent) e;
|
||||||
|
if (s.getNamespace().equals(getId().getString()))
|
||||||
|
ioExecutor.execute(() -> onSettingsUpdated(s.getSettings()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@IoExecutor
|
||||||
|
private void onSettingsUpdated(Settings settings) {
|
||||||
|
boolean enabledByUser =
|
||||||
|
settings.getBoolean(PREF_PLUGIN_ENABLE, isEnabledByDefault());
|
||||||
|
List<ServerSocket> toClose = state.setEnabledByUser(enabledByUser);
|
||||||
|
State s = getState();
|
||||||
|
if (!toClose.isEmpty()) {
|
||||||
|
LOG.info("Disabled by user, closing server sockets");
|
||||||
|
for (ServerSocket ss : toClose) tryToClose(ss, LOG, WARNING);
|
||||||
|
} else if (s == INACTIVE) {
|
||||||
|
LOG.info("Enabled by user, opening server sockets");
|
||||||
|
bind();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@ThreadSafe
|
||||||
|
@NotNullByDefault
|
||||||
|
protected class PluginState {
|
||||||
|
|
||||||
|
@GuardedBy("this")
|
||||||
|
private boolean started = false, stopped = false, enabledByUser = false;
|
||||||
|
|
||||||
|
@GuardedBy("this")
|
||||||
|
@Nullable
|
||||||
|
private ServerSocket serverSocketV4 = null, serverSocketV6 = null;
|
||||||
|
|
||||||
|
synchronized void setStarted(boolean enabledByUser) {
|
||||||
|
started = true;
|
||||||
|
this.enabledByUser = enabledByUser;
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized List<ServerSocket> setStopped() {
|
||||||
|
stopped = true;
|
||||||
|
List<ServerSocket> toClose = clearServerSockets();
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
return toClose;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GuardedBy("this")
|
||||||
|
private List<ServerSocket> clearServerSockets() {
|
||||||
|
List<ServerSocket> toClose = new ArrayList<>(2);
|
||||||
|
if (serverSocketV4 != null) {
|
||||||
|
toClose.add(serverSocketV4);
|
||||||
|
serverSocketV4 = null;
|
||||||
|
}
|
||||||
|
if (serverSocketV6 != null) {
|
||||||
|
toClose.add(serverSocketV6);
|
||||||
|
serverSocketV6 = null;
|
||||||
|
}
|
||||||
|
return toClose;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized List<ServerSocket> setEnabledByUser(
|
||||||
|
boolean enabledByUser) {
|
||||||
|
this.enabledByUser = enabledByUser;
|
||||||
|
List<ServerSocket> toClose = enabledByUser
|
||||||
|
? emptyList() : clearServerSockets();
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
return toClose;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
synchronized ServerSocket getServerSocket(boolean ipv4) {
|
||||||
|
return ipv4 ? serverSocketV4 : serverSocketV6;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized boolean setServerSocket(ServerSocket ss, boolean ipv4) {
|
||||||
|
if (stopped) return false;
|
||||||
|
if (ipv4) {
|
||||||
|
if (serverSocketV4 != null) return false;
|
||||||
|
serverSocketV4 = ss;
|
||||||
|
} else {
|
||||||
|
if (serverSocketV6 != null) return false;
|
||||||
|
serverSocketV6 = ss;
|
||||||
|
}
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized void clearServerSocket(ServerSocket ss, boolean ipv4) {
|
||||||
|
if (ipv4) {
|
||||||
|
if (serverSocketV4 == ss) serverSocketV4 = null;
|
||||||
|
} else {
|
||||||
|
if (serverSocketV6 == ss) serverSocketV6 = null;
|
||||||
|
}
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized State getState() {
|
||||||
|
if (!started || stopped) return STARTING_STOPPING;
|
||||||
|
if (!enabledByUser) return DISABLED;
|
||||||
|
if (serverSocketV4 != null || serverSocketV6 != null) return ACTIVE;
|
||||||
|
return INACTIVE;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized int getReasonsDisabled() {
|
||||||
|
return getState() == DISABLED ? REASON_USER : 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import java.util.concurrent.Executor;
|
|||||||
|
|
||||||
import static java.util.Collections.emptyList;
|
import static java.util.Collections.emptyList;
|
||||||
import static java.util.Collections.singletonList;
|
import static java.util.Collections.singletonList;
|
||||||
|
import static org.briarproject.bramble.api.plugin.WanTcpConstants.DEFAULT_PREF_PLUGIN_ENABLE;
|
||||||
import static org.briarproject.bramble.api.plugin.WanTcpConstants.ID;
|
import static org.briarproject.bramble.api.plugin.WanTcpConstants.ID;
|
||||||
|
|
||||||
@MethodsNotNullByDefault
|
@MethodsNotNullByDefault
|
||||||
@@ -29,11 +30,16 @@ class WanTcpPlugin extends TcpPlugin {
|
|||||||
|
|
||||||
private volatile MappingResult mappingResult;
|
private volatile MappingResult mappingResult;
|
||||||
|
|
||||||
WanTcpPlugin(Executor ioExecutor, Backoff backoff, PortMapper portMapper,
|
WanTcpPlugin(Executor ioExecutor,
|
||||||
PluginCallback callback, int maxLatency, int maxIdleTime,
|
Executor wakefulIoExecutor,
|
||||||
|
Backoff backoff,
|
||||||
|
PortMapper portMapper,
|
||||||
|
PluginCallback callback,
|
||||||
|
int maxLatency,
|
||||||
|
int maxIdleTime,
|
||||||
int connectionTimeout) {
|
int connectionTimeout) {
|
||||||
super(ioExecutor, backoff, callback, maxLatency, maxIdleTime,
|
super(ioExecutor, wakefulIoExecutor, backoff, callback, maxLatency,
|
||||||
connectionTimeout);
|
maxIdleTime, connectionTimeout);
|
||||||
this.portMapper = portMapper;
|
this.portMapper = portMapper;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,10 +49,16 @@ class WanTcpPlugin extends TcpPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected List<InetSocketAddress> getLocalSocketAddresses() {
|
protected boolean isEnabledByDefault() {
|
||||||
|
return DEFAULT_PREF_PLUGIN_ENABLE;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected List<InetSocketAddress> getLocalSocketAddresses(boolean ipv4) {
|
||||||
|
if (!ipv4) return emptyList();
|
||||||
// Use the same address and port as last time if available
|
// Use the same address and port as last time if available
|
||||||
TransportProperties p = callback.getLocalProperties();
|
TransportProperties p = callback.getLocalProperties();
|
||||||
InetSocketAddress old = parseSocketAddress(p.get(PROP_IP_PORT));
|
InetSocketAddress old = parseIpv4SocketAddress(p.get(PROP_IP_PORT));
|
||||||
List<InetSocketAddress> addrs = new LinkedList<>();
|
List<InetSocketAddress> addrs = new LinkedList<>();
|
||||||
for (InetAddress a : getLocalInetAddresses()) {
|
for (InetAddress a : getLocalInetAddresses()) {
|
||||||
if (isAcceptableAddress(a)) {
|
if (isAcceptableAddress(a)) {
|
||||||
@@ -76,14 +88,11 @@ class WanTcpPlugin extends TcpPlugin {
|
|||||||
return ipv4 && !loop && !link && !site;
|
return ipv4 && !loop && !link && !site;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int chooseEphemeralPort() {
|
|
||||||
return 32768 + (int) (Math.random() * 32768);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected List<InetSocketAddress> getRemoteSocketAddresses(
|
protected List<InetSocketAddress> getRemoteSocketAddresses(
|
||||||
TransportProperties p) {
|
TransportProperties p, boolean ipv4) {
|
||||||
InetSocketAddress parsed = parseSocketAddress(p.get(PROP_IP_PORT));
|
if (!ipv4) return emptyList();
|
||||||
|
InetSocketAddress parsed = parseIpv4SocketAddress(p.get(PROP_IP_PORT));
|
||||||
if (parsed == null) return emptyList();
|
if (parsed == null) return emptyList();
|
||||||
return singletonList(parsed);
|
return singletonList(parsed);
|
||||||
}
|
}
|
||||||
@@ -96,7 +105,8 @@ class WanTcpPlugin extends TcpPlugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void setLocalSocketAddress(InetSocketAddress a) {
|
protected void setLocalSocketAddress(InetSocketAddress a, boolean ipv4) {
|
||||||
|
if (!ipv4) throw new AssertionError();
|
||||||
if (mappingResult != null && mappingResult.isUsable()) {
|
if (mappingResult != null && mappingResult.isUsable()) {
|
||||||
// Advertise the external address to contacts
|
// Advertise the external address to contacts
|
||||||
if (a.equals(mappingResult.getInternal())) {
|
if (a.equals(mappingResult.getInternal())) {
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package org.briarproject.bramble.plugin.tcp;
|
package org.briarproject.bramble.plugin.tcp;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.event.EventBus;
|
||||||
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
import org.briarproject.bramble.api.lifecycle.ShutdownManager;
|
import org.briarproject.bramble.api.lifecycle.ShutdownManager;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
@@ -8,10 +10,12 @@ import org.briarproject.bramble.api.plugin.PluginCallback;
|
|||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||||
|
import org.briarproject.bramble.api.system.WakefulIoExecutor;
|
||||||
|
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
import javax.annotation.concurrent.Immutable;
|
import javax.annotation.concurrent.Immutable;
|
||||||
|
import javax.inject.Inject;
|
||||||
|
|
||||||
import static org.briarproject.bramble.api.plugin.WanTcpConstants.ID;
|
import static org.briarproject.bramble.api.plugin.WanTcpConstants.ID;
|
||||||
|
|
||||||
@@ -26,13 +30,20 @@ public class WanTcpPluginFactory implements DuplexPluginFactory {
|
|||||||
private static final int MAX_POLLING_INTERVAL = 600_000; // 10 mins
|
private static final int MAX_POLLING_INTERVAL = 600_000; // 10 mins
|
||||||
private static final double BACKOFF_BASE = 1.2;
|
private static final double BACKOFF_BASE = 1.2;
|
||||||
|
|
||||||
private final Executor ioExecutor;
|
private final Executor ioExecutor, wakefulIoExecutor;
|
||||||
|
private final EventBus eventBus;
|
||||||
private final BackoffFactory backoffFactory;
|
private final BackoffFactory backoffFactory;
|
||||||
private final ShutdownManager shutdownManager;
|
private final ShutdownManager shutdownManager;
|
||||||
|
|
||||||
public WanTcpPluginFactory(Executor ioExecutor,
|
@Inject
|
||||||
BackoffFactory backoffFactory, ShutdownManager shutdownManager) {
|
public WanTcpPluginFactory(@IoExecutor Executor ioExecutor,
|
||||||
|
@WakefulIoExecutor Executor wakefulIoExecutor,
|
||||||
|
EventBus eventBus,
|
||||||
|
BackoffFactory backoffFactory,
|
||||||
|
ShutdownManager shutdownManager) {
|
||||||
this.ioExecutor = ioExecutor;
|
this.ioExecutor = ioExecutor;
|
||||||
|
this.wakefulIoExecutor = wakefulIoExecutor;
|
||||||
|
this.eventBus = eventBus;
|
||||||
this.backoffFactory = backoffFactory;
|
this.backoffFactory = backoffFactory;
|
||||||
this.shutdownManager = shutdownManager;
|
this.shutdownManager = shutdownManager;
|
||||||
}
|
}
|
||||||
@@ -51,8 +62,11 @@ public class WanTcpPluginFactory implements DuplexPluginFactory {
|
|||||||
public DuplexPlugin createPlugin(PluginCallback callback) {
|
public DuplexPlugin createPlugin(PluginCallback callback) {
|
||||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||||
return new WanTcpPlugin(ioExecutor, backoff,
|
PortMapper portMapper = new PortMapperImpl(shutdownManager);
|
||||||
new PortMapperImpl(shutdownManager), callback, MAX_LATENCY,
|
WanTcpPlugin plugin = new WanTcpPlugin(ioExecutor, wakefulIoExecutor,
|
||||||
MAX_IDLE_TIME, CONNECTION_TIMEOUT);
|
backoff, portMapper, callback, MAX_LATENCY, MAX_IDLE_TIME,
|
||||||
|
CONNECTION_TIMEOUT);
|
||||||
|
eventBus.addListener(plugin);
|
||||||
|
return plugin;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ public interface CircumventionProvider {
|
|||||||
String[] BLOCKED = {"CN", "IR", "EG", "BY", "TR", "SY", "VE"};
|
String[] BLOCKED = {"CN", "IR", "EG", "BY", "TR", "SY", "VE"};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Countries where obfs4 bridge connection are likely to work.
|
* Countries where obfs4 or meek bridge connections are likely to work.
|
||||||
* Should be a subset of {@link #BLOCKED}.
|
* Should be a subset of {@link #BLOCKED}.
|
||||||
*/
|
*/
|
||||||
String[] BRIDGES = { "CN", "IR", "EG", "BY", "TR", "SY", "VE" };
|
String[] BRIDGES = { "CN", "IR", "EG", "BY", "TR", "SY", "VE" };
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import org.briarproject.bramble.api.network.NetworkManager;
|
|||||||
import org.briarproject.bramble.api.network.NetworkStatus;
|
import org.briarproject.bramble.api.network.NetworkStatus;
|
||||||
import org.briarproject.bramble.api.network.event.NetworkStatusEvent;
|
import org.briarproject.bramble.api.network.event.NetworkStatusEvent;
|
||||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
import org.briarproject.bramble.api.plugin.ConnectionHandler;
|
import org.briarproject.bramble.api.plugin.ConnectionHandler;
|
||||||
@@ -54,6 +55,9 @@ import java.util.logging.Logger;
|
|||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
import java.util.zip.ZipInputStream;
|
import java.util.zip.ZipInputStream;
|
||||||
|
|
||||||
|
import javax.annotation.Nullable;
|
||||||
|
import javax.annotation.concurrent.GuardedBy;
|
||||||
|
import javax.annotation.concurrent.ThreadSafe;
|
||||||
import javax.net.SocketFactory;
|
import javax.net.SocketFactory;
|
||||||
|
|
||||||
import static java.util.Arrays.asList;
|
import static java.util.Arrays.asList;
|
||||||
@@ -65,7 +69,19 @@ import static java.util.logging.Logger.getLogger;
|
|||||||
import static net.freehaven.tor.control.TorControlCommands.HS_ADDRESS;
|
import static net.freehaven.tor.control.TorControlCommands.HS_ADDRESS;
|
||||||
import static net.freehaven.tor.control.TorControlCommands.HS_PRIVKEY;
|
import static net.freehaven.tor.control.TorControlCommands.HS_PRIVKEY;
|
||||||
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.ACTIVE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.DISABLED;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.ENABLING;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.INACTIVE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.State.STARTING_STOPPING;
|
||||||
import static org.briarproject.bramble.api.plugin.TorConstants.CONTROL_PORT;
|
import static org.briarproject.bramble.api.plugin.TorConstants.CONTROL_PORT;
|
||||||
|
import static org.briarproject.bramble.api.plugin.TorConstants.DEFAULT_PREF_PLUGIN_ENABLE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.TorConstants.DEFAULT_PREF_TOR_MOBILE;
|
||||||
|
import static org.briarproject.bramble.api.plugin.TorConstants.DEFAULT_PREF_TOR_NETWORK;
|
||||||
|
import static org.briarproject.bramble.api.plugin.TorConstants.DEFAULT_PREF_TOR_ONLY_WHEN_CHARGING;
|
||||||
|
import static org.briarproject.bramble.api.plugin.TorConstants.HS_PRIVATE_KEY_V2;
|
||||||
|
import static org.briarproject.bramble.api.plugin.TorConstants.HS_PRIVATE_KEY_V3;
|
||||||
|
import static org.briarproject.bramble.api.plugin.TorConstants.HS_V3_CREATED;
|
||||||
import static org.briarproject.bramble.api.plugin.TorConstants.ID;
|
import static org.briarproject.bramble.api.plugin.TorConstants.ID;
|
||||||
import static org.briarproject.bramble.api.plugin.TorConstants.PREF_TOR_MOBILE;
|
import static org.briarproject.bramble.api.plugin.TorConstants.PREF_TOR_MOBILE;
|
||||||
import static org.briarproject.bramble.api.plugin.TorConstants.PREF_TOR_NETWORK;
|
import static org.briarproject.bramble.api.plugin.TorConstants.PREF_TOR_NETWORK;
|
||||||
@@ -76,6 +92,10 @@ import static org.briarproject.bramble.api.plugin.TorConstants.PREF_TOR_ONLY_WHE
|
|||||||
import static org.briarproject.bramble.api.plugin.TorConstants.PREF_TOR_PORT;
|
import static org.briarproject.bramble.api.plugin.TorConstants.PREF_TOR_PORT;
|
||||||
import static org.briarproject.bramble.api.plugin.TorConstants.PROP_ONION_V2;
|
import static org.briarproject.bramble.api.plugin.TorConstants.PROP_ONION_V2;
|
||||||
import static org.briarproject.bramble.api.plugin.TorConstants.PROP_ONION_V3;
|
import static org.briarproject.bramble.api.plugin.TorConstants.PROP_ONION_V3;
|
||||||
|
import static org.briarproject.bramble.api.plugin.TorConstants.REASON_BATTERY;
|
||||||
|
import static org.briarproject.bramble.api.plugin.TorConstants.REASON_COUNTRY_BLOCKED;
|
||||||
|
import static org.briarproject.bramble.api.plugin.TorConstants.REASON_MOBILE_DATA;
|
||||||
|
import static org.briarproject.bramble.api.plugin.TorConstants.V3_MIGRATION_PERIOD_MS;
|
||||||
import static org.briarproject.bramble.plugin.tor.TorRendezvousCrypto.SEED_BYTES;
|
import static org.briarproject.bramble.plugin.tor.TorRendezvousCrypto.SEED_BYTES;
|
||||||
import static org.briarproject.bramble.util.IoUtils.copyAndClose;
|
import static org.briarproject.bramble.util.IoUtils.copyAndClose;
|
||||||
import static org.briarproject.bramble.util.IoUtils.tryToClose;
|
import static org.briarproject.bramble.util.IoUtils.tryToClose;
|
||||||
@@ -98,7 +118,8 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
private static final Pattern ONION_V2 = Pattern.compile("[a-z2-7]{16}");
|
private static final Pattern ONION_V2 = Pattern.compile("[a-z2-7]{16}");
|
||||||
private static final Pattern ONION_V3 = Pattern.compile("[a-z2-7]{56}");
|
private static final Pattern ONION_V3 = Pattern.compile("[a-z2-7]{56}");
|
||||||
|
|
||||||
private final Executor ioExecutor, connectionStatusExecutor;
|
private final Executor ioExecutor, wakefulIoExecutor;
|
||||||
|
private final Executor connectionStatusExecutor;
|
||||||
private final NetworkManager networkManager;
|
private final NetworkManager networkManager;
|
||||||
private final LocationUtils locationUtils;
|
private final LocationUtils locationUtils;
|
||||||
private final SocketFactory torSocketFactory;
|
private final SocketFactory torSocketFactory;
|
||||||
@@ -113,29 +134,36 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
private final int maxLatency, maxIdleTime, socketTimeout;
|
private final int maxLatency, maxIdleTime, socketTimeout;
|
||||||
private final File torDirectory, torFile, geoIpFile, obfs4File, configFile;
|
private final File torDirectory, torFile, geoIpFile, obfs4File, configFile;
|
||||||
private final File doneFile, cookieFile;
|
private final File doneFile, cookieFile;
|
||||||
private final ConnectionStatus connectionStatus;
|
|
||||||
private final AtomicBoolean used = new AtomicBoolean(false);
|
private final AtomicBoolean used = new AtomicBoolean(false);
|
||||||
|
|
||||||
private volatile ServerSocket socket = null;
|
protected final PluginState state = new PluginState();
|
||||||
|
|
||||||
private volatile Socket controlSocket = null;
|
private volatile Socket controlSocket = null;
|
||||||
private volatile TorControlConnection controlConnection = null;
|
private volatile TorControlConnection controlConnection = null;
|
||||||
private volatile Settings settings = null;
|
private volatile Settings settings = null;
|
||||||
|
|
||||||
protected volatile boolean running = false;
|
|
||||||
|
|
||||||
protected abstract int getProcessId();
|
protected abstract int getProcessId();
|
||||||
|
|
||||||
protected abstract long getLastUpdateTime();
|
protected abstract long getLastUpdateTime();
|
||||||
|
|
||||||
TorPlugin(Executor ioExecutor, NetworkManager networkManager,
|
TorPlugin(Executor ioExecutor,
|
||||||
LocationUtils locationUtils, SocketFactory torSocketFactory,
|
Executor wakefulIoExecutor,
|
||||||
Clock clock, ResourceProvider resourceProvider,
|
NetworkManager networkManager,
|
||||||
|
LocationUtils locationUtils,
|
||||||
|
SocketFactory torSocketFactory,
|
||||||
|
Clock clock,
|
||||||
|
ResourceProvider resourceProvider,
|
||||||
CircumventionProvider circumventionProvider,
|
CircumventionProvider circumventionProvider,
|
||||||
BatteryManager batteryManager, Backoff backoff,
|
BatteryManager batteryManager,
|
||||||
|
Backoff backoff,
|
||||||
TorRendezvousCrypto torRendezvousCrypto,
|
TorRendezvousCrypto torRendezvousCrypto,
|
||||||
PluginCallback callback, String architecture, int maxLatency,
|
PluginCallback callback,
|
||||||
int maxIdleTime, File torDirectory) {
|
String architecture,
|
||||||
|
int maxLatency,
|
||||||
|
int maxIdleTime,
|
||||||
|
File torDirectory) {
|
||||||
this.ioExecutor = ioExecutor;
|
this.ioExecutor = ioExecutor;
|
||||||
|
this.wakefulIoExecutor = wakefulIoExecutor;
|
||||||
this.networkManager = networkManager;
|
this.networkManager = networkManager;
|
||||||
this.locationUtils = locationUtils;
|
this.locationUtils = locationUtils;
|
||||||
this.torSocketFactory = torSocketFactory;
|
this.torSocketFactory = torSocketFactory;
|
||||||
@@ -159,7 +187,6 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
configFile = new File(torDirectory, "torrc");
|
configFile = new File(torDirectory, "torrc");
|
||||||
doneFile = new File(torDirectory, "done");
|
doneFile = new File(torDirectory, "done");
|
||||||
cookieFile = new File(torDirectory, ".tor/control_auth_cookie");
|
cookieFile = new File(torDirectory, ".tor/control_auth_cookie");
|
||||||
connectionStatus = new ConnectionStatus();
|
|
||||||
// Don't execute more than one connection status check at a time
|
// Don't execute more than one connection status check at a time
|
||||||
connectionStatusExecutor =
|
connectionStatusExecutor =
|
||||||
new PoliteExecutor("TorPlugin", ioExecutor, 1);
|
new PoliteExecutor("TorPlugin", ioExecutor, 1);
|
||||||
@@ -190,7 +217,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Load the settings
|
// Load the settings
|
||||||
settings = callback.getSettings();
|
settings = migrateSettings(callback.getSettings());
|
||||||
// Install or update the assets if necessary
|
// Install or update the assets if necessary
|
||||||
if (!assetsAreUpToDate()) installAssets();
|
if (!assetsAreUpToDate()) installAssets();
|
||||||
if (cookieFile.exists() && !cookieFile.delete())
|
if (cookieFile.exists() && !cookieFile.delete())
|
||||||
@@ -258,7 +285,6 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
// Tell Tor to exit when the control connection is closed
|
// Tell Tor to exit when the control connection is closed
|
||||||
controlConnection.takeOwnership();
|
controlConnection.takeOwnership();
|
||||||
controlConnection.resetConf(singletonList(OWNER));
|
controlConnection.resetConf(singletonList(OWNER));
|
||||||
running = true;
|
|
||||||
// Register to receive events from the Tor process
|
// Register to receive events from the Tor process
|
||||||
controlConnection.setEventHandler(this);
|
controlConnection.setEventHandler(this);
|
||||||
controlConnection.setEvents(asList(EVENTS));
|
controlConnection.setEvents(asList(EVENTS));
|
||||||
@@ -266,11 +292,12 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
String phase = controlConnection.getInfo("status/bootstrap-phase");
|
String phase = controlConnection.getInfo("status/bootstrap-phase");
|
||||||
if (phase != null && phase.contains("PROGRESS=100")) {
|
if (phase != null && phase.contains("PROGRESS=100")) {
|
||||||
LOG.info("Tor has already bootstrapped");
|
LOG.info("Tor has already bootstrapped");
|
||||||
connectionStatus.setBootstrapped();
|
state.setBootstrapped();
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new PluginException(e);
|
throw new PluginException(e);
|
||||||
}
|
}
|
||||||
|
state.setStarted();
|
||||||
// Check whether we're online
|
// Check whether we're online
|
||||||
updateConnectionStatus(networkManager.getNetworkStatus(),
|
updateConnectionStatus(networkManager.getNetworkStatus(),
|
||||||
batteryManager.isCharging());
|
batteryManager.isCharging());
|
||||||
@@ -278,6 +305,18 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
bind();
|
bind();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: Remove after a reasonable migration period (added 2020-06-25)
|
||||||
|
private Settings migrateSettings(Settings settings) {
|
||||||
|
int network = settings.getInt(PREF_TOR_NETWORK,
|
||||||
|
DEFAULT_PREF_TOR_NETWORK);
|
||||||
|
if (network == PREF_TOR_NETWORK_NEVER) {
|
||||||
|
settings.putInt(PREF_TOR_NETWORK, DEFAULT_PREF_TOR_NETWORK);
|
||||||
|
settings.putBoolean(PREF_PLUGIN_ENABLE, false);
|
||||||
|
callback.mergeSettings(settings);
|
||||||
|
}
|
||||||
|
return settings;
|
||||||
|
}
|
||||||
|
|
||||||
private boolean assetsAreUpToDate() {
|
private boolean assetsAreUpToDate() {
|
||||||
return doneFile.lastModified() > getLastUpdateTime();
|
return doneFile.lastModified() > getLastUpdateTime();
|
||||||
}
|
}
|
||||||
@@ -393,11 +432,11 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
tryToClose(ss, LOG, WARNING);
|
tryToClose(ss, LOG, WARNING);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!running) {
|
if (!state.setServerSocket(ss)) {
|
||||||
|
LOG.info("Closing redundant server socket");
|
||||||
tryToClose(ss, LOG, WARNING);
|
tryToClose(ss, LOG, WARNING);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
socket = ss;
|
|
||||||
// Store the port number
|
// Store the port number
|
||||||
String localPort = String.valueOf(ss.getLocalPort());
|
String localPort = String.valueOf(ss.getLocalPort());
|
||||||
Settings s = new Settings();
|
Settings s = new Settings();
|
||||||
@@ -412,16 +451,67 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void publishHiddenService(String port) {
|
private void publishHiddenService(String port) {
|
||||||
if (!running) return;
|
if (!state.isTorRunning()) return;
|
||||||
LOG.info("Creating hidden service");
|
// TODO: Remove support for v2 hidden services after a reasonable
|
||||||
String privKey = settings.get(HS_PRIVKEY);
|
// migration period (migration started 2020-06-30)
|
||||||
|
String privKey2 = settings.get(HS_PRIVATE_KEY_V2);
|
||||||
|
String privKey3 = settings.get(HS_PRIVATE_KEY_V3);
|
||||||
|
String v3Created = settings.get(HS_V3_CREATED);
|
||||||
|
// Publish a v2 hidden service if we've already created one, and
|
||||||
|
// either we've never published a v3 hidden service or we're still
|
||||||
|
// in the migration period since first publishing it
|
||||||
|
if (!isNullOrEmpty(privKey2)) {
|
||||||
|
long now = clock.currentTimeMillis();
|
||||||
|
long then = v3Created == null ? now : Long.parseLong(v3Created);
|
||||||
|
if (now - then >= V3_MIGRATION_PERIOD_MS) retireV2HiddenService();
|
||||||
|
else publishV2HiddenService(port, privKey2);
|
||||||
|
}
|
||||||
|
publishV3HiddenService(port, privKey3);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void publishV2HiddenService(String port, String privKey) {
|
||||||
|
LOG.info("Creating v2 hidden service");
|
||||||
|
Map<Integer, String> portLines = singletonMap(80, "127.0.0.1:" + port);
|
||||||
|
Map<String, String> response;
|
||||||
|
try {
|
||||||
|
response = controlConnection.addOnion(privKey, portLines);
|
||||||
|
} catch (IOException e) {
|
||||||
|
logException(LOG, WARNING, e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!response.containsKey(HS_ADDRESS)) {
|
||||||
|
LOG.warning("Tor did not return a hidden service address");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
String onion2 = response.get(HS_ADDRESS);
|
||||||
|
if (LOG.isLoggable(INFO)) {
|
||||||
|
LOG.info("V2 hidden service " + scrubOnion(onion2));
|
||||||
|
}
|
||||||
|
// The hostname has already been published and the private key stored
|
||||||
|
}
|
||||||
|
|
||||||
|
private void retireV2HiddenService() {
|
||||||
|
LOG.info("Retiring v2 hidden service");
|
||||||
|
TransportProperties p = new TransportProperties();
|
||||||
|
p.put(PROP_ONION_V2, "");
|
||||||
|
callback.mergeLocalProperties(p);
|
||||||
|
Settings s = new Settings();
|
||||||
|
s.put(HS_PRIVATE_KEY_V2, "");
|
||||||
|
callback.mergeSettings(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void publishV3HiddenService(String port, @Nullable String privKey) {
|
||||||
|
LOG.info("Creating v3 hidden service");
|
||||||
Map<Integer, String> portLines = singletonMap(80, "127.0.0.1:" + port);
|
Map<Integer, String> portLines = singletonMap(80, "127.0.0.1:" + port);
|
||||||
Map<String, String> response;
|
Map<String, String> response;
|
||||||
try {
|
try {
|
||||||
// Use the control connection to set up the hidden service
|
// Use the control connection to set up the hidden service
|
||||||
if (privKey == null)
|
if (privKey == null) {
|
||||||
response = controlConnection.addOnion(portLines);
|
response = controlConnection.addOnion("NEW:ED25519-V3",
|
||||||
else response = controlConnection.addOnion(privKey, portLines);
|
portLines, null);
|
||||||
|
} else {
|
||||||
|
response = controlConnection.addOnion(privKey, portLines);
|
||||||
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logException(LOG, WARNING, e);
|
logException(LOG, WARNING, e);
|
||||||
return;
|
return;
|
||||||
@@ -434,30 +524,33 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
LOG.warning("Tor did not return a private key");
|
LOG.warning("Tor did not return a private key");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Publish the hidden service's onion hostname in transport properties
|
String onion3 = response.get(HS_ADDRESS);
|
||||||
String onion2 = response.get(HS_ADDRESS);
|
if (LOG.isLoggable(INFO)) {
|
||||||
if (LOG.isLoggable(INFO))
|
LOG.info("V3 hidden service " + scrubOnion(onion3));
|
||||||
LOG.info("Hidden service " + scrubOnion(onion2));
|
}
|
||||||
TransportProperties p = new TransportProperties();
|
|
||||||
p.put(PROP_ONION_V2, onion2);
|
|
||||||
callback.mergeLocalProperties(p);
|
|
||||||
if (privKey == null) {
|
if (privKey == null) {
|
||||||
|
// Publish the hidden service's onion hostname in transport props
|
||||||
|
TransportProperties p = new TransportProperties();
|
||||||
|
p.put(PROP_ONION_V3, onion3);
|
||||||
|
callback.mergeLocalProperties(p);
|
||||||
// Save the hidden service's private key for next time
|
// Save the hidden service's private key for next time
|
||||||
Settings s = new Settings();
|
Settings s = new Settings();
|
||||||
s.put(HS_PRIVKEY, response.get(HS_PRIVKEY));
|
s.put(HS_PRIVATE_KEY_V3, response.get(HS_PRIVKEY));
|
||||||
|
s.put(HS_V3_CREATED, String.valueOf(clock.currentTimeMillis()));
|
||||||
callback.mergeSettings(s);
|
callback.mergeSettings(s);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void acceptContactConnections(ServerSocket ss) {
|
private void acceptContactConnections(ServerSocket ss) {
|
||||||
while (running) {
|
while (true) {
|
||||||
Socket s;
|
Socket s;
|
||||||
try {
|
try {
|
||||||
s = ss.accept();
|
s = ss.accept();
|
||||||
s.setSoTimeout(socketTimeout);
|
s.setSoTimeout(socketTimeout);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
// This is expected when the socket is closed
|
// This is expected when the server socket is closed
|
||||||
if (LOG.isLoggable(INFO)) LOG.info(e.toString());
|
LOG.info("Server socket closed");
|
||||||
|
state.clearServerSocket(ss);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
LOG.info("Connection received");
|
LOG.info("Connection received");
|
||||||
@@ -467,10 +560,8 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected void enableNetwork(boolean enable) throws IOException {
|
protected void enableNetwork(boolean enable) throws IOException {
|
||||||
if (!running) return;
|
state.enableNetwork(enable);
|
||||||
connectionStatus.enableNetwork(enable);
|
|
||||||
controlConnection.setConf("DisableNetwork", enable ? "0" : "1");
|
controlConnection.setConf("DisableNetwork", enable ? "0" : "1");
|
||||||
if (!enable) callback.transportDisabled();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void enableBridges(boolean enable, boolean needsMeek)
|
private void enableBridges(boolean enable, boolean needsMeek)
|
||||||
@@ -494,9 +585,8 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void stop() {
|
public void stop() {
|
||||||
running = false;
|
ServerSocket ss = state.setStopped();
|
||||||
tryToClose(socket, LOG, WARNING);
|
tryToClose(ss, LOG, WARNING);
|
||||||
callback.transportDisabled();
|
|
||||||
if (controlSocket != null && controlConnection != null) {
|
if (controlSocket != null && controlConnection != null) {
|
||||||
try {
|
try {
|
||||||
LOG.info("Stopping Tor");
|
LOG.info("Stopping Tor");
|
||||||
@@ -510,8 +600,13 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean isRunning() {
|
public State getState() {
|
||||||
return running && connectionStatus.isConnected();
|
return state.getState();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int getReasonsDisabled() {
|
||||||
|
return state.getReasonsDisabled();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -527,7 +622,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
@Override
|
@Override
|
||||||
public void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
public void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
||||||
properties) {
|
properties) {
|
||||||
if (!isRunning()) return;
|
if (getState() != ACTIVE) return;
|
||||||
backoff.increment();
|
backoff.increment();
|
||||||
for (Pair<TransportProperties, ConnectionHandler> p : properties) {
|
for (Pair<TransportProperties, ConnectionHandler> p : properties) {
|
||||||
connect(p.getFirst(), p.getSecond());
|
connect(p.getFirst(), p.getSecond());
|
||||||
@@ -535,7 +630,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void connect(TransportProperties p, ConnectionHandler h) {
|
private void connect(TransportProperties p, ConnectionHandler h) {
|
||||||
ioExecutor.execute(() -> {
|
wakefulIoExecutor.execute(() -> {
|
||||||
DuplexTransportConnection d = createConnection(p);
|
DuplexTransportConnection d = createConnection(p);
|
||||||
if (d != null) {
|
if (d != null) {
|
||||||
backoff.reset();
|
backoff.reset();
|
||||||
@@ -546,13 +641,16 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DuplexTransportConnection createConnection(TransportProperties p) {
|
public DuplexTransportConnection createConnection(TransportProperties p) {
|
||||||
if (!isRunning()) return null;
|
if (getState() != ACTIVE) return null;
|
||||||
String bestOnion = null;
|
// TODO: Remove support for v2 hidden services after a reasonable
|
||||||
|
// migration period (migration started 2020-06-30)
|
||||||
|
String bestOnion = null, version = null;
|
||||||
String onion2 = p.get(PROP_ONION_V2);
|
String onion2 = p.get(PROP_ONION_V2);
|
||||||
String onion3 = p.get(PROP_ONION_V3);
|
String onion3 = p.get(PROP_ONION_V3);
|
||||||
if (!isNullOrEmpty(onion2)) {
|
if (!isNullOrEmpty(onion2)) {
|
||||||
if (ONION_V2.matcher(onion2).matches()) {
|
if (ONION_V2.matcher(onion2).matches()) {
|
||||||
bestOnion = onion2;
|
bestOnion = onion2;
|
||||||
|
version = "v2";
|
||||||
} else {
|
} else {
|
||||||
// Don't scrub the address so we can find the problem
|
// Don't scrub the address so we can find the problem
|
||||||
if (LOG.isLoggable(INFO))
|
if (LOG.isLoggable(INFO))
|
||||||
@@ -562,6 +660,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
if (!isNullOrEmpty(onion3)) {
|
if (!isNullOrEmpty(onion3)) {
|
||||||
if (ONION_V3.matcher(onion3).matches()) {
|
if (ONION_V3.matcher(onion3).matches()) {
|
||||||
bestOnion = onion3;
|
bestOnion = onion3;
|
||||||
|
version = "v3";
|
||||||
} else {
|
} else {
|
||||||
// Don't scrub the address so we can find the problem
|
// Don't scrub the address so we can find the problem
|
||||||
if (LOG.isLoggable(INFO))
|
if (LOG.isLoggable(INFO))
|
||||||
@@ -571,17 +670,21 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
if (bestOnion == null) return null;
|
if (bestOnion == null) return null;
|
||||||
Socket s = null;
|
Socket s = null;
|
||||||
try {
|
try {
|
||||||
if (LOG.isLoggable(INFO))
|
if (LOG.isLoggable(INFO)) {
|
||||||
LOG.info("Connecting to " + scrubOnion(bestOnion));
|
LOG.info("Connecting to " + version + " "
|
||||||
|
+ scrubOnion(bestOnion));
|
||||||
|
}
|
||||||
s = torSocketFactory.createSocket(bestOnion + ".onion", 80);
|
s = torSocketFactory.createSocket(bestOnion + ".onion", 80);
|
||||||
s.setSoTimeout(socketTimeout);
|
s.setSoTimeout(socketTimeout);
|
||||||
if (LOG.isLoggable(INFO))
|
if (LOG.isLoggable(INFO)) {
|
||||||
LOG.info("Connected to " + scrubOnion(bestOnion));
|
LOG.info("Connected to " + version + " "
|
||||||
|
+ scrubOnion(bestOnion));
|
||||||
|
}
|
||||||
return new TorTransportConnection(this, s);
|
return new TorTransportConnection(this, s);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
if (LOG.isLoggable(INFO)) {
|
if (LOG.isLoggable(INFO)) {
|
||||||
LOG.info("Could not connect to " + scrubOnion(bestOnion)
|
LOG.info("Could not connect to " + version + " "
|
||||||
+ ": " + e.toString());
|
+ scrubOnion(bestOnion) + ": " + e.toString());
|
||||||
}
|
}
|
||||||
tryToClose(s, LOG, WARNING);
|
tryToClose(s, LOG, WARNING);
|
||||||
return null;
|
return null;
|
||||||
@@ -634,8 +737,8 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
new TorTransportConnection(this, s));
|
new TorTransportConnection(this, s));
|
||||||
}
|
}
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
// This is expected when the socket is closed
|
// This is expected when the server socket is closed
|
||||||
if (LOG.isLoggable(INFO)) LOG.info(e.toString());
|
LOG.info("Rendezvous server socket closed");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
Map<Integer, String> portLines =
|
Map<Integer, String> portLines =
|
||||||
@@ -663,10 +766,9 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
@Override
|
@Override
|
||||||
public void circuitStatus(String status, String id, String path) {
|
public void circuitStatus(String status, String id, String path) {
|
||||||
if (status.equals("BUILT") &&
|
if (status.equals("BUILT") &&
|
||||||
connectionStatus.getAndSetCircuitBuilt()) {
|
state.getAndSetCircuitBuilt()) {
|
||||||
LOG.info("First circuit built");
|
LOG.info("First circuit built");
|
||||||
backoff.reset();
|
backoff.reset();
|
||||||
if (isRunning()) callback.transportEnabled();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -697,16 +799,23 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
public void message(String severity, String msg) {
|
public void message(String severity, String msg) {
|
||||||
if (LOG.isLoggable(INFO)) LOG.info(severity + " " + msg);
|
if (LOG.isLoggable(INFO)) LOG.info(severity + " " + msg);
|
||||||
if (severity.equals("NOTICE") && msg.startsWith("Bootstrapped 100%")) {
|
if (severity.equals("NOTICE") && msg.startsWith("Bootstrapped 100%")) {
|
||||||
connectionStatus.setBootstrapped();
|
state.setBootstrapped();
|
||||||
backoff.reset();
|
backoff.reset();
|
||||||
if (isRunning()) callback.transportEnabled();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void unrecognized(String type, String msg) {
|
public void unrecognized(String type, String msg) {
|
||||||
if (type.equals("HS_DESC") && msg.startsWith("UPLOADED"))
|
if (type.equals("HS_DESC") && msg.startsWith("UPLOADED")) {
|
||||||
LOG.info("Descriptor uploaded");
|
if (LOG.isLoggable(INFO)) {
|
||||||
|
String[] words = msg.split(" ");
|
||||||
|
if (words.length > 1 && ONION_V3.matcher(words[1]).matches()) {
|
||||||
|
LOG.info("V3 descriptor uploaded");
|
||||||
|
} else {
|
||||||
|
LOG.info("V2 descriptor uploaded");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -736,7 +845,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
private void disableNetwork() {
|
private void disableNetwork() {
|
||||||
connectionStatusExecutor.execute(() -> {
|
connectionStatusExecutor.execute(() -> {
|
||||||
try {
|
try {
|
||||||
enableNetwork(false);
|
if (state.isTorRunning()) enableNetwork(false);
|
||||||
} catch (IOException ex) {
|
} catch (IOException ex) {
|
||||||
logException(LOG, WARNING, ex);
|
logException(LOG, WARNING, ex);
|
||||||
}
|
}
|
||||||
@@ -746,63 +855,90 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
private void updateConnectionStatus(NetworkStatus status,
|
private void updateConnectionStatus(NetworkStatus status,
|
||||||
boolean charging) {
|
boolean charging) {
|
||||||
connectionStatusExecutor.execute(() -> {
|
connectionStatusExecutor.execute(() -> {
|
||||||
if (!running) return;
|
if (!state.isTorRunning()) return;
|
||||||
boolean online = status.isConnected();
|
boolean online = status.isConnected();
|
||||||
boolean wifi = status.isWifi();
|
boolean wifi = status.isWifi();
|
||||||
String country = locationUtils.getCurrentCountry();
|
String country = locationUtils.getCurrentCountry();
|
||||||
boolean blocked =
|
boolean blocked =
|
||||||
circumventionProvider.isTorProbablyBlocked(country);
|
circumventionProvider.isTorProbablyBlocked(country);
|
||||||
|
boolean enabledByUser = settings.getBoolean(PREF_PLUGIN_ENABLE,
|
||||||
|
DEFAULT_PREF_PLUGIN_ENABLE);
|
||||||
int network = settings.getInt(PREF_TOR_NETWORK,
|
int network = settings.getInt(PREF_TOR_NETWORK,
|
||||||
PREF_TOR_NETWORK_AUTOMATIC);
|
DEFAULT_PREF_TOR_NETWORK);
|
||||||
boolean useMobile = settings.getBoolean(PREF_TOR_MOBILE, true);
|
boolean useMobile = settings.getBoolean(PREF_TOR_MOBILE,
|
||||||
|
DEFAULT_PREF_TOR_MOBILE);
|
||||||
boolean onlyWhenCharging =
|
boolean onlyWhenCharging =
|
||||||
settings.getBoolean(PREF_TOR_ONLY_WHEN_CHARGING, false);
|
settings.getBoolean(PREF_TOR_ONLY_WHEN_CHARGING,
|
||||||
|
DEFAULT_PREF_TOR_ONLY_WHEN_CHARGING);
|
||||||
boolean bridgesWork = circumventionProvider.doBridgesWork(country);
|
boolean bridgesWork = circumventionProvider.doBridgesWork(country);
|
||||||
boolean automatic = network == PREF_TOR_NETWORK_AUTOMATIC;
|
boolean automatic = network == PREF_TOR_NETWORK_AUTOMATIC;
|
||||||
|
|
||||||
if (LOG.isLoggable(INFO)) {
|
if (LOG.isLoggable(INFO)) {
|
||||||
LOG.info("Online: " + online + ", wifi: " + wifi);
|
LOG.info("Online: " + online + ", wifi: " + wifi);
|
||||||
if ("".equals(country)) LOG.info("Country code unknown");
|
if (country.isEmpty()) LOG.info("Country code unknown");
|
||||||
else LOG.info("Country code: " + country);
|
else LOG.info("Country code: " + country);
|
||||||
LOG.info("Charging: " + charging);
|
LOG.info("Charging: " + charging);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
int reasonsDisabled = 0;
|
||||||
if (!online) {
|
boolean enableNetwork = false, enableBridges = false;
|
||||||
LOG.info("Disabling network, device is offline");
|
boolean useMeek = false, enableConnectionPadding = false;
|
||||||
enableNetwork(false);
|
|
||||||
} else if (!charging && onlyWhenCharging) {
|
if (!online) {
|
||||||
LOG.info("Disabling network, device is on battery");
|
LOG.info("Disabling network, device is offline");
|
||||||
enableNetwork(false);
|
} else {
|
||||||
} else if (network == PREF_TOR_NETWORK_NEVER ||
|
if (!enabledByUser) {
|
||||||
(!useMobile && !wifi)) {
|
LOG.info("User has disabled Tor");
|
||||||
LOG.info("Disabling network, device is using mobile data");
|
reasonsDisabled |= REASON_USER;
|
||||||
enableNetwork(false);
|
}
|
||||||
} else if (automatic && blocked && !bridgesWork) {
|
if (!charging && onlyWhenCharging) {
|
||||||
LOG.info("Disabling network, country is blocked");
|
LOG.info("Configured not to use battery");
|
||||||
enableNetwork(false);
|
reasonsDisabled |= REASON_BATTERY;
|
||||||
} else if (network == PREF_TOR_NETWORK_WITH_BRIDGES ||
|
}
|
||||||
(automatic && bridgesWork)) {
|
if (!useMobile && !wifi) {
|
||||||
if (circumventionProvider.needsMeek(country)) {
|
LOG.info("Configured not to use mobile data");
|
||||||
LOG.info("Enabling network, using meek bridges");
|
reasonsDisabled |= REASON_MOBILE_DATA;
|
||||||
enableBridges(true, true);
|
}
|
||||||
|
if (automatic && blocked && !bridgesWork) {
|
||||||
|
LOG.info("Country is blocked");
|
||||||
|
reasonsDisabled |= REASON_COUNTRY_BLOCKED;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reasonsDisabled != 0) {
|
||||||
|
LOG.info("Disabling network due to settings");
|
||||||
|
} else {
|
||||||
|
LOG.info("Enabling network");
|
||||||
|
enableNetwork = true;
|
||||||
|
if (network == PREF_TOR_NETWORK_WITH_BRIDGES ||
|
||||||
|
(automatic && bridgesWork)) {
|
||||||
|
if (circumventionProvider.needsMeek(country)) {
|
||||||
|
LOG.info("Using meek bridges");
|
||||||
|
enableBridges = true;
|
||||||
|
useMeek = true;
|
||||||
|
} else {
|
||||||
|
LOG.info("Using obfs4 bridges");
|
||||||
|
enableBridges = true;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
LOG.info("Enabling network, using obfs4 bridges");
|
LOG.info("Not using bridges");
|
||||||
enableBridges(true, false);
|
}
|
||||||
|
if (wifi && charging) {
|
||||||
|
LOG.info("Enabling connection padding");
|
||||||
|
enableConnectionPadding = true;
|
||||||
|
} else {
|
||||||
|
LOG.info("Disabling connection padding");
|
||||||
}
|
}
|
||||||
enableNetwork(true);
|
|
||||||
} else {
|
|
||||||
LOG.info("Enabling network, not using bridges");
|
|
||||||
enableBridges(false, false);
|
|
||||||
enableNetwork(true);
|
|
||||||
}
|
}
|
||||||
if (online && wifi && charging) {
|
}
|
||||||
LOG.info("Enabling connection padding");
|
|
||||||
enableConnectionPadding(true);
|
state.setReasonsDisabled(reasonsDisabled);
|
||||||
} else {
|
|
||||||
LOG.info("Disabling connection padding");
|
try {
|
||||||
enableConnectionPadding(false);
|
if (enableNetwork) {
|
||||||
|
enableBridges(enableBridges, useMeek);
|
||||||
|
enableConnectionPadding(enableConnectionPadding);
|
||||||
}
|
}
|
||||||
|
enableNetwork(enableNetwork);
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
logException(LOG, WARNING, e);
|
logException(LOG, WARNING, e);
|
||||||
}
|
}
|
||||||
@@ -810,33 +946,96 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void enableConnectionPadding(boolean enable) throws IOException {
|
private void enableConnectionPadding(boolean enable) throws IOException {
|
||||||
if (!running) return;
|
|
||||||
controlConnection.setConf("ConnectionPadding", enable ? "1" : "0");
|
controlConnection.setConf("ConnectionPadding", enable ? "1" : "0");
|
||||||
}
|
}
|
||||||
|
|
||||||
private static class ConnectionStatus {
|
@ThreadSafe
|
||||||
|
@NotNullByDefault
|
||||||
|
protected class PluginState {
|
||||||
|
|
||||||
// All of the following are locking: this
|
@GuardedBy("this")
|
||||||
private boolean networkEnabled = false;
|
private boolean started = false,
|
||||||
private boolean bootstrapped = false, circuitBuilt = false;
|
stopped = false,
|
||||||
|
networkInitialised = false,
|
||||||
|
networkEnabled = false,
|
||||||
|
bootstrapped = false,
|
||||||
|
circuitBuilt = false,
|
||||||
|
settingsChecked = false;
|
||||||
|
|
||||||
private synchronized void setBootstrapped() {
|
@GuardedBy("this")
|
||||||
bootstrapped = true;
|
private int reasonsDisabled = 0;
|
||||||
|
|
||||||
|
@GuardedBy("this")
|
||||||
|
@Nullable
|
||||||
|
private ServerSocket serverSocket = null;
|
||||||
|
|
||||||
|
synchronized void setStarted() {
|
||||||
|
started = true;
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
}
|
}
|
||||||
|
|
||||||
private synchronized boolean getAndSetCircuitBuilt() {
|
synchronized boolean isTorRunning() {
|
||||||
|
return started && !stopped;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nullable
|
||||||
|
synchronized ServerSocket setStopped() {
|
||||||
|
stopped = true;
|
||||||
|
ServerSocket ss = serverSocket;
|
||||||
|
serverSocket = null;
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
return ss;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized void setBootstrapped() {
|
||||||
|
bootstrapped = true;
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized boolean getAndSetCircuitBuilt() {
|
||||||
boolean firstCircuit = !circuitBuilt;
|
boolean firstCircuit = !circuitBuilt;
|
||||||
circuitBuilt = true;
|
circuitBuilt = true;
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
return firstCircuit;
|
return firstCircuit;
|
||||||
}
|
}
|
||||||
|
|
||||||
private synchronized void enableNetwork(boolean enable) {
|
synchronized void enableNetwork(boolean enable) {
|
||||||
|
networkInitialised = true;
|
||||||
networkEnabled = enable;
|
networkEnabled = enable;
|
||||||
if (!enable) circuitBuilt = false;
|
if (!enable) circuitBuilt = false;
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
}
|
}
|
||||||
|
|
||||||
private synchronized boolean isConnected() {
|
synchronized void setReasonsDisabled(int reasonsDisabled) {
|
||||||
return networkEnabled && bootstrapped && circuitBuilt;
|
settingsChecked = true;
|
||||||
|
this.reasonsDisabled = reasonsDisabled;
|
||||||
|
callback.pluginStateChanged(getState());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Doesn't affect getState()
|
||||||
|
synchronized boolean setServerSocket(ServerSocket ss) {
|
||||||
|
if (stopped || serverSocket != null) return false;
|
||||||
|
serverSocket = ss;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Doesn't affect getState()
|
||||||
|
synchronized void clearServerSocket(ServerSocket ss) {
|
||||||
|
if (serverSocket == ss) serverSocket = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized State getState() {
|
||||||
|
if (!started || stopped || !settingsChecked) {
|
||||||
|
return STARTING_STOPPING;
|
||||||
|
}
|
||||||
|
if (reasonsDisabled != 0) return DISABLED;
|
||||||
|
if (!networkInitialised) return ENABLING;
|
||||||
|
if (!networkEnabled) return INACTIVE;
|
||||||
|
return bootstrapped && circuitBuilt ? ACTIVE : ENABLING;
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized int getReasonsDisabled() {
|
||||||
|
return getState() == DISABLED ? reasonsDisabled : 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
|||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
||||||
|
import org.briarproject.bramble.api.properties.event.RemoteTransportPropertiesUpdatedEvent;
|
||||||
import org.briarproject.bramble.api.sync.Group;
|
import org.briarproject.bramble.api.sync.Group;
|
||||||
import org.briarproject.bramble.api.sync.Group.Visibility;
|
import org.briarproject.bramble.api.sync.Group.Visibility;
|
||||||
import org.briarproject.bramble.api.sync.GroupId;
|
import org.briarproject.bramble.api.sync.GroupId;
|
||||||
@@ -30,6 +31,7 @@ import org.briarproject.bramble.api.versioning.ClientVersioningManager;
|
|||||||
import org.briarproject.bramble.api.versioning.ClientVersioningManager.ClientVersioningHook;
|
import org.briarproject.bramble.api.versioning.ClientVersioningManager.ClientVersioningHook;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Map.Entry;
|
import java.util.Map.Entry;
|
||||||
|
|
||||||
@@ -41,6 +43,8 @@ import static org.briarproject.bramble.api.properties.TransportPropertyConstants
|
|||||||
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.MSG_KEY_LOCAL;
|
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.MSG_KEY_LOCAL;
|
||||||
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.MSG_KEY_TRANSPORT_ID;
|
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.MSG_KEY_TRANSPORT_ID;
|
||||||
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.MSG_KEY_VERSION;
|
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.MSG_KEY_VERSION;
|
||||||
|
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.REFLECTED_PROPERTY_PREFIX;
|
||||||
|
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
||||||
|
|
||||||
@Immutable
|
@Immutable
|
||||||
@NotNullByDefault
|
@NotNullByDefault
|
||||||
@@ -127,8 +131,10 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
|||||||
// We've already received a newer update - delete this one
|
// We've already received a newer update - delete this one
|
||||||
db.deleteMessage(txn, m.getId());
|
db.deleteMessage(txn, m.getId());
|
||||||
db.deleteMessageMetadata(txn, m.getId());
|
db.deleteMessageMetadata(txn, m.getId());
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
txn.attach(new RemoteTransportPropertiesUpdatedEvent(t));
|
||||||
} catch (FormatException e) {
|
} catch (FormatException e) {
|
||||||
throw new InvalidMessageException(e);
|
throw new InvalidMessageException(e);
|
||||||
}
|
}
|
||||||
@@ -151,15 +157,27 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
|||||||
if (props.isEmpty()) return;
|
if (props.isEmpty()) return;
|
||||||
try {
|
try {
|
||||||
db.transaction(false, txn -> {
|
db.transaction(false, txn -> {
|
||||||
Group g = getContactGroup(db.getContact(txn, c));
|
Contact contact = db.getContact(txn, c);
|
||||||
|
Group g = getContactGroup(contact);
|
||||||
BdfDictionary meta = clientHelper.getGroupMetadataAsDictionary(
|
BdfDictionary meta = clientHelper.getGroupMetadataAsDictionary(
|
||||||
txn, g.getId());
|
txn, g.getId());
|
||||||
BdfDictionary discovered =
|
BdfDictionary discovered =
|
||||||
meta.getOptionalDictionary(GROUP_KEY_DISCOVERED);
|
meta.getOptionalDictionary(GROUP_KEY_DISCOVERED);
|
||||||
if (discovered == null) discovered = new BdfDictionary();
|
BdfDictionary merged;
|
||||||
discovered.putAll(props);
|
boolean changed;
|
||||||
meta.put(GROUP_KEY_DISCOVERED, discovered);
|
if (discovered == null) {
|
||||||
clientHelper.mergeGroupMetadata(txn, g.getId(), meta);
|
merged = new BdfDictionary(props);
|
||||||
|
changed = true;
|
||||||
|
} else {
|
||||||
|
merged = new BdfDictionary(discovered);
|
||||||
|
merged.putAll(props);
|
||||||
|
changed = !merged.equals(discovered);
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
meta.put(GROUP_KEY_DISCOVERED, merged);
|
||||||
|
clientHelper.mergeGroupMetadata(txn, g.getId(), meta);
|
||||||
|
updateLocalProperties(txn, contact, t);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
} catch (FormatException e) {
|
} catch (FormatException e) {
|
||||||
throw new DbException(e);
|
throw new DbException(e);
|
||||||
@@ -224,6 +242,24 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void updateLocalProperties(Transaction txn, Contact c,
|
||||||
|
TransportId t) throws DbException {
|
||||||
|
try {
|
||||||
|
TransportProperties local;
|
||||||
|
LatestUpdate latest = findLatest(txn, localGroup.getId(), t, true);
|
||||||
|
if (latest == null) {
|
||||||
|
local = new TransportProperties();
|
||||||
|
} else {
|
||||||
|
BdfList message = clientHelper.getMessageAsList(txn,
|
||||||
|
latest.messageId);
|
||||||
|
local = parseProperties(message);
|
||||||
|
}
|
||||||
|
storeLocalProperties(txn, c, t, local);
|
||||||
|
} catch (FormatException e) {
|
||||||
|
throw new DbException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private TransportProperties getRemoteProperties(Transaction txn, Contact c,
|
private TransportProperties getRemoteProperties(Transaction txn, Contact c,
|
||||||
TransportId t) throws DbException {
|
TransportId t) throws DbException {
|
||||||
Group g = getContactGroup(c);
|
Group g = getContactGroup(c);
|
||||||
@@ -272,14 +308,22 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
|||||||
LatestUpdate latest = findLatest(txn, localGroup.getId(), t,
|
LatestUpdate latest = findLatest(txn, localGroup.getId(), t,
|
||||||
true);
|
true);
|
||||||
if (latest == null) {
|
if (latest == null) {
|
||||||
merged = p;
|
merged = new TransportProperties(p);
|
||||||
|
Iterator<String> it = merged.values().iterator();
|
||||||
|
while (it.hasNext()) {
|
||||||
|
if (isNullOrEmpty(it.next())) it.remove();
|
||||||
|
}
|
||||||
changed = true;
|
changed = true;
|
||||||
} else {
|
} else {
|
||||||
BdfList message = clientHelper.getMessageAsList(txn,
|
BdfList message = clientHelper.getMessageAsList(txn,
|
||||||
latest.messageId);
|
latest.messageId);
|
||||||
TransportProperties old = parseProperties(message);
|
TransportProperties old = parseProperties(message);
|
||||||
merged = new TransportProperties(old);
|
merged = new TransportProperties(old);
|
||||||
merged.putAll(p);
|
for (Entry<String, String> e : p.entrySet()) {
|
||||||
|
String key = e.getKey(), value = e.getValue();
|
||||||
|
if (isNullOrEmpty(value)) merged.remove(key);
|
||||||
|
else merged.put(key, value);
|
||||||
|
}
|
||||||
changed = !merged.equals(old);
|
changed = !merged.equals(old);
|
||||||
}
|
}
|
||||||
if (changed) {
|
if (changed) {
|
||||||
@@ -288,18 +332,10 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
|||||||
storeMessage(txn, localGroup.getId(), t, merged, version,
|
storeMessage(txn, localGroup.getId(), t, merged, version,
|
||||||
true, false);
|
true, false);
|
||||||
// Delete the previous update, if any
|
// Delete the previous update, if any
|
||||||
if (latest != null)
|
if (latest != null) db.removeMessage(txn, latest.messageId);
|
||||||
db.removeMessage(txn, latest.messageId);
|
|
||||||
// Store the merged properties in each contact's group
|
// Store the merged properties in each contact's group
|
||||||
for (Contact c : db.getContacts(txn)) {
|
for (Contact c : db.getContacts(txn)) {
|
||||||
Group g = getContactGroup(c);
|
storeLocalProperties(txn, c, t, merged);
|
||||||
latest = findLatest(txn, g.getId(), t, true);
|
|
||||||
version = latest == null ? 1 : latest.version + 1;
|
|
||||||
storeMessage(txn, g.getId(), t, merged, version,
|
|
||||||
true, true);
|
|
||||||
// Delete the previous update, if any
|
|
||||||
if (latest != null)
|
|
||||||
db.removeMessage(txn, latest.messageId);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -308,6 +344,34 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void storeLocalProperties(Transaction txn, Contact c,
|
||||||
|
TransportId t, TransportProperties p)
|
||||||
|
throws DbException, FormatException {
|
||||||
|
Group g = getContactGroup(c);
|
||||||
|
LatestUpdate latest = findLatest(txn, g.getId(), t, true);
|
||||||
|
long version = latest == null ? 1 : latest.version + 1;
|
||||||
|
// Reflect any remote properties we've discovered
|
||||||
|
BdfDictionary meta = clientHelper.getGroupMetadataAsDictionary(txn,
|
||||||
|
g.getId());
|
||||||
|
BdfDictionary discovered =
|
||||||
|
meta.getOptionalDictionary(GROUP_KEY_DISCOVERED);
|
||||||
|
TransportProperties combined;
|
||||||
|
if (discovered == null) {
|
||||||
|
combined = p;
|
||||||
|
} else {
|
||||||
|
combined = new TransportProperties(p);
|
||||||
|
TransportProperties d = clientHelper
|
||||||
|
.parseAndValidateTransportProperties(discovered);
|
||||||
|
for (Entry<String, String> e : d.entrySet()) {
|
||||||
|
String key = REFLECTED_PROPERTY_PREFIX + e.getKey();
|
||||||
|
combined.put(key, e.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
storeMessage(txn, g.getId(), t, combined, version, true, true);
|
||||||
|
// Delete the previous update, if any
|
||||||
|
if (latest != null) db.removeMessage(txn, latest.messageId);
|
||||||
|
}
|
||||||
|
|
||||||
private Group getContactGroup(Contact c) {
|
private Group getContactGroup(Contact c) {
|
||||||
return contactGroupFactory.createContactGroup(CLIENT_ID,
|
return contactGroupFactory.createContactGroup(CLIENT_ID,
|
||||||
MAJOR_VERSION, c);
|
MAJOR_VERSION, c);
|
||||||
|
|||||||
@@ -31,8 +31,8 @@ import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
|||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||||
import org.briarproject.bramble.api.plugin.event.TransportDisabledEvent;
|
import org.briarproject.bramble.api.plugin.event.TransportActiveEvent;
|
||||||
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
|
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
||||||
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
||||||
@@ -41,7 +41,9 @@ import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionClosedE
|
|||||||
import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionOpenedEvent;
|
import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionOpenedEvent;
|
||||||
import org.briarproject.bramble.api.rendezvous.event.RendezvousPollEvent;
|
import org.briarproject.bramble.api.rendezvous.event.RendezvousPollEvent;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
import org.briarproject.bramble.api.system.Scheduler;
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler.Cancellable;
|
||||||
|
import org.briarproject.bramble.api.system.Wakeful;
|
||||||
|
|
||||||
import java.security.GeneralSecurityException;
|
import java.security.GeneralSecurityException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -52,7 +54,6 @@ import java.util.Map;
|
|||||||
import java.util.Map.Entry;
|
import java.util.Map.Entry;
|
||||||
import java.util.concurrent.ConcurrentHashMap;
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
@@ -68,6 +69,7 @@ import static org.briarproject.bramble.api.contact.PendingContactState.ADDING_CO
|
|||||||
import static org.briarproject.bramble.api.contact.PendingContactState.FAILED;
|
import static org.briarproject.bramble.api.contact.PendingContactState.FAILED;
|
||||||
import static org.briarproject.bramble.api.contact.PendingContactState.OFFLINE;
|
import static org.briarproject.bramble.api.contact.PendingContactState.OFFLINE;
|
||||||
import static org.briarproject.bramble.api.contact.PendingContactState.WAITING_FOR_CONNECTION;
|
import static org.briarproject.bramble.api.contact.PendingContactState.WAITING_FOR_CONNECTION;
|
||||||
|
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
||||||
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNull;
|
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNull;
|
||||||
import static org.briarproject.bramble.rendezvous.RendezvousConstants.POLLING_INTERVAL_MS;
|
import static org.briarproject.bramble.rendezvous.RendezvousConstants.POLLING_INTERVAL_MS;
|
||||||
import static org.briarproject.bramble.rendezvous.RendezvousConstants.RENDEZVOUS_TIMEOUT_MS;
|
import static org.briarproject.bramble.rendezvous.RendezvousConstants.RENDEZVOUS_TIMEOUT_MS;
|
||||||
@@ -80,7 +82,7 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
|||||||
private static final Logger LOG =
|
private static final Logger LOG =
|
||||||
getLogger(RendezvousPollerImpl.class.getName());
|
getLogger(RendezvousPollerImpl.class.getName());
|
||||||
|
|
||||||
private final ScheduledExecutorService scheduler;
|
private final TaskScheduler scheduler;
|
||||||
private final DatabaseComponent db;
|
private final DatabaseComponent db;
|
||||||
private final IdentityManager identityManager;
|
private final IdentityManager identityManager;
|
||||||
private final TransportCrypto transportCrypto;
|
private final TransportCrypto transportCrypto;
|
||||||
@@ -102,10 +104,12 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
|||||||
new HashMap<>();
|
new HashMap<>();
|
||||||
@Nullable
|
@Nullable
|
||||||
private KeyPair handshakeKeyPair = null;
|
private KeyPair handshakeKeyPair = null;
|
||||||
|
@Nullable
|
||||||
|
private Cancellable pollTask = null;
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
RendezvousPollerImpl(@IoExecutor Executor ioExecutor,
|
RendezvousPollerImpl(@IoExecutor Executor ioExecutor,
|
||||||
@Scheduler ScheduledExecutorService scheduler,
|
TaskScheduler scheduler,
|
||||||
DatabaseComponent db,
|
DatabaseComponent db,
|
||||||
IdentityManager identityManager,
|
IdentityManager identityManager,
|
||||||
TransportCrypto transportCrypto,
|
TransportCrypto transportCrypto,
|
||||||
@@ -144,8 +148,6 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
|||||||
} catch (DbException e) {
|
} catch (DbException e) {
|
||||||
throw new ServiceException(e);
|
throw new ServiceException(e);
|
||||||
}
|
}
|
||||||
scheduler.scheduleAtFixedRate(this::poll, POLLING_INTERVAL_MS,
|
|
||||||
POLLING_INTERVAL_MS, MILLISECONDS);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@EventExecutor
|
@EventExecutor
|
||||||
@@ -186,6 +188,12 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
|||||||
}
|
}
|
||||||
if (cs.numEndpoints == 0) broadcastState(p.getId(), OFFLINE);
|
if (cs.numEndpoints == 0) broadcastState(p.getId(), OFFLINE);
|
||||||
else broadcastState(p.getId(), WAITING_FOR_CONNECTION);
|
else broadcastState(p.getId(), WAITING_FOR_CONNECTION);
|
||||||
|
if (cryptoStates.size() == 1) {
|
||||||
|
LOG.info("Starting poller");
|
||||||
|
requireNull(pollTask);
|
||||||
|
pollTask = scheduler.scheduleWithFixedDelay(this::poll, worker,
|
||||||
|
POLLING_INTERVAL_MS, POLLING_INTERVAL_MS, MILLISECONDS);
|
||||||
|
}
|
||||||
} catch (DbException | GeneralSecurityException e) {
|
} catch (DbException | GeneralSecurityException e) {
|
||||||
logException(LOG, WARNING, e);
|
logException(LOG, WARNING, e);
|
||||||
}
|
}
|
||||||
@@ -205,12 +213,12 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
|||||||
return plugin.createRendezvousEndpoint(k, cs.alice, h);
|
return plugin.createRendezvousEndpoint(k, cs.alice, h);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Scheduler
|
// Worker
|
||||||
|
@Wakeful
|
||||||
private void poll() {
|
private void poll() {
|
||||||
worker.execute(() -> {
|
LOG.info("Polling");
|
||||||
removeExpiredPendingContacts();
|
removeExpiredPendingContacts();
|
||||||
for (PluginState ps : pluginStates.values()) poll(ps);
|
for (PluginState ps : pluginStates.values()) poll(ps);
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Worker
|
// Worker
|
||||||
@@ -235,9 +243,15 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
|||||||
RendezvousEndpoint endpoint = ps.endpoints.remove(p);
|
RendezvousEndpoint endpoint = ps.endpoints.remove(p);
|
||||||
if (endpoint != null) tryToClose(endpoint, LOG, INFO);
|
if (endpoint != null) tryToClose(endpoint, LOG, INFO);
|
||||||
}
|
}
|
||||||
|
if (cryptoStates.isEmpty()) {
|
||||||
|
LOG.info("Stopping poller");
|
||||||
|
requireNonNull(pollTask).cancel();
|
||||||
|
pollTask = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Worker
|
// Worker
|
||||||
|
@Wakeful
|
||||||
private void poll(PluginState ps) {
|
private void poll(PluginState ps) {
|
||||||
if (ps.endpoints.isEmpty()) return;
|
if (ps.endpoints.isEmpty()) return;
|
||||||
TransportId t = ps.plugin.getId();
|
TransportId t = ps.plugin.getId();
|
||||||
@@ -269,11 +283,11 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
|||||||
} else if (e instanceof PendingContactRemovedEvent) {
|
} else if (e instanceof PendingContactRemovedEvent) {
|
||||||
PendingContactRemovedEvent p = (PendingContactRemovedEvent) e;
|
PendingContactRemovedEvent p = (PendingContactRemovedEvent) e;
|
||||||
removePendingContactAsync(p.getId());
|
removePendingContactAsync(p.getId());
|
||||||
} else if (e instanceof TransportEnabledEvent) {
|
} else if (e instanceof TransportActiveEvent) {
|
||||||
TransportEnabledEvent t = (TransportEnabledEvent) e;
|
TransportActiveEvent t = (TransportActiveEvent) e;
|
||||||
addTransportAsync(t.getTransportId());
|
addTransportAsync(t.getTransportId());
|
||||||
} else if (e instanceof TransportDisabledEvent) {
|
} else if (e instanceof TransportInactiveEvent) {
|
||||||
TransportDisabledEvent t = (TransportDisabledEvent) e;
|
TransportInactiveEvent t = (TransportInactiveEvent) e;
|
||||||
removeTransportAsync(t.getTransportId());
|
removeTransportAsync(t.getTransportId());
|
||||||
} else if (e instanceof RendezvousConnectionOpenedEvent) {
|
} else if (e instanceof RendezvousConnectionOpenedEvent) {
|
||||||
RendezvousConnectionOpenedEvent r =
|
RendezvousConnectionOpenedEvent r =
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import org.briarproject.bramble.api.event.EventListener;
|
|||||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.TorConstants;
|
import org.briarproject.bramble.api.plugin.TorConstants;
|
||||||
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
|
import org.briarproject.bramble.api.plugin.event.TransportActiveEvent;
|
||||||
import org.briarproject.bramble.api.reporting.DevConfig;
|
import org.briarproject.bramble.api.reporting.DevConfig;
|
||||||
import org.briarproject.bramble.api.reporting.DevReporter;
|
import org.briarproject.bramble.api.reporting.DevReporter;
|
||||||
import org.briarproject.bramble.util.IoUtils;
|
import org.briarproject.bramble.util.IoUtils;
|
||||||
@@ -92,8 +92,8 @@ class DevReporterImpl implements DevReporter, EventListener {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void eventOccurred(Event e) {
|
public void eventOccurred(Event e) {
|
||||||
if (e instanceof TransportEnabledEvent) {
|
if (e instanceof TransportActiveEvent) {
|
||||||
TransportEnabledEvent t = (TransportEnabledEvent) e;
|
TransportActiveEvent t = (TransportActiveEvent) e;
|
||||||
if (t.getTransportId().equals(TorConstants.ID))
|
if (t.getTransportId().equals(TorConstants.ID))
|
||||||
ioExecutor.execute(this::sendReports);
|
ioExecutor.execute(this::sendReports);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
|||||||
import org.briarproject.bramble.api.lifecycle.event.LifecycleEvent;
|
import org.briarproject.bramble.api.lifecycle.event.LifecycleEvent;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
|
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||||
import org.briarproject.bramble.api.sync.Ack;
|
import org.briarproject.bramble.api.sync.Ack;
|
||||||
import org.briarproject.bramble.api.sync.Message;
|
import org.briarproject.bramble.api.sync.Message;
|
||||||
import org.briarproject.bramble.api.sync.Offer;
|
import org.briarproject.bramble.api.sync.Offer;
|
||||||
@@ -238,6 +239,9 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
|
|||||||
} else if (e instanceof CloseSyncConnectionsEvent) {
|
} else if (e instanceof CloseSyncConnectionsEvent) {
|
||||||
CloseSyncConnectionsEvent c = (CloseSyncConnectionsEvent) e;
|
CloseSyncConnectionsEvent c = (CloseSyncConnectionsEvent) e;
|
||||||
if (c.getTransportId().equals(transportId)) interrupt();
|
if (c.getTransportId().equals(transportId)) interrupt();
|
||||||
|
} else if (e instanceof TransportInactiveEvent) {
|
||||||
|
TransportInactiveEvent t = (TransportInactiveEvent) e;
|
||||||
|
if (t.getTransportId().equals(transportId)) interrupt();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
|||||||
import org.briarproject.bramble.api.lifecycle.event.LifecycleEvent;
|
import org.briarproject.bramble.api.lifecycle.event.LifecycleEvent;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
|
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||||
import org.briarproject.bramble.api.sync.Ack;
|
import org.briarproject.bramble.api.sync.Ack;
|
||||||
import org.briarproject.bramble.api.sync.Message;
|
import org.briarproject.bramble.api.sync.Message;
|
||||||
import org.briarproject.bramble.api.sync.SyncRecordWriter;
|
import org.briarproject.bramble.api.sync.SyncRecordWriter;
|
||||||
@@ -131,6 +132,9 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
|
|||||||
} else if (e instanceof CloseSyncConnectionsEvent) {
|
} else if (e instanceof CloseSyncConnectionsEvent) {
|
||||||
CloseSyncConnectionsEvent c = (CloseSyncConnectionsEvent) e;
|
CloseSyncConnectionsEvent c = (CloseSyncConnectionsEvent) e;
|
||||||
if (c.getTransportId().equals(transportId)) interrupt();
|
if (c.getTransportId().equals(transportId)) interrupt();
|
||||||
|
} else if (e instanceof TransportInactiveEvent) {
|
||||||
|
TransportInactiveEvent t = (TransportInactiveEvent) e;
|
||||||
|
if (t.getTransportId().equals(transportId)) interrupt();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ import java.util.concurrent.Executor;
|
|||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import javax.annotation.Nullable;
|
||||||
import javax.annotation.concurrent.ThreadSafe;
|
import javax.annotation.concurrent.ThreadSafe;
|
||||||
import javax.inject.Inject;
|
import javax.inject.Inject;
|
||||||
|
|
||||||
@@ -124,8 +125,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
|
|||||||
Group g = db.getGroup(txn, m.getGroupId());
|
Group g = db.getGroup(txn, m.getGroupId());
|
||||||
return new Pair<>(m, g);
|
return new Pair<>(m, g);
|
||||||
});
|
});
|
||||||
validateMessageAsync(mg.getFirst(), mg.getSecond());
|
validateMessageAsync(mg.getFirst(), mg.getSecond(), unvalidated);
|
||||||
validateNextMessageAsync(unvalidated);
|
|
||||||
} catch (NoSuchMessageException e) {
|
} catch (NoSuchMessageException e) {
|
||||||
LOG.info("Message removed before validation");
|
LOG.info("Message removed before validation");
|
||||||
validateNextMessageAsync(unvalidated);
|
validateNextMessageAsync(unvalidated);
|
||||||
@@ -213,12 +213,14 @@ class ValidationManagerImpl implements ValidationManager, Service,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void validateMessageAsync(Message m, Group g) {
|
private void validateMessageAsync(Message m, Group g,
|
||||||
validationExecutor.execute(() -> validateMessage(m, g));
|
@Nullable Queue<MessageId> unvalidated) {
|
||||||
|
validationExecutor.execute(() -> validateMessage(m, g, unvalidated));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ValidationExecutor
|
@ValidationExecutor
|
||||||
private void validateMessage(Message m, Group g) {
|
private void validateMessage(Message m, Group g,
|
||||||
|
@Nullable Queue<MessageId> unvalidated) {
|
||||||
ClientMajorVersion cv =
|
ClientMajorVersion cv =
|
||||||
new ClientMajorVersion(g.getClientId(), g.getMajorVersion());
|
new ClientMajorVersion(g.getClientId(), g.getMajorVersion());
|
||||||
MessageValidator v = validators.get(cv);
|
MessageValidator v = validators.get(cv);
|
||||||
@@ -234,6 +236,8 @@ class ValidationManagerImpl implements ValidationManager, Service,
|
|||||||
Queue<MessageId> invalidate = new LinkedList<>();
|
Queue<MessageId> invalidate = new LinkedList<>();
|
||||||
invalidate.add(m.getId());
|
invalidate.add(m.getId());
|
||||||
invalidateNextMessageAsync(invalidate);
|
invalidateNextMessageAsync(invalidate);
|
||||||
|
} finally {
|
||||||
|
if (unvalidated != null) validateNextMessageAsync(unvalidated);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -440,7 +444,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
|
|||||||
try {
|
try {
|
||||||
Group g = db.transactionWithResult(true, txn ->
|
Group g = db.transactionWithResult(true, txn ->
|
||||||
db.getGroup(txn, m.getGroupId()));
|
db.getGroup(txn, m.getGroupId()));
|
||||||
validateMessageAsync(m, g);
|
validateMessageAsync(m, g, null);
|
||||||
} catch (NoSuchGroupException e) {
|
} catch (NoSuchGroupException e) {
|
||||||
LOG.info("Group removed before validation");
|
LOG.info("Group removed before validation");
|
||||||
} catch (DbException e) {
|
} catch (DbException e) {
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
|
|
||||||
|
import dagger.Module;
|
||||||
|
import dagger.Provides;
|
||||||
|
|
||||||
|
@Module
|
||||||
|
public class ClockModule {
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
Clock provideClock() {
|
||||||
|
return new SystemClock();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
package org.briarproject.bramble.system;
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
|
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
import org.briarproject.bramble.api.system.Scheduler;
|
|
||||||
|
|
||||||
import java.util.concurrent.RejectedExecutionHandler;
|
import java.util.concurrent.RejectedExecutionHandler;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
@@ -15,34 +14,26 @@ import dagger.Module;
|
|||||||
import dagger.Provides;
|
import dagger.Provides;
|
||||||
|
|
||||||
@Module
|
@Module
|
||||||
public class SystemModule {
|
public class DefaultTaskSchedulerModule {
|
||||||
|
|
||||||
public static class EagerSingletons {
|
public static class EagerSingletons {
|
||||||
@Inject
|
@Inject
|
||||||
@Scheduler
|
TaskScheduler scheduler;
|
||||||
ScheduledExecutorService scheduledExecutorService;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private final ScheduledExecutorService scheduler;
|
private final ScheduledExecutorService scheduledExecutorService;
|
||||||
|
|
||||||
public SystemModule() {
|
public DefaultTaskSchedulerModule() {
|
||||||
// Discard tasks that are submitted during shutdown
|
// Discard tasks that are submitted during shutdown
|
||||||
RejectedExecutionHandler policy =
|
RejectedExecutionHandler policy =
|
||||||
new ScheduledThreadPoolExecutor.DiscardPolicy();
|
new ScheduledThreadPoolExecutor.DiscardPolicy();
|
||||||
scheduler = new ScheduledThreadPoolExecutor(1, policy);
|
scheduledExecutorService = new ScheduledThreadPoolExecutor(1, policy);
|
||||||
}
|
|
||||||
|
|
||||||
@Provides
|
|
||||||
Clock provideClock() {
|
|
||||||
return new SystemClock();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
@Scheduler
|
TaskScheduler provideTaskScheduler(LifecycleManager lifecycleManager) {
|
||||||
ScheduledExecutorService provideScheduledExecutorService(
|
lifecycleManager.registerForShutdown(scheduledExecutorService);
|
||||||
LifecycleManager lifecycleManager) {
|
return new TaskSchedulerImpl(scheduledExecutorService);
|
||||||
lifecycleManager.registerForShutdown(scheduler);
|
|
||||||
return scheduler;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||||
|
import org.briarproject.bramble.api.system.WakefulIoExecutor;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
|
||||||
|
import dagger.Module;
|
||||||
|
import dagger.Provides;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provides a default implementation of {@link WakefulIoExecutor} for systems
|
||||||
|
* without wake locks.
|
||||||
|
*/
|
||||||
|
@Module
|
||||||
|
public class DefaultWakefulIoExecutorModule {
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@WakefulIoExecutor
|
||||||
|
Executor provideWakefulIoExecutor(@IoExecutor Executor ioExecutor) {
|
||||||
|
return ioExecutor;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package org.briarproject.bramble.system;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executor;
|
||||||
|
import java.util.concurrent.ScheduledExecutorService;
|
||||||
|
import java.util.concurrent.ScheduledFuture;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import javax.annotation.concurrent.ThreadSafe;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A {@link TaskScheduler} that uses a {@link ScheduledExecutorService}.
|
||||||
|
*/
|
||||||
|
@ThreadSafe
|
||||||
|
@NotNullByDefault
|
||||||
|
class TaskSchedulerImpl implements TaskScheduler {
|
||||||
|
|
||||||
|
private final ScheduledExecutorService scheduledExecutorService;
|
||||||
|
|
||||||
|
TaskSchedulerImpl(ScheduledExecutorService scheduledExecutorService) {
|
||||||
|
this.scheduledExecutorService = scheduledExecutorService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Cancellable schedule(Runnable task, Executor executor, long delay,
|
||||||
|
TimeUnit unit) {
|
||||||
|
Runnable execute = () -> executor.execute(task);
|
||||||
|
ScheduledFuture<?> future =
|
||||||
|
scheduledExecutorService.schedule(execute, delay, unit);
|
||||||
|
return () -> future.cancel(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Cancellable scheduleWithFixedDelay(Runnable task, Executor executor,
|
||||||
|
long delay, long interval, TimeUnit unit) {
|
||||||
|
Runnable execute = () -> executor.execute(task);
|
||||||
|
ScheduledFuture<?> future = scheduledExecutorService.
|
||||||
|
scheduleWithFixedDelay(execute, delay, interval, unit);
|
||||||
|
return () -> future.cancel(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,10 +6,9 @@ import org.briarproject.bramble.api.db.DatabaseExecutor;
|
|||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
import org.briarproject.bramble.api.system.Scheduler;
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
|
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
|
|
||||||
import javax.annotation.concurrent.Immutable;
|
import javax.annotation.concurrent.Immutable;
|
||||||
import javax.inject.Inject;
|
import javax.inject.Inject;
|
||||||
@@ -22,14 +21,15 @@ class TransportKeyManagerFactoryImpl implements
|
|||||||
private final DatabaseComponent db;
|
private final DatabaseComponent db;
|
||||||
private final TransportCrypto transportCrypto;
|
private final TransportCrypto transportCrypto;
|
||||||
private final Executor dbExecutor;
|
private final Executor dbExecutor;
|
||||||
private final ScheduledExecutorService scheduler;
|
private final TaskScheduler scheduler;
|
||||||
private final Clock clock;
|
private final Clock clock;
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
TransportKeyManagerFactoryImpl(DatabaseComponent db,
|
TransportKeyManagerFactoryImpl(DatabaseComponent db,
|
||||||
TransportCrypto transportCrypto,
|
TransportCrypto transportCrypto,
|
||||||
@DatabaseExecutor Executor dbExecutor,
|
@DatabaseExecutor Executor dbExecutor,
|
||||||
@Scheduler ScheduledExecutorService scheduler, Clock clock) {
|
TaskScheduler scheduler,
|
||||||
|
Clock clock) {
|
||||||
this.db = db;
|
this.db = db;
|
||||||
this.transportCrypto = transportCrypto;
|
this.transportCrypto = transportCrypto;
|
||||||
this.dbExecutor = dbExecutor;
|
this.dbExecutor = dbExecutor;
|
||||||
|
|||||||
@@ -6,12 +6,14 @@ import org.briarproject.bramble.api.contact.PendingContactId;
|
|||||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||||
import org.briarproject.bramble.api.crypto.TransportCrypto;
|
import org.briarproject.bramble.api.crypto.TransportCrypto;
|
||||||
import org.briarproject.bramble.api.db.DatabaseComponent;
|
import org.briarproject.bramble.api.db.DatabaseComponent;
|
||||||
|
import org.briarproject.bramble.api.db.DatabaseExecutor;
|
||||||
import org.briarproject.bramble.api.db.DbException;
|
import org.briarproject.bramble.api.db.DbException;
|
||||||
import org.briarproject.bramble.api.db.Transaction;
|
import org.briarproject.bramble.api.db.Transaction;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
import org.briarproject.bramble.api.system.Scheduler;
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
|
import org.briarproject.bramble.api.system.Wakeful;
|
||||||
import org.briarproject.bramble.api.transport.KeySetId;
|
import org.briarproject.bramble.api.transport.KeySetId;
|
||||||
import org.briarproject.bramble.api.transport.StreamContext;
|
import org.briarproject.bramble.api.transport.StreamContext;
|
||||||
import org.briarproject.bramble.api.transport.TransportKeySet;
|
import org.briarproject.bramble.api.transport.TransportKeySet;
|
||||||
@@ -24,7 +26,6 @@ import java.util.HashMap;
|
|||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.concurrent.locks.ReentrantLock;
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
@@ -53,7 +54,7 @@ class TransportKeyManagerImpl implements TransportKeyManager {
|
|||||||
private final DatabaseComponent db;
|
private final DatabaseComponent db;
|
||||||
private final TransportCrypto transportCrypto;
|
private final TransportCrypto transportCrypto;
|
||||||
private final Executor dbExecutor;
|
private final Executor dbExecutor;
|
||||||
private final ScheduledExecutorService scheduler;
|
private final TaskScheduler scheduler;
|
||||||
private final Clock clock;
|
private final Clock clock;
|
||||||
private final TransportId transportId;
|
private final TransportId transportId;
|
||||||
private final long timePeriodLength;
|
private final long timePeriodLength;
|
||||||
@@ -72,9 +73,12 @@ class TransportKeyManagerImpl implements TransportKeyManager {
|
|||||||
pendingContactOutContexts = new HashMap<>();
|
pendingContactOutContexts = new HashMap<>();
|
||||||
|
|
||||||
TransportKeyManagerImpl(DatabaseComponent db,
|
TransportKeyManagerImpl(DatabaseComponent db,
|
||||||
TransportCrypto transportCrypto, Executor dbExecutor,
|
TransportCrypto transportCrypto,
|
||||||
@Scheduler ScheduledExecutorService scheduler, Clock clock,
|
Executor dbExecutor,
|
||||||
TransportId transportId, long maxLatency) {
|
TaskScheduler scheduler,
|
||||||
|
Clock clock,
|
||||||
|
TransportId transportId,
|
||||||
|
long maxLatency) {
|
||||||
this.db = db;
|
this.db = db;
|
||||||
this.transportCrypto = transportCrypto;
|
this.transportCrypto = transportCrypto;
|
||||||
this.dbExecutor = dbExecutor;
|
this.dbExecutor = dbExecutor;
|
||||||
@@ -196,17 +200,17 @@ class TransportKeyManagerImpl implements TransportKeyManager {
|
|||||||
|
|
||||||
private void scheduleKeyUpdate(long now) {
|
private void scheduleKeyUpdate(long now) {
|
||||||
long delay = timePeriodLength - now % timePeriodLength;
|
long delay = timePeriodLength - now % timePeriodLength;
|
||||||
scheduler.schedule((Runnable) this::updateKeys, delay, MILLISECONDS);
|
scheduler.schedule(this::updateKeys, dbExecutor, delay, MILLISECONDS);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@DatabaseExecutor
|
||||||
|
@Wakeful
|
||||||
private void updateKeys() {
|
private void updateKeys() {
|
||||||
dbExecutor.execute(() -> {
|
try {
|
||||||
try {
|
db.transaction(false, this::updateKeys);
|
||||||
db.transaction(false, this::updateKeys);
|
} catch (DbException e) {
|
||||||
} catch (DbException e) {
|
logException(LOG, WARNING, e);
|
||||||
logException(LOG, WARNING, e);
|
}
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -439,6 +443,8 @@ class TransportKeyManagerImpl implements TransportKeyManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@DatabaseExecutor
|
||||||
|
@Wakeful
|
||||||
private void updateKeys(Transaction txn) throws DbException {
|
private void updateKeys(Transaction txn) throws DbException {
|
||||||
long now = clock.currentTimeMillis();
|
long now = clock.currentTimeMillis();
|
||||||
lock.lock();
|
lock.lock();
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package org.briarproject.bramble;
|
||||||
|
|
||||||
|
import org.briarproject.bramble.system.DefaultTaskSchedulerModule;
|
||||||
|
|
||||||
|
public interface BrambleCoreIntegrationTestEagerSingletons
|
||||||
|
extends BrambleCoreEagerSingletons {
|
||||||
|
|
||||||
|
void inject(DefaultTaskSchedulerModule.EagerSingletons init);
|
||||||
|
|
||||||
|
class Helper {
|
||||||
|
|
||||||
|
public static void injectEagerSingletons(
|
||||||
|
BrambleCoreIntegrationTestEagerSingletons c) {
|
||||||
|
BrambleCoreEagerSingletons.Helper.injectEagerSingletons(c);
|
||||||
|
c.inject(new DefaultTaskSchedulerModule.EagerSingletons());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
package org.briarproject.bramble.contact;
|
package org.briarproject.bramble.contact;
|
||||||
|
|
||||||
import org.briarproject.bramble.BrambleCoreEagerSingletons;
|
import org.briarproject.bramble.BrambleCoreIntegrationTestEagerSingletons;
|
||||||
import org.briarproject.bramble.api.Pair;
|
import org.briarproject.bramble.api.Pair;
|
||||||
import org.briarproject.bramble.api.contact.Contact;
|
import org.briarproject.bramble.api.contact.Contact;
|
||||||
import org.briarproject.bramble.api.contact.ContactManager;
|
import org.briarproject.bramble.api.contact.ContactManager;
|
||||||
@@ -62,11 +62,13 @@ public class ContactExchangeIntegrationTest extends BrambleTestCase {
|
|||||||
alice = DaggerContactExchangeIntegrationTestComponent.builder()
|
alice = DaggerContactExchangeIntegrationTestComponent.builder()
|
||||||
.testDatabaseConfigModule(
|
.testDatabaseConfigModule(
|
||||||
new TestDatabaseConfigModule(aliceDir)).build();
|
new TestDatabaseConfigModule(aliceDir)).build();
|
||||||
BrambleCoreEagerSingletons.Helper.injectEagerSingletons(alice);
|
BrambleCoreIntegrationTestEagerSingletons.Helper
|
||||||
|
.injectEagerSingletons(alice);
|
||||||
bob = DaggerContactExchangeIntegrationTestComponent.builder()
|
bob = DaggerContactExchangeIntegrationTestComponent.builder()
|
||||||
.testDatabaseConfigModule(new TestDatabaseConfigModule(bobDir))
|
.testDatabaseConfigModule(new TestDatabaseConfigModule(bobDir))
|
||||||
.build();
|
.build();
|
||||||
BrambleCoreEagerSingletons.Helper.injectEagerSingletons(bob);
|
BrambleCoreIntegrationTestEagerSingletons.Helper
|
||||||
|
.injectEagerSingletons(bob);
|
||||||
// Set up the devices and get the identities
|
// Set up the devices and get the identities
|
||||||
aliceIdentity = setUp(alice, "Alice");
|
aliceIdentity = setUp(alice, "Alice");
|
||||||
bobIdentity = setUp(bob, "Bob");
|
bobIdentity = setUp(bob, "Bob");
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package org.briarproject.bramble.contact;
|
package org.briarproject.bramble.contact;
|
||||||
|
|
||||||
import org.briarproject.bramble.BrambleCoreEagerSingletons;
|
import org.briarproject.bramble.BrambleCoreIntegrationTestEagerSingletons;
|
||||||
import org.briarproject.bramble.BrambleCoreModule;
|
import org.briarproject.bramble.BrambleCoreModule;
|
||||||
import org.briarproject.bramble.api.connection.ConnectionManager;
|
import org.briarproject.bramble.api.connection.ConnectionManager;
|
||||||
import org.briarproject.bramble.api.contact.ContactExchangeManager;
|
import org.briarproject.bramble.api.contact.ContactExchangeManager;
|
||||||
@@ -23,7 +23,7 @@ import dagger.Component;
|
|||||||
BrambleCoreModule.class
|
BrambleCoreModule.class
|
||||||
})
|
})
|
||||||
interface ContactExchangeIntegrationTestComponent
|
interface ContactExchangeIntegrationTestComponent
|
||||||
extends BrambleCoreEagerSingletons {
|
extends BrambleCoreIntegrationTestEagerSingletons {
|
||||||
|
|
||||||
ConnectionManager getConnectionManager();
|
ConnectionManager getConnectionManager();
|
||||||
|
|
||||||
|
|||||||
@@ -109,8 +109,8 @@ public class PluginManagerImplTest extends BrambleTestCase {
|
|||||||
oneOf(duplexPlugin).stop();
|
oneOf(duplexPlugin).stop();
|
||||||
}});
|
}});
|
||||||
|
|
||||||
PluginManagerImpl p = new PluginManagerImpl(ioExecutor, eventBus,
|
PluginManagerImpl p = new PluginManagerImpl(ioExecutor, ioExecutor,
|
||||||
pluginConfig, connectionManager, settingsManager,
|
eventBus, pluginConfig, connectionManager, settingsManager,
|
||||||
transportPropertyManager);
|
transportPropertyManager);
|
||||||
|
|
||||||
// Two plugins should be started and stopped
|
// Two plugins should be started and stopped
|
||||||
|
|||||||
@@ -13,12 +13,14 @@ import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
|||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||||
import org.briarproject.bramble.api.plugin.event.ConnectionClosedEvent;
|
import org.briarproject.bramble.api.plugin.event.ConnectionClosedEvent;
|
||||||
import org.briarproject.bramble.api.plugin.event.ConnectionOpenedEvent;
|
import org.briarproject.bramble.api.plugin.event.ConnectionOpenedEvent;
|
||||||
import org.briarproject.bramble.api.plugin.event.TransportDisabledEvent;
|
import org.briarproject.bramble.api.plugin.event.TransportActiveEvent;
|
||||||
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
|
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||||
import org.briarproject.bramble.api.plugin.simplex.SimplexPlugin;
|
import org.briarproject.bramble.api.plugin.simplex.SimplexPlugin;
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler.Cancellable;
|
||||||
import org.briarproject.bramble.test.BrambleMockTestCase;
|
import org.briarproject.bramble.test.BrambleMockTestCase;
|
||||||
import org.briarproject.bramble.test.ImmediateExecutor;
|
import org.briarproject.bramble.test.ImmediateExecutor;
|
||||||
import org.briarproject.bramble.test.RunAction;
|
import org.briarproject.bramble.test.RunAction;
|
||||||
@@ -30,8 +32,6 @@ import org.junit.Test;
|
|||||||
import java.security.SecureRandom;
|
import java.security.SecureRandom;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.concurrent.ScheduledFuture;
|
|
||||||
|
|
||||||
import static java.util.Arrays.asList;
|
import static java.util.Arrays.asList;
|
||||||
import static java.util.Collections.emptyList;
|
import static java.util.Collections.emptyList;
|
||||||
@@ -45,8 +45,7 @@ import static org.briarproject.bramble.test.TestUtils.getTransportId;
|
|||||||
|
|
||||||
public class PollerImplTest extends BrambleMockTestCase {
|
public class PollerImplTest extends BrambleMockTestCase {
|
||||||
|
|
||||||
private final ScheduledExecutorService scheduler =
|
private final TaskScheduler scheduler = context.mock(TaskScheduler.class);
|
||||||
context.mock(ScheduledExecutorService.class);
|
|
||||||
private final ConnectionManager connectionManager =
|
private final ConnectionManager connectionManager =
|
||||||
context.mock(ConnectionManager.class);
|
context.mock(ConnectionManager.class);
|
||||||
private final ConnectionRegistry connectionRegistry =
|
private final ConnectionRegistry connectionRegistry =
|
||||||
@@ -56,10 +55,11 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
private final TransportPropertyManager transportPropertyManager =
|
private final TransportPropertyManager transportPropertyManager =
|
||||||
context.mock(TransportPropertyManager.class);
|
context.mock(TransportPropertyManager.class);
|
||||||
private final Clock clock = context.mock(Clock.class);
|
private final Clock clock = context.mock(Clock.class);
|
||||||
private final ScheduledFuture future = context.mock(ScheduledFuture.class);
|
private final Cancellable cancellable = context.mock(Cancellable.class);
|
||||||
private final SecureRandom random;
|
private final SecureRandom random;
|
||||||
|
|
||||||
private final Executor ioExecutor = new ImmediateExecutor();
|
private final Executor ioExecutor = new ImmediateExecutor();
|
||||||
|
private final Executor wakefulIoExecutor = new ImmediateExecutor();
|
||||||
private final TransportId transportId = getTransportId();
|
private final TransportId transportId = getTransportId();
|
||||||
private final ContactId contactId = getContactId();
|
private final ContactId contactId = getContactId();
|
||||||
private final TransportProperties properties = new TransportProperties();
|
private final TransportProperties properties = new TransportProperties();
|
||||||
@@ -75,9 +75,9 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() {
|
public void setUp() {
|
||||||
poller = new PollerImpl(ioExecutor, scheduler, connectionManager,
|
poller = new PollerImpl(ioExecutor, wakefulIoExecutor, scheduler,
|
||||||
connectionRegistry, pluginManager, transportPropertyManager,
|
connectionManager, connectionRegistry, pluginManager,
|
||||||
random, clock);
|
transportPropertyManager, random, clock);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -235,8 +235,9 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
oneOf(clock).currentTimeMillis();
|
oneOf(clock).currentTimeMillis();
|
||||||
will(returnValue(now));
|
will(returnValue(now));
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with((long) pollingInterval), with(MILLISECONDS));
|
with(ioExecutor), with((long) pollingInterval),
|
||||||
will(returnValue(future));
|
with(MILLISECONDS));
|
||||||
|
will(returnValue(cancellable));
|
||||||
}});
|
}});
|
||||||
|
|
||||||
poller.eventOccurred(new ConnectionOpenedEvent(contactId, transportId,
|
poller.eventOccurred(new ConnectionOpenedEvent(contactId, transportId,
|
||||||
@@ -263,8 +264,9 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
oneOf(clock).currentTimeMillis();
|
oneOf(clock).currentTimeMillis();
|
||||||
will(returnValue(now));
|
will(returnValue(now));
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with((long) pollingInterval), with(MILLISECONDS));
|
with(ioExecutor), with((long) pollingInterval),
|
||||||
will(returnValue(future));
|
with(MILLISECONDS));
|
||||||
|
will(returnValue(cancellable));
|
||||||
// Second event
|
// Second event
|
||||||
// Get the plugin
|
// Get the plugin
|
||||||
oneOf(pluginManager).getPlugin(transportId);
|
oneOf(pluginManager).getPlugin(transportId);
|
||||||
@@ -305,8 +307,9 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
oneOf(clock).currentTimeMillis();
|
oneOf(clock).currentTimeMillis();
|
||||||
will(returnValue(now));
|
will(returnValue(now));
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with((long) pollingInterval), with(MILLISECONDS));
|
with(ioExecutor), with((long) pollingInterval),
|
||||||
will(returnValue(future));
|
with(MILLISECONDS));
|
||||||
|
will(returnValue(cancellable));
|
||||||
// Second event
|
// Second event
|
||||||
// Get the plugin
|
// Get the plugin
|
||||||
oneOf(pluginManager).getPlugin(transportId);
|
oneOf(pluginManager).getPlugin(transportId);
|
||||||
@@ -319,9 +322,10 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
will(returnValue(pollingInterval - 2));
|
will(returnValue(pollingInterval - 2));
|
||||||
oneOf(clock).currentTimeMillis();
|
oneOf(clock).currentTimeMillis();
|
||||||
will(returnValue(now + 1));
|
will(returnValue(now + 1));
|
||||||
oneOf(future).cancel(false);
|
oneOf(cancellable).cancel();
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with((long) pollingInterval - 2), with(MILLISECONDS));
|
with(ioExecutor), with((long) pollingInterval - 2),
|
||||||
|
with(MILLISECONDS));
|
||||||
}});
|
}});
|
||||||
|
|
||||||
poller.eventOccurred(new ConnectionOpenedEvent(contactId, transportId,
|
poller.eventOccurred(new ConnectionOpenedEvent(contactId, transportId,
|
||||||
@@ -331,7 +335,7 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testPollsOnTransportEnabled() throws Exception {
|
public void testPollsOnTransportActivated() throws Exception {
|
||||||
DuplexPlugin plugin = context.mock(DuplexPlugin.class);
|
DuplexPlugin plugin = context.mock(DuplexPlugin.class);
|
||||||
|
|
||||||
context.checking(new Expectations() {{
|
context.checking(new Expectations() {{
|
||||||
@@ -346,9 +350,9 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
// Schedule a polling task immediately
|
// Schedule a polling task immediately
|
||||||
oneOf(clock).currentTimeMillis();
|
oneOf(clock).currentTimeMillis();
|
||||||
will(returnValue(now));
|
will(returnValue(now));
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)), with(0L),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with(MILLISECONDS));
|
with(ioExecutor), with(0L), with(MILLISECONDS));
|
||||||
will(returnValue(future));
|
will(returnValue(cancellable));
|
||||||
will(new RunAction());
|
will(new RunAction());
|
||||||
// Running the polling task schedules the next polling task
|
// Running the polling task schedules the next polling task
|
||||||
oneOf(plugin).getPollingInterval();
|
oneOf(plugin).getPollingInterval();
|
||||||
@@ -358,8 +362,9 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
oneOf(clock).currentTimeMillis();
|
oneOf(clock).currentTimeMillis();
|
||||||
will(returnValue(now));
|
will(returnValue(now));
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with((long) (pollingInterval * 0.5)), with(MILLISECONDS));
|
with(ioExecutor), with((long) (pollingInterval * 0.5)),
|
||||||
will(returnValue(future));
|
with(MILLISECONDS));
|
||||||
|
will(returnValue(cancellable));
|
||||||
// Get the transport properties and connected contacts
|
// Get the transport properties and connected contacts
|
||||||
oneOf(transportPropertyManager).getRemoteProperties(transportId);
|
oneOf(transportPropertyManager).getRemoteProperties(transportId);
|
||||||
will(returnValue(singletonMap(contactId, properties)));
|
will(returnValue(singletonMap(contactId, properties)));
|
||||||
@@ -370,7 +375,7 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
pairOf(equal(properties), any(ConnectionHandler.class)))));
|
pairOf(equal(properties), any(ConnectionHandler.class)))));
|
||||||
}});
|
}});
|
||||||
|
|
||||||
poller.eventOccurred(new TransportEnabledEvent(transportId));
|
poller.eventOccurred(new TransportActiveEvent(transportId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -389,9 +394,9 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
// Schedule a polling task immediately
|
// Schedule a polling task immediately
|
||||||
oneOf(clock).currentTimeMillis();
|
oneOf(clock).currentTimeMillis();
|
||||||
will(returnValue(now));
|
will(returnValue(now));
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)), with(0L),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with(MILLISECONDS));
|
with(ioExecutor), with(0L), with(MILLISECONDS));
|
||||||
will(returnValue(future));
|
will(returnValue(cancellable));
|
||||||
will(new RunAction());
|
will(new RunAction());
|
||||||
// Running the polling task schedules the next polling task
|
// Running the polling task schedules the next polling task
|
||||||
oneOf(plugin).getPollingInterval();
|
oneOf(plugin).getPollingInterval();
|
||||||
@@ -401,8 +406,9 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
oneOf(clock).currentTimeMillis();
|
oneOf(clock).currentTimeMillis();
|
||||||
will(returnValue(now));
|
will(returnValue(now));
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with((long) (pollingInterval * 0.5)), with(MILLISECONDS));
|
with(ioExecutor), with((long) (pollingInterval * 0.5)),
|
||||||
will(returnValue(future));
|
with(MILLISECONDS));
|
||||||
|
will(returnValue(cancellable));
|
||||||
// Get the transport properties and connected contacts
|
// Get the transport properties and connected contacts
|
||||||
oneOf(transportPropertyManager).getRemoteProperties(transportId);
|
oneOf(transportPropertyManager).getRemoteProperties(transportId);
|
||||||
will(returnValue(singletonMap(contactId, properties)));
|
will(returnValue(singletonMap(contactId, properties)));
|
||||||
@@ -411,11 +417,11 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
// All contacts are connected, so don't poll the plugin
|
// All contacts are connected, so don't poll the plugin
|
||||||
}});
|
}});
|
||||||
|
|
||||||
poller.eventOccurred(new TransportEnabledEvent(transportId));
|
poller.eventOccurred(new TransportActiveEvent(transportId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCancelsPollingOnTransportDisabled() {
|
public void testCancelsPollingOnTransportDeactivated() {
|
||||||
Plugin plugin = context.mock(Plugin.class);
|
Plugin plugin = context.mock(Plugin.class);
|
||||||
|
|
||||||
context.checking(new Expectations() {{
|
context.checking(new Expectations() {{
|
||||||
@@ -430,15 +436,15 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
// Schedule a polling task immediately
|
// Schedule a polling task immediately
|
||||||
oneOf(clock).currentTimeMillis();
|
oneOf(clock).currentTimeMillis();
|
||||||
will(returnValue(now));
|
will(returnValue(now));
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)), with(0L),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with(MILLISECONDS));
|
with(ioExecutor), with(0L), with(MILLISECONDS));
|
||||||
will(returnValue(future));
|
will(returnValue(cancellable));
|
||||||
// The plugin is disabled before the task runs - cancel the task
|
// The plugin is deactivated before the task runs - cancel the task
|
||||||
oneOf(future).cancel(false);
|
oneOf(cancellable).cancel();
|
||||||
}});
|
}});
|
||||||
|
|
||||||
poller.eventOccurred(new TransportEnabledEvent(transportId));
|
poller.eventOccurred(new TransportActiveEvent(transportId));
|
||||||
poller.eventOccurred(new TransportDisabledEvent(transportId));
|
poller.eventOccurred(new TransportInactiveEvent(transportId));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void expectReschedule(Plugin plugin) {
|
private void expectReschedule(Plugin plugin) {
|
||||||
@@ -455,8 +461,9 @@ public class PollerImplTest extends BrambleMockTestCase {
|
|||||||
oneOf(clock).currentTimeMillis();
|
oneOf(clock).currentTimeMillis();
|
||||||
will(returnValue(now));
|
will(returnValue(now));
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with((long) pollingInterval), with(MILLISECONDS));
|
with(ioExecutor), with((long) pollingInterval),
|
||||||
will(returnValue(future));
|
with(MILLISECONDS));
|
||||||
|
will(returnValue(cancellable));
|
||||||
}});
|
}});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import org.briarproject.bramble.api.data.BdfList;
|
|||||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
|
import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
|
||||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||||
import org.briarproject.bramble.api.plugin.Backoff;
|
import org.briarproject.bramble.api.plugin.Backoff;
|
||||||
|
import org.briarproject.bramble.api.plugin.Plugin.State;
|
||||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||||
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
|
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
|
||||||
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
||||||
@@ -21,16 +22,19 @@ import java.net.InetSocketAddress;
|
|||||||
import java.net.NetworkInterface;
|
import java.net.NetworkInterface;
|
||||||
import java.net.ServerSocket;
|
import java.net.ServerSocket;
|
||||||
import java.net.Socket;
|
import java.net.Socket;
|
||||||
|
import java.util.Collection;
|
||||||
import java.util.concurrent.CountDownLatch;
|
import java.util.concurrent.CountDownLatch;
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
import static java.net.NetworkInterface.getNetworkInterfaces;
|
import static java.net.NetworkInterface.getNetworkInterfaces;
|
||||||
|
import static java.util.Collections.emptyList;
|
||||||
import static java.util.Collections.list;
|
import static java.util.Collections.list;
|
||||||
import static java.util.concurrent.Executors.newCachedThreadPool;
|
import static java.util.concurrent.Executors.newCachedThreadPool;
|
||||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||||
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.COMMIT_LENGTH;
|
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.COMMIT_LENGTH;
|
||||||
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TRANSPORT_ID_LAN;
|
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TRANSPORT_ID_LAN;
|
||||||
|
import static org.briarproject.bramble.api.plugin.Plugin.PREF_PLUGIN_ENABLE;
|
||||||
import static org.briarproject.bramble.plugin.tcp.LanTcpPlugin.areAddressesInSameNetwork;
|
import static org.briarproject.bramble.plugin.tcp.LanTcpPlugin.areAddressesInSameNetwork;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
@@ -49,7 +53,8 @@ public class LanTcpPluginTest extends BrambleTestCase {
|
|||||||
@Before
|
@Before
|
||||||
public void setUp() {
|
public void setUp() {
|
||||||
callback = new Callback();
|
callback = new Callback();
|
||||||
plugin = new LanTcpPlugin(ioExecutor, backoff, callback, 0, 0, 1000) {
|
plugin = new LanTcpPlugin(ioExecutor, ioExecutor, backoff, callback,
|
||||||
|
0, 0, 1000) {
|
||||||
@Override
|
@Override
|
||||||
protected boolean canConnectToOwnAddress() {
|
protected boolean canConnectToOwnAddress() {
|
||||||
return true;
|
return true;
|
||||||
@@ -302,10 +307,15 @@ public class LanTcpPluginTest extends BrambleTestCase {
|
|||||||
private final CountDownLatch propertiesLatch = new CountDownLatch(2);
|
private final CountDownLatch propertiesLatch = new CountDownLatch(2);
|
||||||
private final CountDownLatch connectionsLatch = new CountDownLatch(1);
|
private final CountDownLatch connectionsLatch = new CountDownLatch(1);
|
||||||
private final TransportProperties local = new TransportProperties();
|
private final TransportProperties local = new TransportProperties();
|
||||||
|
private final Settings settings = new Settings();
|
||||||
|
|
||||||
|
private Callback() {
|
||||||
|
settings.putBoolean(PREF_PLUGIN_ENABLE, true);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Settings getSettings() {
|
public Settings getSettings() {
|
||||||
return new Settings();
|
return settings;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -313,6 +323,11 @@ public class LanTcpPluginTest extends BrambleTestCase {
|
|||||||
return local;
|
return local;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Collection<TransportProperties> getRemoteProperties() {
|
||||||
|
return emptyList();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void mergeSettings(Settings s) {
|
public void mergeSettings(Settings s) {
|
||||||
}
|
}
|
||||||
@@ -324,11 +339,7 @@ public class LanTcpPluginTest extends BrambleTestCase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void transportEnabled() {
|
public void pluginStateChanged(State newState) {
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void transportDisabled() {
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -8,11 +8,15 @@ import org.briarproject.bramble.api.data.BdfDictionary;
|
|||||||
import org.briarproject.bramble.api.data.BdfEntry;
|
import org.briarproject.bramble.api.data.BdfEntry;
|
||||||
import org.briarproject.bramble.api.data.BdfList;
|
import org.briarproject.bramble.api.data.BdfList;
|
||||||
import org.briarproject.bramble.api.data.MetadataParser;
|
import org.briarproject.bramble.api.data.MetadataParser;
|
||||||
|
import org.briarproject.bramble.api.db.CommitAction;
|
||||||
import org.briarproject.bramble.api.db.DatabaseComponent;
|
import org.briarproject.bramble.api.db.DatabaseComponent;
|
||||||
|
import org.briarproject.bramble.api.db.EventAction;
|
||||||
import org.briarproject.bramble.api.db.Metadata;
|
import org.briarproject.bramble.api.db.Metadata;
|
||||||
import org.briarproject.bramble.api.db.Transaction;
|
import org.briarproject.bramble.api.db.Transaction;
|
||||||
|
import org.briarproject.bramble.api.event.Event;
|
||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
|
import org.briarproject.bramble.api.properties.event.RemoteTransportPropertiesUpdatedEvent;
|
||||||
import org.briarproject.bramble.api.sync.Group;
|
import org.briarproject.bramble.api.sync.Group;
|
||||||
import org.briarproject.bramble.api.sync.GroupId;
|
import org.briarproject.bramble.api.sync.GroupId;
|
||||||
import org.briarproject.bramble.api.sync.Message;
|
import org.briarproject.bramble.api.sync.Message;
|
||||||
@@ -45,6 +49,7 @@ import static org.briarproject.bramble.test.TestUtils.getMessage;
|
|||||||
import static org.briarproject.bramble.test.TestUtils.getRandomId;
|
import static org.briarproject.bramble.test.TestUtils.getRandomId;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||||
|
|
||||||
@@ -59,23 +64,28 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
|||||||
private final Clock clock = context.mock(Clock.class);
|
private final Clock clock = context.mock(Clock.class);
|
||||||
|
|
||||||
private final Group localGroup = getGroup(CLIENT_ID, MAJOR_VERSION);
|
private final Group localGroup = getGroup(CLIENT_ID, MAJOR_VERSION);
|
||||||
private final BdfDictionary fooPropertiesDict = BdfDictionary.of(
|
private final BdfDictionary fooPropertiesDict, barPropertiesDict;
|
||||||
new BdfEntry("fooKey1", "fooValue1"),
|
private final BdfDictionary discoveredPropertiesDict, mergedPropertiesDict;
|
||||||
new BdfEntry("fooKey2", "fooValue2")
|
|
||||||
);
|
|
||||||
private final BdfDictionary barPropertiesDict = BdfDictionary.of(
|
|
||||||
new BdfEntry("barKey1", "barValue1"),
|
|
||||||
new BdfEntry("barKey2", "barValue2")
|
|
||||||
);
|
|
||||||
private final TransportProperties fooProperties, barProperties;
|
private final TransportProperties fooProperties, barProperties;
|
||||||
|
private final TransportProperties discoveredProperties;
|
||||||
|
|
||||||
public TransportPropertyManagerImplTest() throws Exception {
|
public TransportPropertyManagerImplTest() {
|
||||||
fooProperties = new TransportProperties();
|
fooProperties = new TransportProperties();
|
||||||
for (String key : fooPropertiesDict.keySet())
|
fooProperties.put("fooKey1", "fooValue1");
|
||||||
fooProperties.put(key, fooPropertiesDict.getString(key));
|
fooProperties.put("fooKey2", "fooValue2");
|
||||||
|
fooPropertiesDict = new BdfDictionary(fooProperties);
|
||||||
|
|
||||||
barProperties = new TransportProperties();
|
barProperties = new TransportProperties();
|
||||||
for (String key : barPropertiesDict.keySet())
|
barProperties.put("barKey1", "barValue1");
|
||||||
barProperties.put(key, barPropertiesDict.getString(key));
|
barProperties.put("barKey2", "barValue2");
|
||||||
|
barPropertiesDict = new BdfDictionary(barProperties);
|
||||||
|
|
||||||
|
discoveredProperties = new TransportProperties();
|
||||||
|
discoveredProperties.put("fooKey3", "fooValue3");
|
||||||
|
discoveredPropertiesDict = new BdfDictionary(discoveredProperties);
|
||||||
|
|
||||||
|
mergedPropertiesDict = new BdfDictionary(fooProperties);
|
||||||
|
mergedPropertiesDict.put("u:fooKey3", "fooValue3");
|
||||||
}
|
}
|
||||||
|
|
||||||
private TransportPropertyManagerImpl createInstance() {
|
private TransportPropertyManagerImpl createInstance() {
|
||||||
@@ -221,6 +231,7 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
|||||||
|
|
||||||
TransportPropertyManagerImpl t = createInstance();
|
TransportPropertyManagerImpl t = createInstance();
|
||||||
assertFalse(t.incomingMessage(txn, message, meta));
|
assertFalse(t.incomingMessage(txn, message, meta));
|
||||||
|
assertTrue(hasEvent(txn, RemoteTransportPropertiesUpdatedEvent.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -259,6 +270,7 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
|||||||
|
|
||||||
TransportPropertyManagerImpl t = createInstance();
|
TransportPropertyManagerImpl t = createInstance();
|
||||||
assertFalse(t.incomingMessage(txn, message, meta));
|
assertFalse(t.incomingMessage(txn, message, meta));
|
||||||
|
assertTrue(hasEvent(txn, RemoteTransportPropertiesUpdatedEvent.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -292,10 +304,12 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
|||||||
// The update being delivered (version 3) should be deleted
|
// The update being delivered (version 3) should be deleted
|
||||||
oneOf(db).deleteMessage(txn, message.getId());
|
oneOf(db).deleteMessage(txn, message.getId());
|
||||||
oneOf(db).deleteMessageMetadata(txn, message.getId());
|
oneOf(db).deleteMessageMetadata(txn, message.getId());
|
||||||
|
// No event should be broadcast
|
||||||
}});
|
}});
|
||||||
|
|
||||||
TransportPropertyManagerImpl t = createInstance();
|
TransportPropertyManagerImpl t = createInstance();
|
||||||
assertFalse(t.incomingMessage(txn, message, meta));
|
assertFalse(t.incomingMessage(txn, message, meta));
|
||||||
|
assertFalse(hasEvent(txn, RemoteTransportPropertiesUpdatedEvent.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -566,6 +580,10 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
|||||||
Contact contact = getContact();
|
Contact contact = getContact();
|
||||||
Group contactGroup = getGroup(CLIENT_ID, MAJOR_VERSION);
|
Group contactGroup = getGroup(CLIENT_ID, MAJOR_VERSION);
|
||||||
|
|
||||||
|
// Property with an empty value should be discarded
|
||||||
|
TransportProperties properties = new TransportProperties(fooProperties);
|
||||||
|
properties.put("fooKey3", "");
|
||||||
|
|
||||||
context.checking(new DbExpectations() {{
|
context.checking(new DbExpectations() {{
|
||||||
oneOf(db).transaction(with(false), withDbRunnable(txn));
|
oneOf(db).transaction(with(false), withDbRunnable(txn));
|
||||||
// There are no existing properties to merge with
|
// There are no existing properties to merge with
|
||||||
@@ -584,10 +602,56 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
|||||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||||
contactGroup.getId());
|
contactGroup.getId());
|
||||||
will(returnValue(emptyMap()));
|
will(returnValue(emptyMap()));
|
||||||
|
oneOf(clientHelper).getGroupMetadataAsDictionary(txn,
|
||||||
|
contactGroup.getId());
|
||||||
|
will(returnValue(new BdfDictionary()));
|
||||||
expectStoreMessage(txn, contactGroup.getId(), "foo",
|
expectStoreMessage(txn, contactGroup.getId(), "foo",
|
||||||
fooPropertiesDict, 1, true, true);
|
fooPropertiesDict, 1, true, true);
|
||||||
}});
|
}});
|
||||||
|
|
||||||
|
TransportPropertyManagerImpl t = createInstance();
|
||||||
|
t.mergeLocalProperties(new TransportId("foo"), properties);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testMergingNewPropertiesCreatesUpdateWithReflectedProperties()
|
||||||
|
throws Exception {
|
||||||
|
Transaction txn = new Transaction(null, false);
|
||||||
|
Contact contact = getContact();
|
||||||
|
Group contactGroup = getGroup(CLIENT_ID, MAJOR_VERSION);
|
||||||
|
BdfDictionary contactGroupMeta = BdfDictionary.of(
|
||||||
|
new BdfEntry(GROUP_KEY_DISCOVERED, discoveredPropertiesDict)
|
||||||
|
);
|
||||||
|
|
||||||
|
context.checking(new DbExpectations() {{
|
||||||
|
oneOf(db).transaction(with(false), withDbRunnable(txn));
|
||||||
|
// There are no existing properties to merge with
|
||||||
|
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||||
|
localGroup.getId());
|
||||||
|
will(returnValue(emptyMap()));
|
||||||
|
// Store the new properties in the local group, version 1
|
||||||
|
expectStoreMessage(txn, localGroup.getId(), "foo",
|
||||||
|
fooPropertiesDict, 1, true, false);
|
||||||
|
// Store the new properties in each contact's group, version 1
|
||||||
|
oneOf(db).getContacts(txn);
|
||||||
|
will(returnValue(singletonList(contact)));
|
||||||
|
oneOf(contactGroupFactory).createContactGroup(CLIENT_ID,
|
||||||
|
MAJOR_VERSION, contact);
|
||||||
|
will(returnValue(contactGroup));
|
||||||
|
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||||
|
contactGroup.getId());
|
||||||
|
will(returnValue(emptyMap()));
|
||||||
|
oneOf(clientHelper).getGroupMetadataAsDictionary(txn,
|
||||||
|
contactGroup.getId());
|
||||||
|
will(returnValue(contactGroupMeta));
|
||||||
|
// Reflect discovered properties
|
||||||
|
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||||
|
discoveredPropertiesDict);
|
||||||
|
will(returnValue(discoveredProperties));
|
||||||
|
expectStoreMessage(txn, contactGroup.getId(), "foo",
|
||||||
|
mergedPropertiesDict, 1, true, true);
|
||||||
|
}});
|
||||||
|
|
||||||
TransportPropertyManagerImpl t = createInstance();
|
TransportPropertyManagerImpl t = createInstance();
|
||||||
t.mergeLocalProperties(new TransportId("foo"), fooProperties);
|
t.mergeLocalProperties(new TransportId("foo"), fooProperties);
|
||||||
}
|
}
|
||||||
@@ -603,6 +667,79 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
|||||||
new BdfEntry(MSG_KEY_LOCAL, true)
|
new BdfEntry(MSG_KEY_LOCAL, true)
|
||||||
);
|
);
|
||||||
MessageId localGroupUpdateId = new MessageId(getRandomId());
|
MessageId localGroupUpdateId = new MessageId(getRandomId());
|
||||||
|
Map<MessageId, BdfDictionary> localGroupMessageMetadata =
|
||||||
|
singletonMap(localGroupUpdateId, oldMetadata);
|
||||||
|
|
||||||
|
MessageId contactGroupUpdateId = new MessageId(getRandomId());
|
||||||
|
Map<MessageId, BdfDictionary> contactGroupMessageMetadata =
|
||||||
|
singletonMap(contactGroupUpdateId, oldMetadata);
|
||||||
|
|
||||||
|
TransportProperties oldProperties = new TransportProperties();
|
||||||
|
oldProperties.put("fooKey1", "oldFooValue1");
|
||||||
|
oldProperties.put("fooKey3", "oldFooValue3");
|
||||||
|
BdfDictionary oldPropertiesDict = BdfDictionary.of(
|
||||||
|
new BdfEntry("fooKey1", "oldFooValue1"),
|
||||||
|
new BdfEntry("fooKey3", "oldFooValue3")
|
||||||
|
);
|
||||||
|
BdfList oldUpdate = BdfList.of("foo", 1, oldPropertiesDict);
|
||||||
|
|
||||||
|
// Property assigned an empty value should be removed
|
||||||
|
TransportProperties properties = new TransportProperties(fooProperties);
|
||||||
|
properties.put("fooKey3", "");
|
||||||
|
|
||||||
|
context.checking(new DbExpectations() {{
|
||||||
|
oneOf(db).transaction(with(false), withDbRunnable(txn));
|
||||||
|
// Merge the new properties with the existing properties
|
||||||
|
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||||
|
localGroup.getId());
|
||||||
|
will(returnValue(localGroupMessageMetadata));
|
||||||
|
oneOf(clientHelper).getMessageAsList(txn, localGroupUpdateId);
|
||||||
|
will(returnValue(oldUpdate));
|
||||||
|
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||||
|
oldPropertiesDict);
|
||||||
|
will(returnValue(oldProperties));
|
||||||
|
// Store the merged properties in the local group, version 2
|
||||||
|
expectStoreMessage(txn, localGroup.getId(), "foo",
|
||||||
|
fooPropertiesDict, 2, true, false);
|
||||||
|
// Delete the previous update
|
||||||
|
oneOf(db).removeMessage(txn, localGroupUpdateId);
|
||||||
|
// Store the merged properties in each contact's group, version 2
|
||||||
|
oneOf(db).getContacts(txn);
|
||||||
|
will(returnValue(singletonList(contact)));
|
||||||
|
oneOf(contactGroupFactory).createContactGroup(CLIENT_ID,
|
||||||
|
MAJOR_VERSION, contact);
|
||||||
|
will(returnValue(contactGroup));
|
||||||
|
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||||
|
contactGroup.getId());
|
||||||
|
will(returnValue(contactGroupMessageMetadata));
|
||||||
|
oneOf(clientHelper).getGroupMetadataAsDictionary(txn,
|
||||||
|
contactGroup.getId());
|
||||||
|
will(returnValue(new BdfDictionary()));
|
||||||
|
expectStoreMessage(txn, contactGroup.getId(), "foo",
|
||||||
|
fooPropertiesDict, 2, true, true);
|
||||||
|
// Delete the previous update
|
||||||
|
oneOf(db).removeMessage(txn, contactGroupUpdateId);
|
||||||
|
}});
|
||||||
|
|
||||||
|
TransportPropertyManagerImpl t = createInstance();
|
||||||
|
t.mergeLocalProperties(new TransportId("foo"), properties);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testMergingUpdatedPropertiesCreatesUpdateWithReflectedProperties()
|
||||||
|
throws Exception {
|
||||||
|
Transaction txn = new Transaction(null, false);
|
||||||
|
Contact contact = getContact();
|
||||||
|
Group contactGroup = getGroup(CLIENT_ID, MAJOR_VERSION);
|
||||||
|
BdfDictionary contactGroupMeta = BdfDictionary.of(
|
||||||
|
new BdfEntry(GROUP_KEY_DISCOVERED, discoveredPropertiesDict)
|
||||||
|
);
|
||||||
|
BdfDictionary oldMetadata = BdfDictionary.of(
|
||||||
|
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||||
|
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||||
|
new BdfEntry(MSG_KEY_LOCAL, true)
|
||||||
|
);
|
||||||
|
MessageId localGroupUpdateId = new MessageId(getRandomId());
|
||||||
Map<MessageId, BdfDictionary> localGroupMessageMetadata =
|
Map<MessageId, BdfDictionary> localGroupMessageMetadata =
|
||||||
singletonMap(localGroupUpdateId, oldMetadata);
|
singletonMap(localGroupUpdateId, oldMetadata);
|
||||||
MessageId contactGroupUpdateId = new MessageId(getRandomId());
|
MessageId contactGroupUpdateId = new MessageId(getRandomId());
|
||||||
@@ -640,8 +777,15 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
|||||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||||
contactGroup.getId());
|
contactGroup.getId());
|
||||||
will(returnValue(contactGroupMessageMetadata));
|
will(returnValue(contactGroupMessageMetadata));
|
||||||
|
oneOf(clientHelper).getGroupMetadataAsDictionary(txn,
|
||||||
|
contactGroup.getId());
|
||||||
|
will(returnValue(contactGroupMeta));
|
||||||
|
// Reflect discovered properties
|
||||||
|
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||||
|
discoveredPropertiesDict);
|
||||||
|
will(returnValue(discoveredProperties));
|
||||||
expectStoreMessage(txn, contactGroup.getId(), "foo",
|
expectStoreMessage(txn, contactGroup.getId(), "foo",
|
||||||
fooPropertiesDict, 2, true, true);
|
mergedPropertiesDict, 2, true, true);
|
||||||
// Delete the previous update
|
// Delete the previous update
|
||||||
oneOf(db).removeMessage(txn, contactGroupUpdateId);
|
oneOf(db).removeMessage(txn, contactGroupUpdateId);
|
||||||
}});
|
}});
|
||||||
@@ -707,4 +851,15 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
|||||||
false);
|
false);
|
||||||
}});
|
}});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean hasEvent(Transaction txn,
|
||||||
|
Class<? extends Event> eventClass) {
|
||||||
|
for (CommitAction action : txn.getActions()) {
|
||||||
|
if (action instanceof EventAction) {
|
||||||
|
Event event = ((EventAction) action).getEvent();
|
||||||
|
if (eventClass.isInstance(event)) return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ import org.briarproject.bramble.api.plugin.ConnectionHandler;
|
|||||||
import org.briarproject.bramble.api.plugin.PluginManager;
|
import org.briarproject.bramble.api.plugin.PluginManager;
|
||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||||
import org.briarproject.bramble.api.plugin.event.TransportDisabledEvent;
|
import org.briarproject.bramble.api.plugin.event.TransportActiveEvent;
|
||||||
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
|
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||||
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
||||||
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
||||||
@@ -26,6 +26,8 @@ import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionClosedE
|
|||||||
import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionOpenedEvent;
|
import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionOpenedEvent;
|
||||||
import org.briarproject.bramble.api.rendezvous.event.RendezvousPollEvent;
|
import org.briarproject.bramble.api.rendezvous.event.RendezvousPollEvent;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler.Cancellable;
|
||||||
import org.briarproject.bramble.test.BrambleMockTestCase;
|
import org.briarproject.bramble.test.BrambleMockTestCase;
|
||||||
import org.briarproject.bramble.test.CaptureArgumentAction;
|
import org.briarproject.bramble.test.CaptureArgumentAction;
|
||||||
import org.briarproject.bramble.test.DbExpectations;
|
import org.briarproject.bramble.test.DbExpectations;
|
||||||
@@ -37,7 +39,6 @@ import org.junit.Test;
|
|||||||
|
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
import java.util.concurrent.atomic.AtomicReference;
|
||||||
|
|
||||||
import static java.util.Collections.emptyList;
|
import static java.util.Collections.emptyList;
|
||||||
@@ -60,8 +61,7 @@ import static org.briarproject.bramble.test.TestUtils.getTransportProperties;
|
|||||||
|
|
||||||
public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||||
|
|
||||||
private final ScheduledExecutorService scheduler =
|
private final TaskScheduler scheduler = context.mock(TaskScheduler.class);
|
||||||
context.mock(ScheduledExecutorService.class);
|
|
||||||
private final DatabaseComponent db = context.mock(DatabaseComponent.class);
|
private final DatabaseComponent db = context.mock(DatabaseComponent.class);
|
||||||
private final IdentityManager identityManager =
|
private final IdentityManager identityManager =
|
||||||
context.mock(IdentityManager.class);
|
context.mock(IdentityManager.class);
|
||||||
@@ -80,6 +80,7 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
context.mock(KeyMaterialSource.class);
|
context.mock(KeyMaterialSource.class);
|
||||||
private final RendezvousEndpoint rendezvousEndpoint =
|
private final RendezvousEndpoint rendezvousEndpoint =
|
||||||
context.mock(RendezvousEndpoint.class);
|
context.mock(RendezvousEndpoint.class);
|
||||||
|
private final Cancellable cancellable = context.mock(Cancellable.class);
|
||||||
|
|
||||||
private final Executor ioExecutor = new ImmediateExecutor();
|
private final Executor ioExecutor = new ImmediateExecutor();
|
||||||
private final PendingContact pendingContact = getPendingContact();
|
private final PendingContact pendingContact = getPendingContact();
|
||||||
@@ -108,7 +109,7 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
long beforeExpiry = pendingContact.getTimestamp()
|
long beforeExpiry = pendingContact.getTimestamp()
|
||||||
+ RENDEZVOUS_TIMEOUT_MS - 1000;
|
+ RENDEZVOUS_TIMEOUT_MS - 1000;
|
||||||
long afterExpiry = beforeExpiry + POLLING_INTERVAL_MS;
|
long afterExpiry = beforeExpiry + POLLING_INTERVAL_MS;
|
||||||
AtomicReference<Runnable> capturePollTask = new AtomicReference<>();
|
AtomicReference<Runnable> capturePollTask;
|
||||||
|
|
||||||
// Start the service
|
// Start the service
|
||||||
context.checking(new DbExpectations() {{
|
context.checking(new DbExpectations() {{
|
||||||
@@ -122,21 +123,17 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
oneOf(eventBus).broadcast(with(new PredicateMatcher<>(
|
oneOf(eventBus).broadcast(with(new PredicateMatcher<>(
|
||||||
PendingContactStateChangedEvent.class, e ->
|
PendingContactStateChangedEvent.class, e ->
|
||||||
e.getPendingContactState() == OFFLINE)));
|
e.getPendingContactState() == OFFLINE)));
|
||||||
// Capture the poll task
|
|
||||||
oneOf(scheduler).scheduleAtFixedRate(with(any(Runnable.class)),
|
|
||||||
with(POLLING_INTERVAL_MS), with(POLLING_INTERVAL_MS),
|
|
||||||
with(MILLISECONDS));
|
|
||||||
will(new CaptureArgumentAction<>(capturePollTask, Runnable.class,
|
|
||||||
0));
|
|
||||||
}});
|
}});
|
||||||
|
|
||||||
expectDeriveRendezvousKey();
|
expectDeriveRendezvousKey();
|
||||||
|
capturePollTask = expectSchedulePolling();
|
||||||
|
|
||||||
rendezvousPoller.startService();
|
rendezvousPoller.startService();
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Run the poll task - pending contact expires
|
// Run the poll task - pending contact expires, polling is cancelled
|
||||||
expectPendingContactExpires(afterExpiry);
|
expectPendingContactExpires(afterExpiry);
|
||||||
|
expectCancelPolling();
|
||||||
|
|
||||||
capturePollTask.get().run();
|
capturePollTask.get().run();
|
||||||
}
|
}
|
||||||
@@ -158,10 +155,6 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
oneOf(eventBus).broadcast(with(new PredicateMatcher<>(
|
oneOf(eventBus).broadcast(with(new PredicateMatcher<>(
|
||||||
PendingContactStateChangedEvent.class, e ->
|
PendingContactStateChangedEvent.class, e ->
|
||||||
e.getPendingContactState() == FAILED)));
|
e.getPendingContactState() == FAILED)));
|
||||||
// Schedule the poll task
|
|
||||||
oneOf(scheduler).scheduleAtFixedRate(with(any(Runnable.class)),
|
|
||||||
with(POLLING_INTERVAL_MS), with(POLLING_INTERVAL_MS),
|
|
||||||
with(MILLISECONDS));
|
|
||||||
}});
|
}});
|
||||||
|
|
||||||
rendezvousPoller.startService();
|
rendezvousPoller.startService();
|
||||||
@@ -178,13 +171,14 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
rendezvousPoller.startService();
|
rendezvousPoller.startService();
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Enable the transport - no endpoints should be created yet
|
// Activate the transport - no endpoints should be created yet
|
||||||
expectGetPlugin();
|
expectGetPlugin();
|
||||||
|
|
||||||
rendezvousPoller.eventOccurred(new TransportEnabledEvent(transportId));
|
rendezvousPoller.eventOccurred(new TransportActiveEvent(transportId));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Add the pending contact - endpoint should be created and polled
|
// Add the pending contact - endpoint should be created and polled,
|
||||||
|
// polling should be scheduled
|
||||||
expectAddPendingContact(beforeExpiry, WAITING_FOR_CONNECTION);
|
expectAddPendingContact(beforeExpiry, WAITING_FOR_CONNECTION);
|
||||||
expectDeriveRendezvousKey();
|
expectDeriveRendezvousKey();
|
||||||
expectCreateEndpoint();
|
expectCreateEndpoint();
|
||||||
@@ -201,19 +195,23 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
any(ConnectionHandler.class)))));
|
any(ConnectionHandler.class)))));
|
||||||
}});
|
}});
|
||||||
|
|
||||||
|
expectSchedulePolling();
|
||||||
|
|
||||||
rendezvousPoller.eventOccurred(
|
rendezvousPoller.eventOccurred(
|
||||||
new PendingContactAddedEvent(pendingContact));
|
new PendingContactAddedEvent(pendingContact));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Remove the pending contact - endpoint should be closed
|
// Remove the pending contact - endpoint should be closed,
|
||||||
|
// polling should be cancelled
|
||||||
expectCloseEndpoint();
|
expectCloseEndpoint();
|
||||||
|
expectCancelPolling();
|
||||||
|
|
||||||
rendezvousPoller.eventOccurred(
|
rendezvousPoller.eventOccurred(
|
||||||
new PendingContactRemovedEvent(pendingContact.getId()));
|
new PendingContactRemovedEvent(pendingContact.getId()));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Disable the transport - endpoint is already closed
|
// Deactivate the transport - endpoint is already closed
|
||||||
rendezvousPoller.eventOccurred(new TransportDisabledEvent(transportId));
|
rendezvousPoller.eventOccurred(new TransportInactiveEvent(transportId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -222,21 +220,22 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
long beforeExpiry = pendingContact.getTimestamp()
|
long beforeExpiry = pendingContact.getTimestamp()
|
||||||
+ RENDEZVOUS_TIMEOUT_MS - 1000;
|
+ RENDEZVOUS_TIMEOUT_MS - 1000;
|
||||||
long afterExpiry = beforeExpiry + POLLING_INTERVAL_MS;
|
long afterExpiry = beforeExpiry + POLLING_INTERVAL_MS;
|
||||||
|
AtomicReference<Runnable> capturePollTask;
|
||||||
|
|
||||||
// Start the service, capturing the poll task
|
// Start the service
|
||||||
AtomicReference<Runnable> capturePollTask =
|
expectStartupWithNoPendingContacts();
|
||||||
expectStartupWithNoPendingContacts();
|
|
||||||
|
|
||||||
rendezvousPoller.startService();
|
rendezvousPoller.startService();
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Enable the transport - no endpoints should be created yet
|
// Activate the transport - no endpoints should be created yet
|
||||||
expectGetPlugin();
|
expectGetPlugin();
|
||||||
|
|
||||||
rendezvousPoller.eventOccurred(new TransportEnabledEvent(transportId));
|
rendezvousPoller.eventOccurred(new TransportActiveEvent(transportId));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Add the pending contact - endpoint should be created and polled
|
// Add the pending contact - endpoint should be created and polled,
|
||||||
|
// polling should be scheduled
|
||||||
expectAddPendingContact(beforeExpiry, WAITING_FOR_CONNECTION);
|
expectAddPendingContact(beforeExpiry, WAITING_FOR_CONNECTION);
|
||||||
expectDeriveRendezvousKey();
|
expectDeriveRendezvousKey();
|
||||||
expectCreateEndpoint();
|
expectCreateEndpoint();
|
||||||
@@ -253,13 +252,17 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
any(ConnectionHandler.class)))));
|
any(ConnectionHandler.class)))));
|
||||||
}});
|
}});
|
||||||
|
|
||||||
|
capturePollTask = expectSchedulePolling();
|
||||||
|
|
||||||
rendezvousPoller.eventOccurred(
|
rendezvousPoller.eventOccurred(
|
||||||
new PendingContactAddedEvent(pendingContact));
|
new PendingContactAddedEvent(pendingContact));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Run the poll task - pending contact expires, endpoint is closed
|
// Run the poll task - pending contact expires, endpoint is closed,
|
||||||
|
// polling is cancelled
|
||||||
expectPendingContactExpires(afterExpiry);
|
expectPendingContactExpires(afterExpiry);
|
||||||
expectCloseEndpoint();
|
expectCloseEndpoint();
|
||||||
|
expectCancelPolling();
|
||||||
|
|
||||||
capturePollTask.get().run();
|
capturePollTask.get().run();
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
@@ -269,12 +272,12 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
new PendingContactRemovedEvent(pendingContact.getId()));
|
new PendingContactRemovedEvent(pendingContact.getId()));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Disable the transport - endpoint is already closed
|
// Deactivate the transport - endpoint is already closed
|
||||||
rendezvousPoller.eventOccurred(new TransportDisabledEvent(transportId));
|
rendezvousPoller.eventOccurred(new TransportInactiveEvent(transportId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCreatesAndClosesEndpointsWhenTransportIsEnabledAndDisabled()
|
public void testCreatesAndClosesEndpointsWhenTransportIsActivatedAndDeactivated()
|
||||||
throws Exception {
|
throws Exception {
|
||||||
long beforeExpiry = pendingContact.getTimestamp();
|
long beforeExpiry = pendingContact.getTimestamp();
|
||||||
|
|
||||||
@@ -287,27 +290,30 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
// Add the pending contact - no endpoints should be created yet
|
// Add the pending contact - no endpoints should be created yet
|
||||||
expectAddPendingContact(beforeExpiry, OFFLINE);
|
expectAddPendingContact(beforeExpiry, OFFLINE);
|
||||||
expectDeriveRendezvousKey();
|
expectDeriveRendezvousKey();
|
||||||
|
expectSchedulePolling();
|
||||||
|
|
||||||
rendezvousPoller.eventOccurred(
|
rendezvousPoller.eventOccurred(
|
||||||
new PendingContactAddedEvent(pendingContact));
|
new PendingContactAddedEvent(pendingContact));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Enable the transport - endpoint should be created
|
// Activate the transport - endpoint should be created
|
||||||
expectGetPlugin();
|
expectGetPlugin();
|
||||||
expectCreateEndpoint();
|
expectCreateEndpoint();
|
||||||
expectStateChangedEvent(WAITING_FOR_CONNECTION);
|
expectStateChangedEvent(WAITING_FOR_CONNECTION);
|
||||||
|
|
||||||
rendezvousPoller.eventOccurred(new TransportEnabledEvent(transportId));
|
rendezvousPoller.eventOccurred(new TransportActiveEvent(transportId));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Disable the transport - endpoint should be closed
|
// Deactivate the transport - endpoint should be closed
|
||||||
expectCloseEndpoint();
|
expectCloseEndpoint();
|
||||||
expectStateChangedEvent(OFFLINE);
|
expectStateChangedEvent(OFFLINE);
|
||||||
|
|
||||||
rendezvousPoller.eventOccurred(new TransportDisabledEvent(transportId));
|
rendezvousPoller.eventOccurred(new TransportInactiveEvent(transportId));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Remove the pending contact - endpoint is already closed
|
// Remove the pending contact - endpoint is already closed
|
||||||
|
expectCancelPolling();
|
||||||
|
|
||||||
rendezvousPoller.eventOccurred(
|
rendezvousPoller.eventOccurred(
|
||||||
new PendingContactRemovedEvent(pendingContact.getId()));
|
new PendingContactRemovedEvent(pendingContact.getId()));
|
||||||
}
|
}
|
||||||
@@ -349,8 +355,9 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
rendezvousPoller.startService();
|
rendezvousPoller.startService();
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Run the poll task - pending contact expires
|
// Run the poll task - pending contact expires, polling is cancelled
|
||||||
expectPendingContactExpires(afterExpiry);
|
expectPendingContactExpires(afterExpiry);
|
||||||
|
expectCancelPolling();
|
||||||
|
|
||||||
capturePollTask.get().run();
|
capturePollTask.get().run();
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
@@ -386,8 +393,9 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
new RendezvousConnectionOpenedEvent(pendingContact.getId()));
|
new RendezvousConnectionOpenedEvent(pendingContact.getId()));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Run the poll task - pending contact expires
|
// Run the poll task - pending contact expires, polling is cancelled
|
||||||
expectPendingContactExpires(afterExpiry);
|
expectPendingContactExpires(afterExpiry);
|
||||||
|
expectCancelPolling();
|
||||||
|
|
||||||
capturePollTask.get().run();
|
capturePollTask.get().run();
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
@@ -418,8 +426,9 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
new RendezvousConnectionOpenedEvent(pendingContact.getId()));
|
new RendezvousConnectionOpenedEvent(pendingContact.getId()));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Run the poll task - pending contact expires
|
// Run the poll task - pending contact expires, polling is cancelled
|
||||||
expectPendingContactExpires(afterExpiry);
|
expectPendingContactExpires(afterExpiry);
|
||||||
|
expectCancelPolling();
|
||||||
|
|
||||||
capturePollTask.get().run();
|
capturePollTask.get().run();
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
@@ -448,6 +457,8 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
|
|
||||||
// Pending contact is removed - no event should be broadcast
|
// Pending contact is removed - no event should be broadcast
|
||||||
|
expectCancelPolling();
|
||||||
|
|
||||||
rendezvousPoller.eventOccurred(
|
rendezvousPoller.eventOccurred(
|
||||||
new PendingContactRemovedEvent(pendingContact.getId()));
|
new PendingContactRemovedEvent(pendingContact.getId()));
|
||||||
context.assertIsSatisfied();
|
context.assertIsSatisfied();
|
||||||
@@ -457,25 +468,35 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
pendingContact.getId(), false));
|
pendingContact.getId(), false));
|
||||||
}
|
}
|
||||||
|
|
||||||
private AtomicReference<Runnable> expectStartupWithNoPendingContacts()
|
private AtomicReference<Runnable> expectSchedulePolling() {
|
||||||
throws Exception {
|
|
||||||
Transaction txn = new Transaction(null, true);
|
|
||||||
AtomicReference<Runnable> capturePollTask = new AtomicReference<>();
|
AtomicReference<Runnable> capturePollTask = new AtomicReference<>();
|
||||||
|
|
||||||
|
context.checking(new Expectations() {{
|
||||||
|
oneOf(scheduler).scheduleWithFixedDelay(with(any(Runnable.class)),
|
||||||
|
with(any(Executor.class)), with(POLLING_INTERVAL_MS),
|
||||||
|
with(POLLING_INTERVAL_MS), with(MILLISECONDS));
|
||||||
|
will(doAll(new CaptureArgumentAction<>(capturePollTask,
|
||||||
|
Runnable.class, 0), returnValue(cancellable)));
|
||||||
|
}});
|
||||||
|
|
||||||
|
return capturePollTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void expectCancelPolling() {
|
||||||
|
context.checking(new Expectations() {{
|
||||||
|
oneOf(cancellable).cancel();
|
||||||
|
}});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void expectStartupWithNoPendingContacts() throws Exception {
|
||||||
|
Transaction txn = new Transaction(null, true);
|
||||||
|
|
||||||
context.checking(new DbExpectations() {{
|
context.checking(new DbExpectations() {{
|
||||||
// Load the pending contacts
|
// Load the pending contacts
|
||||||
oneOf(db).transaction(with(true), withDbRunnable(txn));
|
oneOf(db).transaction(with(true), withDbRunnable(txn));
|
||||||
oneOf(db).getPendingContacts(txn);
|
oneOf(db).getPendingContacts(txn);
|
||||||
will(returnValue(emptyList()));
|
will(returnValue(emptyList()));
|
||||||
// Capture the poll task
|
|
||||||
oneOf(scheduler).scheduleAtFixedRate(with(any(Runnable.class)),
|
|
||||||
with(POLLING_INTERVAL_MS), with(POLLING_INTERVAL_MS),
|
|
||||||
with(MILLISECONDS));
|
|
||||||
will(new CaptureArgumentAction<>(capturePollTask, Runnable.class,
|
|
||||||
0));
|
|
||||||
}});
|
}});
|
||||||
|
|
||||||
return capturePollTask;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void expectAddPendingContact(long now,
|
private void expectAddPendingContact(long now,
|
||||||
@@ -531,7 +552,6 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
private AtomicReference<Runnable> expectStartupWithPendingContact(long now)
|
private AtomicReference<Runnable> expectStartupWithPendingContact(long now)
|
||||||
throws Exception {
|
throws Exception {
|
||||||
Transaction txn = new Transaction(null, true);
|
Transaction txn = new Transaction(null, true);
|
||||||
AtomicReference<Runnable> capturePollTask = new AtomicReference<>();
|
|
||||||
|
|
||||||
context.checking(new DbExpectations() {{
|
context.checking(new DbExpectations() {{
|
||||||
// Load the pending contacts
|
// Load the pending contacts
|
||||||
@@ -544,17 +564,10 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
|||||||
oneOf(eventBus).broadcast(with(new PredicateMatcher<>(
|
oneOf(eventBus).broadcast(with(new PredicateMatcher<>(
|
||||||
PendingContactStateChangedEvent.class, e ->
|
PendingContactStateChangedEvent.class, e ->
|
||||||
e.getPendingContactState() == OFFLINE)));
|
e.getPendingContactState() == OFFLINE)));
|
||||||
// Capture the poll task
|
|
||||||
oneOf(scheduler).scheduleAtFixedRate(with(any(Runnable.class)),
|
|
||||||
with(POLLING_INTERVAL_MS), with(POLLING_INTERVAL_MS),
|
|
||||||
with(MILLISECONDS));
|
|
||||||
will(new CaptureArgumentAction<>(capturePollTask, Runnable.class,
|
|
||||||
0));
|
|
||||||
}});
|
}});
|
||||||
|
|
||||||
expectDeriveRendezvousKey();
|
expectDeriveRendezvousKey();
|
||||||
|
return expectSchedulePolling();
|
||||||
return capturePollTask;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void expectPendingContactExpires(long now) {
|
private void expectPendingContactExpires(long now) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package org.briarproject.bramble.sync;
|
package org.briarproject.bramble.sync;
|
||||||
|
|
||||||
import org.briarproject.bramble.BrambleCoreEagerSingletons;
|
import org.briarproject.bramble.BrambleCoreIntegrationTestEagerSingletons;
|
||||||
import org.briarproject.bramble.api.contact.ContactId;
|
import org.briarproject.bramble.api.contact.ContactId;
|
||||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||||
import org.briarproject.bramble.api.crypto.TransportCrypto;
|
import org.briarproject.bramble.api.crypto.TransportCrypto;
|
||||||
@@ -73,7 +73,8 @@ public class SyncIntegrationTest extends BrambleTestCase {
|
|||||||
|
|
||||||
SyncIntegrationTestComponent component =
|
SyncIntegrationTestComponent component =
|
||||||
DaggerSyncIntegrationTestComponent.builder().build();
|
DaggerSyncIntegrationTestComponent.builder().build();
|
||||||
BrambleCoreEagerSingletons.Helper.injectEagerSingletons(component);
|
BrambleCoreIntegrationTestEagerSingletons.Helper
|
||||||
|
.injectEagerSingletons(component);
|
||||||
component.inject(this);
|
component.inject(this);
|
||||||
|
|
||||||
contactId = getContactId();
|
contactId = getContactId();
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package org.briarproject.bramble.sync;
|
package org.briarproject.bramble.sync;
|
||||||
|
|
||||||
import org.briarproject.bramble.BrambleCoreEagerSingletons;
|
import org.briarproject.bramble.BrambleCoreIntegrationTestEagerSingletons;
|
||||||
import org.briarproject.bramble.BrambleCoreModule;
|
import org.briarproject.bramble.BrambleCoreModule;
|
||||||
import org.briarproject.bramble.test.BrambleCoreIntegrationTestModule;
|
import org.briarproject.bramble.test.BrambleCoreIntegrationTestModule;
|
||||||
|
|
||||||
@@ -13,7 +13,8 @@ import dagger.Component;
|
|||||||
BrambleCoreIntegrationTestModule.class,
|
BrambleCoreIntegrationTestModule.class,
|
||||||
BrambleCoreModule.class
|
BrambleCoreModule.class
|
||||||
})
|
})
|
||||||
interface SyncIntegrationTestComponent extends BrambleCoreEagerSingletons {
|
interface SyncIntegrationTestComponent extends
|
||||||
|
BrambleCoreIntegrationTestEagerSingletons {
|
||||||
|
|
||||||
void inject(SyncIntegrationTest testCase);
|
void inject(SyncIntegrationTest testCase);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package org.briarproject.bramble.test;
|
|||||||
import org.briarproject.bramble.api.FeatureFlags;
|
import org.briarproject.bramble.api.FeatureFlags;
|
||||||
import org.briarproject.bramble.battery.DefaultBatteryManagerModule;
|
import org.briarproject.bramble.battery.DefaultBatteryManagerModule;
|
||||||
import org.briarproject.bramble.event.DefaultEventExecutorModule;
|
import org.briarproject.bramble.event.DefaultEventExecutorModule;
|
||||||
|
import org.briarproject.bramble.system.DefaultTaskSchedulerModule;
|
||||||
|
import org.briarproject.bramble.system.DefaultWakefulIoExecutorModule;
|
||||||
|
|
||||||
import dagger.Module;
|
import dagger.Module;
|
||||||
import dagger.Provides;
|
import dagger.Provides;
|
||||||
@@ -10,6 +12,8 @@ import dagger.Provides;
|
|||||||
@Module(includes = {
|
@Module(includes = {
|
||||||
DefaultBatteryManagerModule.class,
|
DefaultBatteryManagerModule.class,
|
||||||
DefaultEventExecutorModule.class,
|
DefaultEventExecutorModule.class,
|
||||||
|
DefaultTaskSchedulerModule.class,
|
||||||
|
DefaultWakefulIoExecutorModule.class,
|
||||||
TestDatabaseConfigModule.class,
|
TestDatabaseConfigModule.class,
|
||||||
TestPluginConfigModule.class,
|
TestPluginConfigModule.class,
|
||||||
TestSecureRandomModule.class
|
TestSecureRandomModule.class
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import org.briarproject.bramble.api.db.DatabaseComponent;
|
|||||||
import org.briarproject.bramble.api.db.Transaction;
|
import org.briarproject.bramble.api.db.Transaction;
|
||||||
import org.briarproject.bramble.api.plugin.TransportId;
|
import org.briarproject.bramble.api.plugin.TransportId;
|
||||||
import org.briarproject.bramble.api.system.Clock;
|
import org.briarproject.bramble.api.system.Clock;
|
||||||
|
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||||
import org.briarproject.bramble.api.transport.IncomingKeys;
|
import org.briarproject.bramble.api.transport.IncomingKeys;
|
||||||
import org.briarproject.bramble.api.transport.KeySetId;
|
import org.briarproject.bramble.api.transport.KeySetId;
|
||||||
import org.briarproject.bramble.api.transport.OutgoingKeys;
|
import org.briarproject.bramble.api.transport.OutgoingKeys;
|
||||||
@@ -29,7 +30,6 @@ import java.util.Collection;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
import java.util.concurrent.Executor;
|
import java.util.concurrent.Executor;
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
|
|
||||||
import static java.util.Arrays.asList;
|
import static java.util.Arrays.asList;
|
||||||
import static java.util.Collections.singletonList;
|
import static java.util.Collections.singletonList;
|
||||||
@@ -55,8 +55,7 @@ public class TransportKeyManagerImplTest extends BrambleMockTestCase {
|
|||||||
private final TransportCrypto transportCrypto =
|
private final TransportCrypto transportCrypto =
|
||||||
context.mock(TransportCrypto.class);
|
context.mock(TransportCrypto.class);
|
||||||
private final Executor dbExecutor = context.mock(Executor.class);
|
private final Executor dbExecutor = context.mock(Executor.class);
|
||||||
private final ScheduledExecutorService scheduler =
|
private final TaskScheduler scheduler = context.mock(TaskScheduler.class);
|
||||||
context.mock(ScheduledExecutorService.class);
|
|
||||||
private final Clock clock = context.mock(Clock.class);
|
private final Clock clock = context.mock(Clock.class);
|
||||||
|
|
||||||
private final TransportId transportId = getTransportId();
|
private final TransportId transportId = getTransportId();
|
||||||
@@ -118,7 +117,8 @@ public class TransportKeyManagerImplTest extends BrambleMockTestCase {
|
|||||||
new TransportKeySet(keySetId, contactId, null, updated)));
|
new TransportKeySet(keySetId, contactId, null, updated)));
|
||||||
// Schedule a key update at the start of the next time period
|
// Schedule a key update at the start of the next time period
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with(timePeriodLength - 1), with(MILLISECONDS));
|
with(dbExecutor), with(timePeriodLength - 1),
|
||||||
|
with(MILLISECONDS));
|
||||||
}});
|
}});
|
||||||
|
|
||||||
transportKeyManager.start(txn);
|
transportKeyManager.start(txn);
|
||||||
@@ -421,9 +421,8 @@ public class TransportKeyManagerImplTest extends BrambleMockTestCase {
|
|||||||
}
|
}
|
||||||
// Schedule a key update at the start of the next time period
|
// Schedule a key update at the start of the next time period
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with(timePeriodLength), with(MILLISECONDS));
|
with(dbExecutor), with(timePeriodLength),
|
||||||
will(new RunAction());
|
with(MILLISECONDS));
|
||||||
oneOf(dbExecutor).execute(with(any(Runnable.class)));
|
|
||||||
will(new RunAction());
|
will(new RunAction());
|
||||||
// Start a transaction for updating keys
|
// Start a transaction for updating keys
|
||||||
oneOf(db).transaction(with(false), withDbRunnable(txn1));
|
oneOf(db).transaction(with(false), withDbRunnable(txn1));
|
||||||
@@ -446,7 +445,8 @@ public class TransportKeyManagerImplTest extends BrambleMockTestCase {
|
|||||||
new TransportKeySet(keySetId, contactId, null, updated)));
|
new TransportKeySet(keySetId, contactId, null, updated)));
|
||||||
// Schedule a key update at the start of the next time period
|
// Schedule a key update at the start of the next time period
|
||||||
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
oneOf(scheduler).schedule(with(any(Runnable.class)),
|
||||||
with(timePeriodLength), with(MILLISECONDS));
|
with(dbExecutor), with(timePeriodLength),
|
||||||
|
with(MILLISECONDS));
|
||||||
}});
|
}});
|
||||||
|
|
||||||
transportKeyManager.start(txn);
|
transportKeyManager.start(txn);
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user