mirror of
https://code.briarproject.org/briar/briar.git
synced 2026-02-12 10:49:06 +01:00
Compare commits
47 Commits
1712-detec
...
nav-drawer
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af469d7f27 | ||
|
|
0192b64dd3 | ||
|
|
aeb148c600 | ||
|
|
ac288b01d1 | ||
|
|
197b40647c | ||
|
|
9fc4bc838d | ||
|
|
89c227e2da | ||
|
|
4269bd4b74 | ||
|
|
cc7a19402e | ||
|
|
dc64c4148d | ||
|
|
e647ae7bb4 | ||
|
|
42776f56d0 | ||
|
|
559776b0f5 | ||
|
|
642485d7bd | ||
|
|
070be8621d | ||
|
|
2e42fb3c44 | ||
|
|
3f0f3746d7 | ||
|
|
c2dd61b006 | ||
|
|
5e37b3da22 | ||
|
|
8622f663f6 | ||
|
|
628b69d4eb | ||
|
|
b53319a7b0 | ||
|
|
98d4a48855 | ||
|
|
9184bf6afc | ||
|
|
4f2f145ab6 | ||
|
|
c945b3f611 | ||
|
|
0940b8d5b9 | ||
|
|
dac21cb3a0 | ||
|
|
9bfbb4d02d | ||
|
|
2689e5f361 | ||
|
|
d7d8af7e32 | ||
|
|
57a47463d6 | ||
|
|
8db481a17a | ||
|
|
2b9ffc7fbe | ||
|
|
0a5f93edf9 | ||
|
|
0aada89625 | ||
|
|
549cf4e2be | ||
|
|
c6981fb243 | ||
|
|
10791aea49 | ||
|
|
1c98d8f12a | ||
|
|
6bce4b76d2 | ||
|
|
c7565cb93e | ||
|
|
32288c376b | ||
|
|
1e7a1670dd | ||
|
|
850ad18a36 | ||
|
|
5d6ed1a724 | ||
|
|
ded1792213 |
@@ -11,8 +11,8 @@ android {
|
||||
defaultConfig {
|
||||
minSdkVersion 16
|
||||
targetSdkVersion 28
|
||||
versionCode 10207
|
||||
versionName "1.2.7"
|
||||
versionCode 10205
|
||||
versionName "1.2.5"
|
||||
consumerProguardFiles 'proguard-rules.txt'
|
||||
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
@@ -38,7 +38,7 @@ configurations {
|
||||
|
||||
dependencies {
|
||||
implementation project(path: ':bramble-core', configuration: 'default')
|
||||
tor 'org.briarproject:tor-android:0.3.5.10@zip'
|
||||
tor 'org.briarproject:tor-android:0.3.5.9@zip'
|
||||
tor 'org.briarproject:obfs4proxy-android:0.0.11-2@zip'
|
||||
|
||||
annotationProcessor 'com.google.dagger:dagger-compiler:2.24'
|
||||
|
||||
@@ -12,7 +12,6 @@ import org.briarproject.bramble.api.identity.IdentityManager;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@@ -21,7 +20,6 @@ import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static android.os.Build.VERSION.SDK_INT;
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.logging.Level.INFO;
|
||||
import static org.briarproject.bramble.util.IoUtils.deleteFileOrDir;
|
||||
import static org.briarproject.bramble.util.LogUtils.logFileOrDir;
|
||||
@@ -32,12 +30,6 @@ class AndroidAccountManager extends AccountManagerImpl
|
||||
private static final Logger LOG =
|
||||
Logger.getLogger(AndroidAccountManager.class.getName());
|
||||
|
||||
/**
|
||||
* Directories that shouldn't be deleted when deleting the user's account.
|
||||
*/
|
||||
private static final List<String> PROTECTED_DIR_NAMES =
|
||||
asList("cache", "code_cache", "lib", "shared_prefs");
|
||||
|
||||
protected final Context appContext;
|
||||
private final SharedPreferences prefs;
|
||||
|
||||
@@ -89,7 +81,7 @@ class AndroidAccountManager extends AccountManagerImpl
|
||||
if (!prefs.edit().clear().commit())
|
||||
LOG.warning("Could not clear shared preferences");
|
||||
}
|
||||
// Delete files, except protected directories
|
||||
// Delete files, except lib and shared_prefs directories
|
||||
Set<File> files = new HashSet<>();
|
||||
File dataDir = getDataDir();
|
||||
@Nullable
|
||||
@@ -98,12 +90,14 @@ class AndroidAccountManager extends AccountManagerImpl
|
||||
LOG.warning("Could not list files in app data dir");
|
||||
} else {
|
||||
for (File file : fileArray) {
|
||||
if (!PROTECTED_DIR_NAMES.contains(file.getName())) {
|
||||
String name = file.getName();
|
||||
if (!name.equals("lib") && !name.equals("shared_prefs")) {
|
||||
files.add(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
files.add(appContext.getFilesDir());
|
||||
files.add(appContext.getCacheDir());
|
||||
addIfNotNull(files, appContext.getExternalCacheDir());
|
||||
if (SDK_INT >= 19) {
|
||||
for (File file : appContext.getExternalCacheDirs()) {
|
||||
@@ -115,16 +109,12 @@ class AndroidAccountManager extends AccountManagerImpl
|
||||
addIfNotNull(files, file);
|
||||
}
|
||||
}
|
||||
// Clear the cache directory but don't delete it
|
||||
File cacheDir = appContext.getCacheDir();
|
||||
File[] children = cacheDir.listFiles();
|
||||
if (children != null) files.addAll(asList(children));
|
||||
for (File file : files) {
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Deleting " + file.getAbsolutePath());
|
||||
}
|
||||
deleteFileOrDir(file);
|
||||
}
|
||||
// Recreate the cache dir as some OpenGL drivers expect it to exist
|
||||
if (!new File(dataDir, "cache").mkdirs())
|
||||
LOG.warning("Could not recreate cache dir");
|
||||
}
|
||||
|
||||
private File getDataDir() {
|
||||
|
||||
@@ -32,7 +32,6 @@ import static android.content.Intent.ACTION_SCREEN_OFF;
|
||||
import static android.content.Intent.ACTION_SCREEN_ON;
|
||||
import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
|
||||
import static android.net.ConnectivityManager.TYPE_WIFI;
|
||||
import static android.net.wifi.p2p.WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION;
|
||||
import static android.os.Build.VERSION.SDK_INT;
|
||||
import static android.os.PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED;
|
||||
import static java.util.concurrent.TimeUnit.MINUTES;
|
||||
@@ -77,9 +76,9 @@ class AndroidNetworkManager implements NetworkManager, Service {
|
||||
filter.addAction(ACTION_SCREEN_ON);
|
||||
filter.addAction(ACTION_SCREEN_OFF);
|
||||
filter.addAction(WIFI_AP_STATE_CHANGED_ACTION);
|
||||
filter.addAction(WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
|
||||
if (SDK_INT >= 23) filter.addAction(ACTION_DEVICE_IDLE_MODE_CHANGED);
|
||||
appContext.registerReceiver(networkStateReceiver, filter);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -137,8 +136,7 @@ class AndroidNetworkManager implements NetworkManager, Service {
|
||||
}
|
||||
|
||||
private boolean isApEvent(@Nullable String action) {
|
||||
return WIFI_AP_STATE_CHANGED_ACTION.equals(action) ||
|
||||
WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action);
|
||||
return WIFI_AP_STATE_CHANGED_ACTION.equals(action);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
|
||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Backoff;
|
||||
@@ -25,6 +24,7 @@ import java.io.IOException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
@@ -47,10 +47,7 @@ import static android.bluetooth.BluetoothAdapter.SCAN_MODE_NONE;
|
||||
import static android.bluetooth.BluetoothAdapter.STATE_OFF;
|
||||
import static android.bluetooth.BluetoothAdapter.STATE_ON;
|
||||
import static android.bluetooth.BluetoothDevice.ACTION_FOUND;
|
||||
import static android.bluetooth.BluetoothDevice.DEVICE_TYPE_LE;
|
||||
import static android.bluetooth.BluetoothDevice.EXTRA_DEVICE;
|
||||
import static android.os.Build.VERSION.SDK_INT;
|
||||
import static java.util.Collections.shuffle;
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
import static java.util.logging.Level.INFO;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
@@ -77,12 +74,11 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
||||
private volatile BluetoothAdapter adapter = null;
|
||||
|
||||
AndroidBluetoothPlugin(BluetoothConnectionLimiter connectionLimiter,
|
||||
TimeoutMonitor timeoutMonitor, Executor ioExecutor,
|
||||
SecureRandom secureRandom, AndroidExecutor androidExecutor,
|
||||
Context appContext, Clock clock, Backoff backoff,
|
||||
PluginCallback callback, int maxLatency, int maxIdleTime) {
|
||||
super(connectionLimiter, timeoutMonitor, ioExecutor, secureRandom,
|
||||
backoff, callback, maxLatency, maxIdleTime);
|
||||
Executor ioExecutor, AndroidExecutor androidExecutor,
|
||||
Context appContext, SecureRandom secureRandom, Clock clock,
|
||||
Backoff backoff, PluginCallback callback, int maxLatency) {
|
||||
super(connectionLimiter, ioExecutor, secureRandom, backoff, callback,
|
||||
maxLatency);
|
||||
this.androidExecutor = androidExecutor;
|
||||
this.appContext = appContext;
|
||||
this.clock = clock;
|
||||
@@ -150,6 +146,12 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
||||
wasEnabledByUs = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
void onAdapterDisabled() {
|
||||
super.onAdapterDisabled();
|
||||
wasEnabledByUs = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
String getBluetoothAddress() {
|
||||
@@ -174,10 +176,9 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
||||
return wrapSocket(ss.accept());
|
||||
}
|
||||
|
||||
private DuplexTransportConnection wrapSocket(BluetoothSocket s)
|
||||
throws IOException {
|
||||
return new AndroidBluetoothTransportConnection(this, connectionLimiter,
|
||||
timeoutMonitor, s);
|
||||
private DuplexTransportConnection wrapSocket(BluetoothSocket s) {
|
||||
return new AndroidBluetoothTransportConnection(this,
|
||||
connectionLimiter, s);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -245,15 +246,11 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
||||
break;
|
||||
} else if (ACTION_FOUND.equals(action)) {
|
||||
BluetoothDevice d = i.getParcelableExtra(EXTRA_DEVICE);
|
||||
// Ignore Bluetooth LE devices
|
||||
if (SDK_INT < 18 || d.getType() != DEVICE_TYPE_LE) {
|
||||
String address = d.getAddress();
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Discovered " +
|
||||
scrubMacAddress(address));
|
||||
if (!addresses.contains(address))
|
||||
addresses.add(address);
|
||||
}
|
||||
String address = d.getAddress();
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Discovered " + scrubMacAddress(address));
|
||||
if (!addresses.contains(address))
|
||||
addresses.add(address);
|
||||
}
|
||||
now = clock.currentTimeMillis();
|
||||
}
|
||||
@@ -269,7 +266,7 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
||||
appContext.unregisterReceiver(receiver);
|
||||
}
|
||||
// Shuffle the addresses so we don't always try the same one first
|
||||
shuffle(addresses);
|
||||
Collections.shuffle(addresses);
|
||||
return addresses;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ package org.briarproject.bramble.plugin.bluetooth;
|
||||
import android.content.Context;
|
||||
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Backoff;
|
||||
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
||||
@@ -26,7 +25,6 @@ import static org.briarproject.bramble.api.plugin.BluetoothConstants.ID;
|
||||
public class AndroidBluetoothPluginFactory implements DuplexPluginFactory {
|
||||
|
||||
private static final int MAX_LATENCY = 30 * 1000; // 30 seconds
|
||||
private static final int MAX_IDLE_TIME = 30 * 1000; // 30 seconds
|
||||
private static final int MIN_POLLING_INTERVAL = 60 * 1000; // 1 minute
|
||||
private static final int MAX_POLLING_INTERVAL = 10 * 60 * 1000; // 10 mins
|
||||
private static final double BACKOFF_BASE = 1.2;
|
||||
@@ -37,20 +35,18 @@ public class AndroidBluetoothPluginFactory implements DuplexPluginFactory {
|
||||
private final SecureRandom secureRandom;
|
||||
private final EventBus eventBus;
|
||||
private final Clock clock;
|
||||
private final TimeoutMonitor timeoutMonitor;
|
||||
private final BackoffFactory backoffFactory;
|
||||
|
||||
public AndroidBluetoothPluginFactory(Executor ioExecutor,
|
||||
AndroidExecutor androidExecutor, Context appContext,
|
||||
SecureRandom secureRandom, EventBus eventBus, Clock clock,
|
||||
TimeoutMonitor timeoutMonitor, BackoffFactory backoffFactory) {
|
||||
BackoffFactory backoffFactory) {
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.androidExecutor = androidExecutor;
|
||||
this.appContext = appContext;
|
||||
this.secureRandom = secureRandom;
|
||||
this.eventBus = eventBus;
|
||||
this.clock = clock;
|
||||
this.timeoutMonitor = timeoutMonitor;
|
||||
this.backoffFactory = backoffFactory;
|
||||
}
|
||||
|
||||
@@ -67,13 +63,12 @@ public class AndroidBluetoothPluginFactory implements DuplexPluginFactory {
|
||||
@Override
|
||||
public DuplexPlugin createPlugin(PluginCallback callback) {
|
||||
BluetoothConnectionLimiter connectionLimiter =
|
||||
new BluetoothConnectionLimiterImpl(eventBus, clock);
|
||||
new BluetoothConnectionLimiterImpl();
|
||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||
AndroidBluetoothPlugin plugin = new AndroidBluetoothPlugin(
|
||||
connectionLimiter, timeoutMonitor, ioExecutor, secureRandom,
|
||||
androidExecutor, appContext, clock, backoff,
|
||||
callback, MAX_LATENCY, MAX_IDLE_TIME);
|
||||
connectionLimiter, ioExecutor, androidExecutor, appContext,
|
||||
secureRandom, clock, backoff, callback, MAX_LATENCY);
|
||||
eventBus.addListener(plugin);
|
||||
return plugin;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ 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.Plugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.AbstractDuplexTransportConnection;
|
||||
@@ -11,33 +10,24 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
import static org.briarproject.bramble.api.plugin.BluetoothConstants.PROP_ADDRESS;
|
||||
import static org.briarproject.bramble.util.AndroidUtils.isValidBluetoothAddress;
|
||||
|
||||
@NotNullByDefault
|
||||
class AndroidBluetoothTransportConnection
|
||||
extends AbstractDuplexTransportConnection {
|
||||
|
||||
private final BluetoothConnectionLimiter connectionLimiter;
|
||||
private final BluetoothConnectionLimiter connectionManager;
|
||||
private final BluetoothSocket socket;
|
||||
private final InputStream in;
|
||||
|
||||
AndroidBluetoothTransportConnection(Plugin plugin,
|
||||
BluetoothConnectionLimiter connectionLimiter,
|
||||
TimeoutMonitor timeoutMonitor, BluetoothSocket socket)
|
||||
throws IOException {
|
||||
BluetoothConnectionLimiter connectionManager,
|
||||
BluetoothSocket socket) {
|
||||
super(plugin);
|
||||
this.connectionLimiter = connectionLimiter;
|
||||
this.connectionManager = connectionManager;
|
||||
this.socket = socket;
|
||||
in = timeoutMonitor.createTimeoutInputStream(
|
||||
socket.getInputStream(), plugin.getMaxIdleTime() * 2);
|
||||
String address = socket.getRemoteDevice().getAddress();
|
||||
if (isValidBluetoothAddress(address)) remote.put(PROP_ADDRESS, address);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected InputStream getInputStream() {
|
||||
return in;
|
||||
protected InputStream getInputStream() throws IOException {
|
||||
return socket.getInputStream();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -50,7 +40,7 @@ class AndroidBluetoothTransportConnection
|
||||
try {
|
||||
socket.close();
|
||||
} finally {
|
||||
connectionLimiter.connectionClosed(this, exception);
|
||||
connectionManager.connectionClosed(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,17 +9,17 @@ import android.net.wifi.WifiManager;
|
||||
|
||||
import org.briarproject.bramble.PoliteExecutor;
|
||||
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.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Backoff;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
import org.briarproject.bramble.api.settings.Settings;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.List;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@@ -32,14 +32,31 @@ import static android.net.ConnectivityManager.TYPE_WIFI;
|
||||
import static android.os.Build.VERSION.SDK_INT;
|
||||
import static java.util.Collections.emptyList;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
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.INACTIVE;
|
||||
import static org.briarproject.bramble.util.IoUtils.tryToClose;
|
||||
|
||||
@NotNullByDefault
|
||||
class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
|
||||
class AndroidLanTcpPlugin extends LanTcpPlugin {
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(AndroidLanTcpPlugin.class.getName());
|
||||
|
||||
private static final byte[] WIFI_AP_ADDRESS_BYTES =
|
||||
{(byte) 192, (byte) 168, 43, 1};
|
||||
private static final InetAddress WIFI_AP_ADDRESS;
|
||||
|
||||
static {
|
||||
try {
|
||||
WIFI_AP_ADDRESS = InetAddress.getByAddress(WIFI_AP_ADDRESS_BYTES);
|
||||
} catch (UnknownHostException e) {
|
||||
// Should only be thrown if the address has an illegal length
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private final Executor connectionStatusExecutor;
|
||||
private final ConnectivityManager connectivityManager;
|
||||
@Nullable
|
||||
@@ -49,9 +66,8 @@ class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
|
||||
|
||||
AndroidLanTcpPlugin(Executor ioExecutor, Context appContext,
|
||||
Backoff backoff, PluginCallback callback, int maxLatency,
|
||||
int maxIdleTime, int connectionTimeout) {
|
||||
super(ioExecutor, backoff, callback, maxLatency, maxIdleTime,
|
||||
connectionTimeout);
|
||||
int maxIdleTime) {
|
||||
super(ioExecutor, backoff, callback, maxLatency, maxIdleTime);
|
||||
// Don't execute more than one connection status check at a time
|
||||
connectionStatusExecutor =
|
||||
new PoliteExecutor("AndroidLanTcpPlugin", ioExecutor, 1);
|
||||
@@ -67,36 +83,27 @@ class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
|
||||
@Override
|
||||
public void start() {
|
||||
if (used.getAndSet(true)) throw new IllegalStateException();
|
||||
initialisePortProperty();
|
||||
running = true;
|
||||
Settings settings = callback.getSettings();
|
||||
state.setStarted(settings.getBoolean(PREF_PLUGIN_ENABLE, false));
|
||||
updateConnectionStatus();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
running = false;
|
||||
tryToClose(socket);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Socket createSocket() throws IOException {
|
||||
return socketFactory.createSocket();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<InetAddress> getUsableLocalInetAddresses() {
|
||||
protected Collection<InetAddress> getLocalIpAddresses() {
|
||||
// If the device doesn't have wifi, don't open any sockets
|
||||
if (wifiManager == null) return emptyList();
|
||||
// If we're connected to a wifi network, return its address
|
||||
// If we're connected to a wifi network, use that network
|
||||
WifiInfo info = wifiManager.getConnectionInfo();
|
||||
if (info != null && info.getIpAddress() != 0) {
|
||||
if (info != null && info.getIpAddress() != 0)
|
||||
return singletonList(intToInetAddress(info.getIpAddress()));
|
||||
}
|
||||
// If we're running an access point, return its address
|
||||
for (InetAddress addr : getLocalInetAddresses()) {
|
||||
if (addr.equals(WIFI_AP_ADDRESS)) return singletonList(addr);
|
||||
if (addr.equals(WIFI_DIRECT_AP_ADDRESS)) return singletonList(addr);
|
||||
}
|
||||
if (super.getLocalIpAddresses().contains(WIFI_AP_ADDRESS))
|
||||
return singletonList(WIFI_AP_ADDRESS);
|
||||
// No suitable addresses
|
||||
return emptyList();
|
||||
}
|
||||
@@ -130,30 +137,37 @@ class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
super.eventOccurred(e);
|
||||
if (e instanceof NetworkStatusEvent) updateConnectionStatus();
|
||||
}
|
||||
|
||||
private void updateConnectionStatus() {
|
||||
connectionStatusExecutor.execute(() -> {
|
||||
if (!running) return;
|
||||
List<InetAddress> addrs = getUsableLocalInetAddresses();
|
||||
if (addrs.contains(WIFI_AP_ADDRESS)
|
||||
|| addrs.contains(WIFI_DIRECT_AP_ADDRESS)) {
|
||||
State s = getState();
|
||||
if (s != ACTIVE && s != INACTIVE) return;
|
||||
Collection<InetAddress> addrs = getLocalIpAddresses();
|
||||
if (addrs.contains(WIFI_AP_ADDRESS)) {
|
||||
LOG.info("Providing wifi hotspot");
|
||||
// There's no corresponding Network object and thus no way
|
||||
// to get a suitable socket factory, so we won't be able to
|
||||
// make outgoing connections on API 21+ if another network
|
||||
// has internet access
|
||||
socketFactory = SocketFactory.getDefault();
|
||||
if (socket == null || socket.isClosed()) bind();
|
||||
if (s == INACTIVE) bind();
|
||||
} else if (addrs.isEmpty()) {
|
||||
LOG.info("Not connected to wifi");
|
||||
socketFactory = SocketFactory.getDefault();
|
||||
tryToClose(socket);
|
||||
// Server socket may not have been closed automatically when
|
||||
// interface was taken down. Socket will be cleared and state
|
||||
// updated in acceptContactConnections()
|
||||
if (s == ACTIVE) {
|
||||
LOG.info("Closing server socket");
|
||||
tryToClose(state.getServerSocket(), LOG, WARNING);
|
||||
}
|
||||
} else {
|
||||
LOG.info("Connected to wifi");
|
||||
socketFactory = getSocketFactory();
|
||||
if (socket == null || socket.isClosed()) bind();
|
||||
if (s == INACTIVE) bind();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -21,11 +21,10 @@ import static org.briarproject.bramble.api.plugin.LanTcpConstants.ID;
|
||||
@NotNullByDefault
|
||||
public class AndroidLanTcpPluginFactory implements DuplexPluginFactory {
|
||||
|
||||
private static final int MAX_LATENCY = 30_000; // 30 seconds
|
||||
private static final int MAX_IDLE_TIME = 30_000; // 30 seconds
|
||||
private static final int CONNECTION_TIMEOUT = 3_000; // 3 seconds
|
||||
private static final int MIN_POLLING_INTERVAL = 60_000; // 1 minute
|
||||
private static final int MAX_POLLING_INTERVAL = 600_000; // 10 mins
|
||||
private static final int MAX_LATENCY = 30 * 1000; // 30 seconds
|
||||
private static final int MAX_IDLE_TIME = 30 * 1000; // 30 seconds
|
||||
private static final int MIN_POLLING_INTERVAL = 60 * 1000; // 1 minute
|
||||
private static final int MAX_POLLING_INTERVAL = 10 * 60 * 1000; // 10 mins
|
||||
private static final double BACKOFF_BASE = 1.2;
|
||||
|
||||
private final Executor ioExecutor;
|
||||
@@ -56,8 +55,7 @@ public class AndroidLanTcpPluginFactory implements DuplexPluginFactory {
|
||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||
AndroidLanTcpPlugin plugin = new AndroidLanTcpPlugin(ioExecutor,
|
||||
appContext, backoff, callback, MAX_LATENCY, MAX_IDLE_TIME,
|
||||
CONNECTION_TIMEOUT);
|
||||
appContext, backoff, callback, MAX_LATENCY, MAX_IDLE_TIME);
|
||||
eventBus.addListener(plugin);
|
||||
return plugin;
|
||||
}
|
||||
|
||||
@@ -74,7 +74,6 @@ class AndroidTorPlugin extends TorPlugin {
|
||||
|
||||
@Override
|
||||
protected void enableNetwork(boolean enable) throws IOException {
|
||||
if (!running) return;
|
||||
if (enable) wakeLock.acquire();
|
||||
super.enableNetwork(enable);
|
||||
if (!enable) wakeLock.release();
|
||||
|
||||
@@ -61,12 +61,12 @@ class AndroidLocationUtils implements LocationUtils {
|
||||
private String getCountryFromPhoneNetwork() {
|
||||
Object o = appContext.getSystemService(TELEPHONY_SERVICE);
|
||||
TelephonyManager tm = (TelephonyManager) o;
|
||||
return tm.getNetworkCountryIso();
|
||||
return tm == null ? "" : tm.getNetworkCountryIso();
|
||||
}
|
||||
|
||||
private String getCountryFromSimCard() {
|
||||
Object o = appContext.getSystemService(TELEPHONY_SERVICE);
|
||||
TelephonyManager tm = (TelephonyManager) o;
|
||||
return tm.getSimCountryIso();
|
||||
return tm == null ? "" : tm.getSimCountryIso();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ public class AndroidUtils {
|
||||
return new Pair<>("", "");
|
||||
}
|
||||
|
||||
public static boolean isValidBluetoothAddress(@Nullable String address) {
|
||||
private static boolean isValidBluetoothAddress(@Nullable String address) {
|
||||
return !StringUtils.isNullOrEmpty(address)
|
||||
&& BluetoothAdapter.checkBluetoothAddress(address)
|
||||
&& !address.equals(FAKE_BLUETOOTH_ADDRESS);
|
||||
|
||||
@@ -72,9 +72,7 @@ public class AndroidAccountManagerTest extends BrambleMockTestCase {
|
||||
@Test
|
||||
public void testDeleteAccountClearsSharedPrefsAndDeletesFiles()
|
||||
throws Exception {
|
||||
// Directories 'code_cache', 'lib' and 'shared_prefs' should be spared
|
||||
File codeCacheDir = new File(testDir, "code_cache");
|
||||
File codeCacheFile = new File(codeCacheDir, "file");
|
||||
// Directories 'lib' and 'shared_prefs' should be spared
|
||||
File libDir = new File(testDir, "lib");
|
||||
File libFile = new File(libDir, "file");
|
||||
File sharedPrefsDir = new File(testDir, "shared_prefs");
|
||||
@@ -113,8 +111,6 @@ public class AndroidAccountManagerTest extends BrambleMockTestCase {
|
||||
|
||||
assertTrue(dbDir.mkdirs());
|
||||
assertTrue(keyDir.mkdirs());
|
||||
assertTrue(codeCacheDir.mkdirs());
|
||||
assertTrue(codeCacheFile.createNewFile());
|
||||
assertTrue(libDir.mkdirs());
|
||||
assertTrue(libFile.createNewFile());
|
||||
assertTrue(sharedPrefsDir.mkdirs());
|
||||
@@ -130,8 +126,6 @@ public class AndroidAccountManagerTest extends BrambleMockTestCase {
|
||||
|
||||
assertFalse(dbDir.exists());
|
||||
assertFalse(keyDir.exists());
|
||||
assertTrue(codeCacheDir.exists());
|
||||
assertTrue(codeCacheFile.exists());
|
||||
assertTrue(libDir.exists());
|
||||
assertTrue(libFile.exists());
|
||||
assertTrue(sharedPrefsDir.exists());
|
||||
|
||||
@@ -70,7 +70,7 @@ dependencyVerification {
|
||||
'org.bouncycastle:bcpkix-jdk15on:1.56:bcpkix-jdk15on-1.56.jar:7043dee4e9e7175e93e0b36f45b1ec1ecb893c5f755667e8b916eb8dd201c6ca',
|
||||
'org.bouncycastle:bcprov-jdk15on:1.56:bcprov-jdk15on-1.56.jar:963e1ee14f808ffb99897d848ddcdb28fa91ddda867eb18d303e82728f878349',
|
||||
'org.briarproject:obfs4proxy-android:0.0.11-2:obfs4proxy-android-0.0.11-2.zip:57e55cbe87aa2aac210fdbb6cd8cdeafe15f825406a08ebf77a8b787aa2c6a8a',
|
||||
'org.briarproject:tor-android:0.3.5.10:tor-android-0.3.5.10.zip:edd83bf557fcff2105eaa0bdb3f607a6852ebe7360920929ae3039dd5f4774c5',
|
||||
'org.briarproject:tor-android:0.3.5.9:tor-android-0.3.5.9.zip:853b0440feccd6904bd03e6b2de53a62ebcde1d58068beeadc447a7dff950bc8',
|
||||
'org.checkerframework:checker-compat-qual:2.5.3:checker-compat-qual-2.5.3.jar:d76b9afea61c7c082908023f0cbc1427fab9abd2df915c8b8a3e7a509bccbc6d',
|
||||
'org.checkerframework:checker-qual:2.5.2:checker-qual-2.5.2.jar:64b02691c8b9d4e7700f8ee2e742dce7ea2c6e81e662b7522c9ee3bf568c040a',
|
||||
'org.codehaus.groovy:groovy-all:2.4.15:groovy-all-2.4.15.jar:51d6c4e71782e85674239189499854359d380fb75e1a703756e3aaa5b98a5af0',
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.briarproject.bramble.api.account;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.DecryptionException;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.identity.IdentityManager;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
@@ -14,8 +13,7 @@ public interface AccountManager {
|
||||
* Returns true if the manager has the database key. This will be false
|
||||
* before {@link #createAccount(String, String)} or {@link #signIn(String)}
|
||||
* has been called, and true after {@link #createAccount(String, String)}
|
||||
* or {@link #signIn(String)} has returned true, until
|
||||
* {@link #deleteAccount()} is called or the process exits.
|
||||
* or {@link #signIn(String)} has returned true, until the process exits.
|
||||
*/
|
||||
boolean hasDatabaseKey();
|
||||
|
||||
@@ -24,22 +22,25 @@ public interface AccountManager {
|
||||
* before {@link #createAccount(String, String)} or {@link #signIn(String)}
|
||||
* has been called, and non-null after
|
||||
* {@link #createAccount(String, String)} or {@link #signIn(String)} has
|
||||
* returned true, until {@link #deleteAccount()} is called or the process
|
||||
* exits.
|
||||
* returned true, until the process exits.
|
||||
*/
|
||||
@Nullable
|
||||
SecretKey getDatabaseKey();
|
||||
|
||||
/**
|
||||
* Returns true if the encrypted database key can be loaded from disk.
|
||||
* Returns true if the encrypted database key can be loaded from disk, and
|
||||
* the database directory exists and is a directory.
|
||||
*/
|
||||
boolean accountExists();
|
||||
|
||||
/**
|
||||
* Creates an identity with the given name and registers it with the
|
||||
* {@link IdentityManager}. Creates a database key, encrypts it with the
|
||||
* given password and stores it on disk. {@link #accountExists()} will
|
||||
* return true after this method returns true.
|
||||
* given password and stores it on disk.
|
||||
* <p/>
|
||||
* This method does not create the database directory, so
|
||||
* {@link #accountExists()} will continue to return false until the
|
||||
* database directory is created.
|
||||
*/
|
||||
boolean createAccount(String name, String password);
|
||||
|
||||
@@ -53,19 +54,17 @@ public interface AccountManager {
|
||||
* Loads the encrypted database key from disk and decrypts it with the
|
||||
* given password.
|
||||
*
|
||||
* @throws DecryptionException If the database key could not be loaded and
|
||||
* decrypted.
|
||||
* @return true if the database key was successfully loaded and decrypted.
|
||||
*/
|
||||
void signIn(String password) throws DecryptionException;
|
||||
boolean signIn(String password);
|
||||
|
||||
/**
|
||||
* Loads the encrypted database key from disk, decrypts it with the old
|
||||
* password, encrypts it with the new password, and stores it on disk,
|
||||
* replacing the old key.
|
||||
*
|
||||
* @throws DecryptionException If the database key could not be loaded and
|
||||
* decrypted.
|
||||
* @return true if the database key was successfully loaded, re-encrypted
|
||||
* and stored.
|
||||
*/
|
||||
void changePassword(String oldPassword, String newPassword)
|
||||
throws DecryptionException;
|
||||
boolean changePassword(String oldPassword, String newPassword);
|
||||
}
|
||||
|
||||
@@ -142,17 +142,16 @@ public interface CryptoComponent {
|
||||
/**
|
||||
* Decrypts and authenticates the given ciphertext that has been read from
|
||||
* storage. The encryption and authentication keys are derived from the
|
||||
* given password.
|
||||
* given password. Returns null if the ciphertext cannot be decrypted and
|
||||
* authenticated (for example, if the password is wrong).
|
||||
*
|
||||
* @param keyStrengthener Used to strengthen the password-based key. If
|
||||
* null, or if strengthening was not used when encrypting the ciphertext,
|
||||
* the password-based key will not be strengthened
|
||||
* @throws DecryptionException If the ciphertext cannot be decrypted and
|
||||
* authenticated (for example, if the password is wrong).
|
||||
*/
|
||||
@Nullable
|
||||
byte[] decryptWithPassword(byte[] ciphertext, String password,
|
||||
@Nullable KeyStrengthener keyStrengthener)
|
||||
throws DecryptionException;
|
||||
@Nullable KeyStrengthener keyStrengthener);
|
||||
|
||||
/**
|
||||
* Returns true if the given ciphertext was encrypted using a strengthened
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
package org.briarproject.bramble.api.crypto;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
@NotNullByDefault
|
||||
public class DecryptionException extends Exception {
|
||||
|
||||
private final DecryptionResult result;
|
||||
|
||||
public DecryptionException(DecryptionResult result) {
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
public DecryptionResult getDecryptionResult() {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package org.briarproject.bramble.api.crypto;
|
||||
|
||||
/**
|
||||
* The result of a password-based decryption operation.
|
||||
*/
|
||||
public enum DecryptionResult {
|
||||
|
||||
/**
|
||||
* Decryption succeeded.
|
||||
*/
|
||||
SUCCESS,
|
||||
|
||||
/**
|
||||
* Decryption failed because the format of the ciphertext was invalid.
|
||||
*/
|
||||
INVALID_CIPHERTEXT,
|
||||
|
||||
/**
|
||||
* Decryption failed because the {@link KeyStrengthener} used for
|
||||
* encryption was not available for decryption.
|
||||
*/
|
||||
KEY_STRENGTHENER_ERROR,
|
||||
|
||||
/**
|
||||
* Decryption failed because the password used for decryption did not match
|
||||
* the password used for encryption.
|
||||
*/
|
||||
INVALID_PASSWORD
|
||||
}
|
||||
@@ -18,6 +18,8 @@ public interface EventBus {
|
||||
/**
|
||||
* Asynchronously notifies all listeners of an event. Listeners are
|
||||
* notified on the {@link EventExecutor}.
|
||||
* <p>
|
||||
* This method can safely be called while holding a lock.
|
||||
*/
|
||||
void broadcast(Event e);
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package org.briarproject.bramble.api.io;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
public interface TimeoutMonitor {
|
||||
|
||||
/**
|
||||
* Returns an {@link InputStream} that wraps the given stream and allows
|
||||
* read timeouts to be detected.
|
||||
*
|
||||
* @param timeoutMs The read timeout in milliseconds. Timeouts will be
|
||||
* detected eventually but are not guaranteed to be detected immediately.
|
||||
*/
|
||||
InputStream createTimeoutInputStream(InputStream in, long timeoutMs);
|
||||
}
|
||||
@@ -9,5 +9,6 @@ public interface BluetoothConstants {
|
||||
String PROP_ADDRESS = "address";
|
||||
String PROP_UUID = "uuid";
|
||||
|
||||
String PREF_BT_ENABLE = "enable";
|
||||
// Reason code returned by Plugin#getReasonDisabled()
|
||||
int REASON_NO_BT_ADAPTER = 2;
|
||||
}
|
||||
|
||||
@@ -4,10 +4,10 @@ public interface LanTcpConstants {
|
||||
|
||||
TransportId ID = new TransportId("org.briarproject.bramble.lan");
|
||||
|
||||
// Transport properties (shared with contacts)
|
||||
// a transport property (shared with contacts)
|
||||
String PROP_IP_PORTS = "ipPorts";
|
||||
String PROP_PORT = "port";
|
||||
|
||||
// A local setting
|
||||
// a local setting
|
||||
String PREF_LAN_IP_PORTS = "ipPorts";
|
||||
|
||||
}
|
||||
|
||||
@@ -3,12 +3,57 @@ package org.briarproject.bramble.api.plugin;
|
||||
import org.briarproject.bramble.api.Pair;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.settings.SettingsManager;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
@NotNullByDefault
|
||||
public interface Plugin {
|
||||
|
||||
enum State {
|
||||
|
||||
/**
|
||||
* The plugin has not been started, has been stopped, or is disabled by
|
||||
* settings.
|
||||
*/
|
||||
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 code returned by {@link #getReasonDisabled()} to indicate that
|
||||
* the plugin is disabled because it has not been started or has been
|
||||
* stopped.
|
||||
*/
|
||||
int REASON_STARTING_STOPPING = 0;
|
||||
|
||||
/**
|
||||
* Reason code returned by {@link #getReasonDisabled()} to indicate that
|
||||
* the plugin has been disabled by the user.
|
||||
*/
|
||||
int REASON_USER = 1;
|
||||
|
||||
/**
|
||||
* Returns the plugin's transport identifier.
|
||||
*/
|
||||
@@ -35,9 +80,19 @@ public interface Plugin {
|
||||
void stop() throws PluginException;
|
||||
|
||||
/**
|
||||
* Returns true if the plugin is running.
|
||||
* Returns the current state of the plugin.
|
||||
*/
|
||||
boolean isRunning();
|
||||
State getState();
|
||||
|
||||
/**
|
||||
* Returns an integer code indicating why the plugin is
|
||||
* {@link State#DISABLED disabled}, or -1 if the plugin is not disabled.
|
||||
* <p>
|
||||
* The codes used are plugin-specific, except the generic codes
|
||||
* {@link #REASON_STARTING_STOPPING} and {@link #REASON_USER}, which may
|
||||
* be used by any plugin.
|
||||
*/
|
||||
int getReasonDisabled();
|
||||
|
||||
/**
|
||||
* Returns true if the plugin should be polled periodically to attempt to
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package org.briarproject.bramble.api.plugin;
|
||||
|
||||
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.settings.Settings;
|
||||
|
||||
@@ -32,12 +36,17 @@ public interface PluginCallback extends ConnectionHandler {
|
||||
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();
|
||||
|
||||
/**
|
||||
* Signals that the transport is disabled.
|
||||
*/
|
||||
void transportDisabled();
|
||||
void pluginStateChanged(State state);
|
||||
}
|
||||
|
||||
@@ -41,4 +41,17 @@ public interface PluginManager {
|
||||
* Returns any duplex plugins that support rendezvous.
|
||||
*/
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
@@ -23,4 +23,8 @@ public interface TorConstants {
|
||||
int PREF_TOR_NETWORK_WITH_BRIDGES = 2;
|
||||
int PREF_TOR_NETWORK_NEVER = 3;
|
||||
|
||||
// Reason codes returned by Plugin#getReasonDisabled()
|
||||
int REASON_BATTERY = 2;
|
||||
int REASON_MOBILE_DATA = 3;
|
||||
int REASON_COUNTRY_BLOCKED = 4;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Plugin;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -15,8 +14,6 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
public abstract class AbstractDuplexTransportConnection
|
||||
implements DuplexTransportConnection {
|
||||
|
||||
protected final TransportProperties remote = new TransportProperties();
|
||||
|
||||
private final Plugin plugin;
|
||||
private final Reader reader;
|
||||
private final Writer writer;
|
||||
@@ -47,11 +44,6 @@ public abstract class AbstractDuplexTransportConnection
|
||||
return writer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TransportProperties getRemoteProperties() {
|
||||
return remote;
|
||||
}
|
||||
|
||||
private class Reader implements TransportConnectionReader {
|
||||
|
||||
@Override
|
||||
|
||||
@@ -3,7 +3,6 @@ package org.briarproject.bramble.api.plugin.duplex;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
|
||||
/**
|
||||
* An interface for reading and writing data over a duplex transport. The
|
||||
@@ -24,10 +23,4 @@ public interface DuplexTransportConnection {
|
||||
* for writing to the connection.
|
||||
*/
|
||||
TransportConnectionWriter getWriter();
|
||||
|
||||
/**
|
||||
* Returns a possibly empty set of {@link TransportProperties} describing
|
||||
* the remote peer.
|
||||
*/
|
||||
TransportProperties getRemoteProperties();
|
||||
}
|
||||
|
||||
@@ -2,20 +2,22 @@ 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 a transport is enabled.
|
||||
* An event that is broadcast when a plugin enters the {@link State#ACTIVE}
|
||||
* state.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class TransportEnabledEvent extends Event {
|
||||
public class TransportActiveEvent extends Event {
|
||||
|
||||
private final TransportId transportId;
|
||||
|
||||
public TransportEnabledEvent(TransportId transportId) {
|
||||
public TransportActiveEvent(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.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 a transport is disabled.
|
||||
* An event that is broadcast when a plugin leaves the {@link State#ACTIVE}
|
||||
* state.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class TransportDisabledEvent extends Event {
|
||||
public class TransportInactiveEvent extends Event {
|
||||
|
||||
private final TransportId transportId;
|
||||
|
||||
public TransportDisabledEvent(TransportId transportId) {
|
||||
public TransportInactiveEvent(TransportId transportId) {
|
||||
this.transportId = transportId;
|
||||
}
|
||||
|
||||
@@ -1,26 +1,32 @@
|
||||
package org.briarproject.bramble.api.sync.event;
|
||||
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 all sync connections using a given
|
||||
* transport should be closed.
|
||||
* An event that is broadcast when the {@link State state} of a plugin changes.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class CloseSyncConnectionsEvent extends Event {
|
||||
public class TransportStateEvent extends Event {
|
||||
|
||||
private final TransportId transportId;
|
||||
private final State state;
|
||||
|
||||
public CloseSyncConnectionsEvent(TransportId transportId) {
|
||||
public TransportStateEvent(TransportId transportId, State state) {
|
||||
this.transportId = transportId;
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public TransportId getTransportId() {
|
||||
return transportId;
|
||||
}
|
||||
|
||||
public State getState() {
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -11,28 +11,4 @@ public interface TransportPropertyConstants {
|
||||
* The maximum length of a property's key or value in UTF-8 bytes.
|
||||
*/
|
||||
int MAX_PROPERTY_LENGTH = 100;
|
||||
|
||||
/**
|
||||
* Message metadata key for the transport ID of a local or remote update,
|
||||
* as a BDF string.
|
||||
*/
|
||||
String MSG_KEY_TRANSPORT_ID = "transportId";
|
||||
|
||||
/**
|
||||
* Message metadata key for the version number of a local or remote update,
|
||||
* as a BDF long.
|
||||
*/
|
||||
String MSG_KEY_VERSION = "version";
|
||||
|
||||
/**
|
||||
* Message metadata key for whether an update is local or remote, as a BDF
|
||||
* boolean.
|
||||
*/
|
||||
String MSG_KEY_LOCAL = "local";
|
||||
|
||||
/**
|
||||
* Group metadata key for any discovered transport properties of the
|
||||
* contact, as a BDF dictionary.
|
||||
*/
|
||||
String GROUP_KEY_DISCOVERED = "discovered";
|
||||
}
|
||||
|
||||
@@ -34,14 +34,6 @@ public interface TransportPropertyManager {
|
||||
void addRemoteProperties(Transaction txn, ContactId c,
|
||||
Map<TransportId, TransportProperties> props) throws DbException;
|
||||
|
||||
/**
|
||||
* Stores the given properties discovered from an incoming transport
|
||||
* connection. They will be overridden by any properties received while
|
||||
* adding the contact or synced from the contact.
|
||||
*/
|
||||
void addRemotePropertiesFromConnection(ContactId c, TransportId t,
|
||||
TransportProperties props) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the local transport properties for all transports.
|
||||
*/
|
||||
|
||||
@@ -2,7 +2,6 @@ package org.briarproject.bramble.api.sync;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.transport.StreamWriter;
|
||||
|
||||
import java.io.InputStream;
|
||||
@@ -12,9 +11,9 @@ public interface SyncSessionFactory {
|
||||
|
||||
SyncSession createIncomingSession(ContactId c, InputStream in);
|
||||
|
||||
SyncSession createSimplexOutgoingSession(ContactId c, TransportId t,
|
||||
int maxLatency, StreamWriter streamWriter);
|
||||
SyncSession createSimplexOutgoingSession(ContactId c, int maxLatency,
|
||||
StreamWriter streamWriter);
|
||||
|
||||
SyncSession createDuplexOutgoingSession(ContactId c, TransportId t,
|
||||
int maxLatency, int maxIdleTime, StreamWriter streamWriter);
|
||||
SyncSession createDuplexOutgoingSession(ContactId c, int maxLatency,
|
||||
int maxIdleTime, StreamWriter streamWriter);
|
||||
}
|
||||
|
||||
@@ -117,10 +117,4 @@ public class IoUtils {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isNonEmptyDirectory(File f) {
|
||||
if (!f.isDirectory()) return false;
|
||||
File[] children = f.listFiles();
|
||||
return children != null && children.length > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import org.briarproject.bramble.db.DatabaseExecutorModule;
|
||||
import org.briarproject.bramble.db.DatabaseModule;
|
||||
import org.briarproject.bramble.event.EventModule;
|
||||
import org.briarproject.bramble.identity.IdentityModule;
|
||||
import org.briarproject.bramble.io.IoModule;
|
||||
import org.briarproject.bramble.keyagreement.KeyAgreementModule;
|
||||
import org.briarproject.bramble.lifecycle.LifecycleModule;
|
||||
import org.briarproject.bramble.plugin.PluginModule;
|
||||
@@ -36,7 +35,6 @@ import dagger.Module;
|
||||
DatabaseExecutorModule.class,
|
||||
EventModule.class,
|
||||
IdentityModule.class,
|
||||
IoModule.class,
|
||||
KeyAgreementModule.class,
|
||||
LifecycleModule.class,
|
||||
PluginModule.class,
|
||||
|
||||
@@ -2,7 +2,6 @@ package org.briarproject.bramble.account;
|
||||
|
||||
import org.briarproject.bramble.api.account.AccountManager;
|
||||
import org.briarproject.bramble.api.crypto.CryptoComponent;
|
||||
import org.briarproject.bramble.api.crypto.DecryptionException;
|
||||
import org.briarproject.bramble.api.crypto.KeyStrengthener;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
@@ -18,7 +17,6 @@ import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
@@ -26,7 +24,6 @@ import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static org.briarproject.bramble.api.crypto.DecryptionResult.INVALID_CIPHERTEXT;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
import static org.briarproject.bramble.util.StringUtils.fromHexString;
|
||||
import static org.briarproject.bramble.util.StringUtils.toHexString;
|
||||
@@ -98,7 +95,7 @@ class AccountManagerImpl implements AccountManager {
|
||||
}
|
||||
try {
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(
|
||||
new FileInputStream(f), Charset.forName("UTF-8")));
|
||||
new FileInputStream(f), "UTF-8"));
|
||||
String key = reader.readLine();
|
||||
reader.close();
|
||||
return key;
|
||||
@@ -150,7 +147,7 @@ class AccountManagerImpl implements AccountManager {
|
||||
@GuardedBy("stateChangeLock")
|
||||
private void writeDbKeyToFile(String key, File f) throws IOException {
|
||||
FileOutputStream out = new FileOutputStream(f);
|
||||
out.write(key.getBytes(Charset.forName("UTF-8")));
|
||||
out.write(key.getBytes("UTF-8"));
|
||||
out.flush();
|
||||
out.close();
|
||||
}
|
||||
@@ -158,7 +155,8 @@ class AccountManagerImpl implements AccountManager {
|
||||
@Override
|
||||
public boolean accountExists() {
|
||||
synchronized (stateChangeLock) {
|
||||
return loadEncryptedDatabaseKey() != null;
|
||||
return loadEncryptedDatabaseKey() != null
|
||||
&& databaseConfig.getDatabaseDirectory().isDirectory();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,24 +193,31 @@ class AccountManagerImpl implements AccountManager {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void signIn(String password) throws DecryptionException {
|
||||
public boolean signIn(String password) {
|
||||
synchronized (stateChangeLock) {
|
||||
databaseKey = loadAndDecryptDatabaseKey(password);
|
||||
SecretKey key = loadAndDecryptDatabaseKey(password);
|
||||
if (key == null) return false;
|
||||
databaseKey = key;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@GuardedBy("stateChangeLock")
|
||||
private SecretKey loadAndDecryptDatabaseKey(String password)
|
||||
throws DecryptionException {
|
||||
@Nullable
|
||||
private SecretKey loadAndDecryptDatabaseKey(String password) {
|
||||
String hex = loadEncryptedDatabaseKey();
|
||||
if (hex == null) {
|
||||
LOG.warning("Failed to load encrypted database key");
|
||||
throw new DecryptionException(INVALID_CIPHERTEXT);
|
||||
return null;
|
||||
}
|
||||
byte[] ciphertext = fromHexString(hex);
|
||||
KeyStrengthener keyStrengthener = databaseConfig.getKeyStrengthener();
|
||||
byte[] plaintext = crypto.decryptWithPassword(ciphertext, password,
|
||||
keyStrengthener);
|
||||
if (plaintext == null) {
|
||||
LOG.info("Failed to decrypt database key");
|
||||
return null;
|
||||
}
|
||||
SecretKey key = new SecretKey(plaintext);
|
||||
// If the DB key was encrypted with a weak key and a key strengthener
|
||||
// is now available, re-encrypt the DB key with a strengthened key
|
||||
@@ -225,11 +230,10 @@ class AccountManagerImpl implements AccountManager {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void changePassword(String oldPassword, String newPassword)
|
||||
throws DecryptionException {
|
||||
public boolean changePassword(String oldPassword, String newPassword) {
|
||||
synchronized (stateChangeLock) {
|
||||
SecretKey key = loadAndDecryptDatabaseKey(oldPassword);
|
||||
encryptAndStoreDatabaseKey(key, newPassword);
|
||||
return key != null && encryptAndStoreDatabaseKey(key, newPassword);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import net.i2p.crypto.eddsa.KeyPairGenerator;
|
||||
import org.briarproject.bramble.api.crypto.AgreementPrivateKey;
|
||||
import org.briarproject.bramble.api.crypto.AgreementPublicKey;
|
||||
import org.briarproject.bramble.api.crypto.CryptoComponent;
|
||||
import org.briarproject.bramble.api.crypto.DecryptionException;
|
||||
import org.briarproject.bramble.api.crypto.KeyPair;
|
||||
import org.briarproject.bramble.api.crypto.KeyParser;
|
||||
import org.briarproject.bramble.api.crypto.KeyStrengthener;
|
||||
@@ -40,9 +39,6 @@ import static java.lang.System.arraycopy;
|
||||
import static java.util.logging.Level.INFO;
|
||||
import static org.briarproject.bramble.api.crypto.CryptoConstants.KEY_TYPE_AGREEMENT;
|
||||
import static org.briarproject.bramble.api.crypto.CryptoConstants.KEY_TYPE_SIGNATURE;
|
||||
import static org.briarproject.bramble.api.crypto.DecryptionResult.INVALID_CIPHERTEXT;
|
||||
import static org.briarproject.bramble.api.crypto.DecryptionResult.INVALID_PASSWORD;
|
||||
import static org.briarproject.bramble.api.crypto.DecryptionResult.KEY_STRENGTHENER_ERROR;
|
||||
import static org.briarproject.bramble.util.ByteUtils.INT_32_BYTES;
|
||||
import static org.briarproject.bramble.util.LogUtils.logDuration;
|
||||
import static org.briarproject.bramble.util.LogUtils.now;
|
||||
@@ -363,17 +359,16 @@ class CryptoComponentImpl implements CryptoComponent {
|
||||
}
|
||||
|
||||
@Override
|
||||
@Nullable
|
||||
public byte[] decryptWithPassword(byte[] input, String password,
|
||||
@Nullable KeyStrengthener keyStrengthener)
|
||||
throws DecryptionException {
|
||||
@Nullable KeyStrengthener keyStrengthener) {
|
||||
AuthenticatedCipher cipher = new XSalsa20Poly1305AuthenticatedCipher();
|
||||
int macBytes = cipher.getMacBytes();
|
||||
// The input contains the format version, salt, cost parameter, IV,
|
||||
// ciphertext and MAC
|
||||
if (input.length < 1 + PBKDF_SALT_BYTES + INT_32_BYTES
|
||||
+ STORAGE_IV_BYTES + macBytes) {
|
||||
throw new DecryptionException(INVALID_CIPHERTEXT);
|
||||
}
|
||||
+ STORAGE_IV_BYTES + macBytes)
|
||||
return null; // Invalid input
|
||||
int inputOff = 0;
|
||||
// Format version
|
||||
byte formatVersion = input[inputOff];
|
||||
@@ -381,7 +376,7 @@ class CryptoComponentImpl implements CryptoComponent {
|
||||
// Check whether we support this format version
|
||||
if (formatVersion != PBKDF_FORMAT_SCRYPT &&
|
||||
formatVersion != PBKDF_FORMAT_SCRYPT_STRENGTHENED) {
|
||||
throw new DecryptionException(INVALID_CIPHERTEXT);
|
||||
return null;
|
||||
}
|
||||
// Salt
|
||||
byte[] salt = new byte[PBKDF_SALT_BYTES];
|
||||
@@ -390,9 +385,8 @@ class CryptoComponentImpl implements CryptoComponent {
|
||||
// Cost parameter
|
||||
long cost = ByteUtils.readUint32(input, inputOff);
|
||||
inputOff += INT_32_BYTES;
|
||||
if (cost < 2 || cost > Integer.MAX_VALUE) {
|
||||
throw new DecryptionException(INVALID_CIPHERTEXT);
|
||||
}
|
||||
if (cost < 2 || cost > Integer.MAX_VALUE)
|
||||
return null; // Invalid cost parameter
|
||||
// IV
|
||||
byte[] iv = new byte[STORAGE_IV_BYTES];
|
||||
arraycopy(input, inputOff, iv, 0, iv.length);
|
||||
@@ -400,10 +394,8 @@ class CryptoComponentImpl implements CryptoComponent {
|
||||
// Derive the decryption key from the password
|
||||
SecretKey key = passwordBasedKdf.deriveKey(password, salt, (int) cost);
|
||||
if (formatVersion == PBKDF_FORMAT_SCRYPT_STRENGTHENED) {
|
||||
if (keyStrengthener == null || !keyStrengthener.isInitialised()) {
|
||||
// Can't derive the same strengthened key
|
||||
throw new DecryptionException(KEY_STRENGTHENER_ERROR);
|
||||
}
|
||||
if (keyStrengthener == null || !keyStrengthener.isInitialised())
|
||||
return null; // Can't derive the same strengthened key
|
||||
key = keyStrengthener.strengthenKey(key);
|
||||
}
|
||||
// Initialise the cipher
|
||||
@@ -419,7 +411,7 @@ class CryptoComponentImpl implements CryptoComponent {
|
||||
cipher.process(input, inputOff, inputLen, output, 0);
|
||||
return output;
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new DecryptionException(INVALID_PASSWORD);
|
||||
return null; // Invalid ciphertext
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,6 @@ 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.db.JdbcUtils.tryToClose;
|
||||
import static org.briarproject.bramble.util.IoUtils.isNonEmptyDirectory;
|
||||
import static org.briarproject.bramble.util.LogUtils.logFileOrDir;
|
||||
|
||||
/**
|
||||
@@ -70,9 +69,8 @@ class H2Database extends JdbcDatabase {
|
||||
LOG.info("Contents of account directory before opening DB:");
|
||||
logFileOrDir(LOG, INFO, dir.getParentFile());
|
||||
}
|
||||
boolean reopen = isNonEmptyDirectory(dir);
|
||||
boolean reopen = !dir.mkdirs();
|
||||
if (LOG.isLoggable(INFO)) LOG.info("Reopening DB: " + reopen);
|
||||
if (!reopen && dir.mkdirs()) LOG.info("Created database directory");
|
||||
super.open("org.h2.Driver", reopen, key, listener);
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Contents of account directory after opening DB:");
|
||||
|
||||
@@ -20,11 +20,9 @@ import java.util.logging.Logger;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
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.db.JdbcUtils.tryToClose;
|
||||
import static org.briarproject.bramble.util.IoUtils.isNonEmptyDirectory;
|
||||
|
||||
/**
|
||||
* Contains all the HSQLDB-specific code for the database.
|
||||
@@ -66,10 +64,7 @@ class HyperSqlDatabase extends JdbcDatabase {
|
||||
public boolean open(SecretKey key, @Nullable MigrationListener listener)
|
||||
throws DbException {
|
||||
this.key = key;
|
||||
File dir = config.getDatabaseDirectory();
|
||||
boolean reopen = isNonEmptyDirectory(dir);
|
||||
if (LOG.isLoggable(INFO)) LOG.info("Reopening DB: " + reopen);
|
||||
if (!reopen && dir.mkdirs()) LOG.info("Created database directory");
|
||||
boolean reopen = !config.getDatabaseDirectory().mkdirs();
|
||||
super.open("org.hsqldb.jdbc.JDBCDriver", reopen, key, listener);
|
||||
return reopen;
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
package org.briarproject.bramble.io;
|
||||
|
||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import dagger.Module;
|
||||
import dagger.Provides;
|
||||
|
||||
@Module
|
||||
public class IoModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
TimeoutMonitor provideTimeoutMonitor(TimeoutMonitorImpl timeoutMonitor) {
|
||||
return timeoutMonitor;
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package org.briarproject.bramble.io;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
|
||||
@NotNullByDefault
|
||||
class TimeoutInputStream extends InputStream {
|
||||
|
||||
private final Clock clock;
|
||||
private final InputStream in;
|
||||
private final long timeoutMs;
|
||||
private final CloseListener listener;
|
||||
private final Object lock = new Object();
|
||||
@GuardedBy("lock")
|
||||
private long readStartedMs = -1;
|
||||
|
||||
TimeoutInputStream(Clock clock, InputStream in, long timeoutMs,
|
||||
CloseListener listener) {
|
||||
this.clock = clock;
|
||||
this.in = in;
|
||||
this.timeoutMs = timeoutMs;
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
synchronized (lock) {
|
||||
readStartedMs = clock.currentTimeMillis();
|
||||
}
|
||||
int input = in.read();
|
||||
synchronized (lock) {
|
||||
readStartedMs = -1;
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] b) throws IOException {
|
||||
return read(b, 0, b.length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] b, int off, int len) throws IOException {
|
||||
synchronized (lock) {
|
||||
readStartedMs = clock.currentTimeMillis();
|
||||
}
|
||||
int read = in.read(b, off, len);
|
||||
synchronized (lock) {
|
||||
readStartedMs = -1;
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
try {
|
||||
in.close();
|
||||
} finally {
|
||||
listener.onClose(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int available() throws IOException {
|
||||
return in.available();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void mark(int readlimit) {
|
||||
in.mark(readlimit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean markSupported() {
|
||||
return in.markSupported();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() throws IOException {
|
||||
in.reset();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long skip(long n) throws IOException {
|
||||
return in.skip(n);
|
||||
}
|
||||
|
||||
boolean hasTimedOut() {
|
||||
synchronized (lock) {
|
||||
return readStartedMs != -1 &&
|
||||
clock.currentTimeMillis() - readStartedMs > timeoutMs;
|
||||
}
|
||||
}
|
||||
|
||||
interface CloseListener {
|
||||
|
||||
void onClose(TimeoutInputStream closed);
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
package org.briarproject.bramble.io;
|
||||
|
||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.api.system.Scheduler;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
import static java.util.logging.Level.INFO;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
|
||||
class TimeoutMonitorImpl implements TimeoutMonitor {
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(TimeoutMonitorImpl.class.getName());
|
||||
|
||||
private static final long CHECK_INTERVAL_MS = SECONDS.toMillis(10);
|
||||
|
||||
private final ScheduledExecutorService scheduler;
|
||||
private final Executor ioExecutor;
|
||||
private final Clock clock;
|
||||
private final Object lock = new Object();
|
||||
@GuardedBy("lock")
|
||||
private final List<TimeoutInputStream> streams = new ArrayList<>();
|
||||
|
||||
@GuardedBy("lock")
|
||||
private Future<?> task = null;
|
||||
|
||||
@Inject
|
||||
TimeoutMonitorImpl(@Scheduler ScheduledExecutorService scheduler,
|
||||
@IoExecutor Executor ioExecutor, Clock clock) {
|
||||
this.scheduler = scheduler;
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream createTimeoutInputStream(InputStream in,
|
||||
long timeoutMs) {
|
||||
TimeoutInputStream stream = new TimeoutInputStream(clock, in,
|
||||
timeoutMs, this::removeStream);
|
||||
synchronized (lock) {
|
||||
if (streams.isEmpty()) {
|
||||
task = scheduler.scheduleWithFixedDelay(this::checkTimeouts,
|
||||
CHECK_INTERVAL_MS, CHECK_INTERVAL_MS, MILLISECONDS);
|
||||
}
|
||||
streams.add(stream);
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
private void removeStream(TimeoutInputStream stream) {
|
||||
Future<?> toCancel = null;
|
||||
synchronized (lock) {
|
||||
if (streams.remove(stream) && streams.isEmpty()) {
|
||||
toCancel = task;
|
||||
task = null;
|
||||
}
|
||||
}
|
||||
if (toCancel != null) toCancel.cancel(false);
|
||||
}
|
||||
|
||||
@Scheduler
|
||||
private void checkTimeouts() {
|
||||
ioExecutor.execute(() -> {
|
||||
List<TimeoutInputStream> snapshot;
|
||||
synchronized (lock) {
|
||||
snapshot = new ArrayList<>(streams);
|
||||
}
|
||||
for (TimeoutInputStream stream : snapshot) {
|
||||
if (stream.hasTimedOut()) {
|
||||
LOG.info("Input stream has timed out");
|
||||
try {
|
||||
stream.close();
|
||||
} catch (IOException e) {
|
||||
logException(LOG, INFO, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,6 @@ import org.briarproject.bramble.api.plugin.TransportConnectionReader;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
||||
import org.briarproject.bramble.api.sync.SyncSession;
|
||||
import org.briarproject.bramble.api.sync.SyncSessionFactory;
|
||||
import org.briarproject.bramble.api.transport.KeyManager;
|
||||
@@ -54,7 +52,6 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
private final HandshakeManager handshakeManager;
|
||||
private final ContactExchangeManager contactExchangeManager;
|
||||
private final ConnectionRegistry connectionRegistry;
|
||||
private final TransportPropertyManager transportPropertyManager;
|
||||
|
||||
@Inject
|
||||
ConnectionManagerImpl(@IoExecutor Executor ioExecutor,
|
||||
@@ -63,8 +60,7 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
SyncSessionFactory syncSessionFactory,
|
||||
HandshakeManager handshakeManager,
|
||||
ContactExchangeManager contactExchangeManager,
|
||||
ConnectionRegistry connectionRegistry,
|
||||
TransportPropertyManager transportPropertyManager) {
|
||||
ConnectionRegistry connectionRegistry) {
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.keyManager = keyManager;
|
||||
this.streamReaderFactory = streamReaderFactory;
|
||||
@@ -73,7 +69,6 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
this.handshakeManager = handshakeManager;
|
||||
this.contactExchangeManager = contactExchangeManager;
|
||||
this.connectionRegistry = connectionRegistry;
|
||||
this.transportPropertyManager = transportPropertyManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -130,8 +125,8 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
TransportConnectionWriter w) throws IOException {
|
||||
StreamWriter streamWriter = streamWriterFactory.createStreamWriter(
|
||||
w.getOutputStream(), ctx);
|
||||
return syncSessionFactory.createSimplexOutgoingSession(
|
||||
requireNonNull(ctx.getContactId()), ctx.getTransportId(),
|
||||
ContactId c = requireNonNull(ctx.getContactId());
|
||||
return syncSessionFactory.createSimplexOutgoingSession(c,
|
||||
w.getMaxLatency(), streamWriter);
|
||||
}
|
||||
|
||||
@@ -139,8 +134,8 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
TransportConnectionWriter w) throws IOException {
|
||||
StreamWriter streamWriter = streamWriterFactory.createStreamWriter(
|
||||
w.getOutputStream(), ctx);
|
||||
return syncSessionFactory.createDuplexOutgoingSession(
|
||||
requireNonNull(ctx.getContactId()), ctx.getTransportId(),
|
||||
ContactId c = requireNonNull(ctx.getContactId());
|
||||
return syncSessionFactory.createDuplexOutgoingSession(c,
|
||||
w.getMaxLatency(), w.getMaxIdleTime(), streamWriter);
|
||||
}
|
||||
|
||||
@@ -274,7 +269,6 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
private final TransportId transportId;
|
||||
private final TransportConnectionReader reader;
|
||||
private final TransportConnectionWriter writer;
|
||||
private final TransportProperties remote;
|
||||
|
||||
@Nullable
|
||||
private volatile SyncSession outgoingSession = null;
|
||||
@@ -284,7 +278,6 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
this.transportId = transportId;
|
||||
reader = connection.getReader();
|
||||
writer = connection.getWriter();
|
||||
remote = connection.getRemoteProperties();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -320,16 +313,13 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
// Start the outgoing session on another thread
|
||||
ioExecutor.execute(() -> runOutgoingSession(contactId));
|
||||
try {
|
||||
// Store any transport properties discovered from the connection
|
||||
transportPropertyManager.addRemotePropertiesFromConnection(
|
||||
contactId, transportId, remote);
|
||||
// Create and run the incoming session
|
||||
createIncomingSession(ctx, reader).run();
|
||||
reader.dispose(false, true);
|
||||
// Interrupt the outgoing session so it finishes cleanly
|
||||
SyncSession out = outgoingSession;
|
||||
if (out != null) out.interrupt();
|
||||
} catch (DbException | IOException e) {
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
onReadError(true);
|
||||
} finally {
|
||||
@@ -385,7 +375,6 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
private final TransportId transportId;
|
||||
private final TransportConnectionReader reader;
|
||||
private final TransportConnectionWriter writer;
|
||||
private final TransportProperties remote;
|
||||
|
||||
@Nullable
|
||||
private volatile SyncSession outgoingSession = null;
|
||||
@@ -396,7 +385,6 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
this.transportId = transportId;
|
||||
reader = connection.getReader();
|
||||
writer = connection.getWriter();
|
||||
remote = connection.getRemoteProperties();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -473,16 +461,13 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
connectionRegistry.registerConnection(contactId, transportId,
|
||||
false);
|
||||
try {
|
||||
// Store any transport properties discovered from the connection
|
||||
transportPropertyManager.addRemotePropertiesFromConnection(
|
||||
contactId, transportId, remote);
|
||||
// Create and run the incoming session
|
||||
createIncomingSession(ctx, reader).run();
|
||||
reader.dispose(false, true);
|
||||
// Interrupt the outgoing session so it finishes cleanly
|
||||
SyncSession out = outgoingSession;
|
||||
if (out != null) out.interrupt();
|
||||
} catch (DbException | IOException e) {
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
onReadError();
|
||||
} finally {
|
||||
|
||||
@@ -8,6 +8,7 @@ import org.briarproject.bramble.api.lifecycle.ServiceException;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.ConnectionManager;
|
||||
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.PluginConfig;
|
||||
import org.briarproject.bramble.api.plugin.PluginException;
|
||||
@@ -18,8 +19,9 @@ import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportDisabledEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
|
||||
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.plugin.simplex.SimplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.simplex.SimplexPluginFactory;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
@@ -36,6 +38,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
@@ -45,6 +48,9 @@ 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.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.util.LogUtils.logDuration;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
import static org.briarproject.bramble.util.LogUtils.now;
|
||||
@@ -177,6 +183,26 @@ class PluginManagerImpl implements PluginManager, Service {
|
||||
return supported;
|
||||
}
|
||||
|
||||
@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 class PluginStarter implements Runnable {
|
||||
|
||||
private final Plugin plugin;
|
||||
@@ -250,7 +276,8 @@ class PluginManagerImpl implements PluginManager, Service {
|
||||
private class Callback implements PluginCallback {
|
||||
|
||||
private final TransportId id;
|
||||
private final AtomicBoolean enabled = new AtomicBoolean(false);
|
||||
private final AtomicReference<State> state =
|
||||
new AtomicReference<>(DISABLED);
|
||||
|
||||
private Callback(TransportId id) {
|
||||
this.id = id;
|
||||
@@ -278,11 +305,7 @@ class PluginManagerImpl implements PluginManager, Service {
|
||||
|
||||
@Override
|
||||
public void mergeSettings(Settings s) {
|
||||
try {
|
||||
settingsManager.mergeSettings(s, id.getString());
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
PluginManagerImpl.this.mergeSettings(s, id.getString());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -295,15 +318,20 @@ class PluginManagerImpl implements PluginManager, Service {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transportEnabled() {
|
||||
if (!enabled.getAndSet(true))
|
||||
eventBus.broadcast(new TransportEnabledEvent(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transportDisabled() {
|
||||
if (enabled.getAndSet(false))
|
||||
eventBus.broadcast(new TransportDisabledEvent(id));
|
||||
public void pluginStateChanged(State newState) {
|
||||
State oldState = state.getAndSet(newState);
|
||||
if (newState != oldState) {
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info(id + " changed from state " + oldState
|
||||
+ " to " + newState);
|
||||
}
|
||||
eventBus.broadcast(new TransportStateEvent(id, newState));
|
||||
if (newState == ACTIVE) {
|
||||
eventBus.broadcast(new TransportActiveEvent(id));
|
||||
} else if (oldState == ACTIVE) {
|
||||
eventBus.broadcast(new TransportInactiveEvent(id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -20,8 +20,8 @@ import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.plugin.event.ConnectionClosedEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.ConnectionOpenedEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportDisabledEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportActiveEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||
import org.briarproject.bramble.api.plugin.simplex.SimplexPlugin;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
||||
@@ -106,13 +106,13 @@ class PollerImpl implements Poller, EventListener {
|
||||
ConnectionOpenedEvent c = (ConnectionOpenedEvent) e;
|
||||
// Reschedule polling, the polling interval may have decreased
|
||||
reschedule(c.getTransportId());
|
||||
} else if (e instanceof TransportEnabledEvent) {
|
||||
TransportEnabledEvent t = (TransportEnabledEvent) e;
|
||||
// Poll the newly enabled transport
|
||||
} else if (e instanceof TransportActiveEvent) {
|
||||
TransportActiveEvent t = (TransportActiveEvent) e;
|
||||
// Poll the newly activated transport
|
||||
pollNow(t.getTransportId());
|
||||
} else if (e instanceof TransportDisabledEvent) {
|
||||
TransportDisabledEvent t = (TransportDisabledEvent) e;
|
||||
// Cancel polling for the disabled transport
|
||||
} else if (e instanceof TransportInactiveEvent) {
|
||||
TransportInactiveEvent t = (TransportInactiveEvent) e;
|
||||
// Cancel polling for the deactivated transport
|
||||
cancel(t.getTransportId());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,30 +3,9 @@ package org.briarproject.bramble.plugin.bluetooth;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
|
||||
import static java.util.concurrent.TimeUnit.DAYS;
|
||||
import static java.util.concurrent.TimeUnit.MINUTES;
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
|
||||
@NotNullByDefault
|
||||
interface BluetoothConnectionLimiter {
|
||||
|
||||
/**
|
||||
* How long a connection must remain open before it's considered stable.
|
||||
*/
|
||||
long STABILITY_PERIOD_MS = SECONDS.toMillis(90);
|
||||
|
||||
/**
|
||||
* The minimum interval between attempts to raise the connection limit.
|
||||
* This is longer than {@link #STABILITY_PERIOD_MS} so we don't start
|
||||
* another attempt before knowing the outcome of the last one.
|
||||
*/
|
||||
long MIN_ATTEMPT_INTERVAL_MS = MINUTES.toMillis(2);
|
||||
|
||||
/**
|
||||
* The maximum interval between attempts to raise the connection limit.
|
||||
*/
|
||||
long MAX_ATTEMPT_INTERVAL_MS = DAYS.toMillis(2);
|
||||
|
||||
/**
|
||||
* Informs the limiter that key agreement has started.
|
||||
*/
|
||||
@@ -44,12 +23,12 @@ interface BluetoothConnectionLimiter {
|
||||
boolean canOpenContactConnection();
|
||||
|
||||
/**
|
||||
* Informs the limiter that a contact connection has been opened.
|
||||
* Informs the limiter that a contact connection has been opened. The
|
||||
* limiter may close the new connection if key agreement is in progress.
|
||||
* <p/>
|
||||
* Returns true if the connection is allowed.
|
||||
* Returns false if the limiter has closed the new connection.
|
||||
*/
|
||||
boolean contactConnectionOpened(DuplexTransportConnection conn,
|
||||
boolean incoming);
|
||||
boolean contactConnectionOpened(DuplexTransportConnection conn);
|
||||
|
||||
/**
|
||||
* Informs the limiter that a key agreement connection has been opened.
|
||||
@@ -58,13 +37,11 @@ interface BluetoothConnectionLimiter {
|
||||
|
||||
/**
|
||||
* Informs the limiter that the given connection has been closed.
|
||||
*
|
||||
* @param exception True if the connection was closed due to an exception.
|
||||
*/
|
||||
void connectionClosed(DuplexTransportConnection conn, boolean exception);
|
||||
void connectionClosed(DuplexTransportConnection conn);
|
||||
|
||||
/**
|
||||
* Informs the limiter that the Bluetooth adapter has been disabled.
|
||||
* Informs the limiter that all connections have been closed.
|
||||
*/
|
||||
void bluetoothDisabled();
|
||||
void allConnectionsClosed();
|
||||
}
|
||||
|
||||
@@ -1,59 +1,46 @@
|
||||
package org.briarproject.bramble.plugin.bluetooth;
|
||||
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.sync.event.CloseSyncConnectionsEvent;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static java.lang.Math.min;
|
||||
import static java.util.logging.Level.INFO;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.api.plugin.BluetoothConstants.ID;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
|
||||
@NotNullByDefault
|
||||
@ThreadSafe
|
||||
class BluetoothConnectionLimiterImpl implements BluetoothConnectionLimiter {
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(BluetoothConnectionLimiterImpl.class.getName());
|
||||
|
||||
private final EventBus eventBus;
|
||||
private final Clock clock;
|
||||
Logger.getLogger(BluetoothConnectionLimiterImpl.class.getName());
|
||||
|
||||
private final Object lock = new Object();
|
||||
@GuardedBy("lock")
|
||||
private final List<ConnectionRecord> connections = new LinkedList<>();
|
||||
@GuardedBy("lock")
|
||||
// The following are locking: lock
|
||||
private final LinkedList<DuplexTransportConnection> connections =
|
||||
new LinkedList<>();
|
||||
private boolean keyAgreementInProgress = false;
|
||||
@GuardedBy("lock")
|
||||
private int connectionLimit = 1;
|
||||
@GuardedBy("lock")
|
||||
private long timeOfLastAttempt = 0,
|
||||
attemptInterval = MIN_ATTEMPT_INTERVAL_MS;
|
||||
|
||||
@Inject
|
||||
BluetoothConnectionLimiterImpl(EventBus eventBus, Clock clock) {
|
||||
this.eventBus = eventBus;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void keyAgreementStarted() {
|
||||
List<DuplexTransportConnection> close;
|
||||
synchronized (lock) {
|
||||
keyAgreementInProgress = true;
|
||||
close = new ArrayList<>(connections);
|
||||
connections.clear();
|
||||
}
|
||||
LOG.info("Key agreement started");
|
||||
eventBus.broadcast(new CloseSyncConnectionsEvent(ID));
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Key agreement started, closing " + close.size() +
|
||||
" connections");
|
||||
}
|
||||
for (DuplexTransportConnection conn : close) tryToClose(conn);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -68,128 +55,62 @@ class BluetoothConnectionLimiterImpl implements BluetoothConnectionLimiter {
|
||||
public boolean canOpenContactConnection() {
|
||||
synchronized (lock) {
|
||||
if (keyAgreementInProgress) {
|
||||
LOG.info("Refusing contact connection during key agreement");
|
||||
LOG.info("Can't open contact connection during key agreement");
|
||||
return false;
|
||||
} else {
|
||||
long now = clock.currentTimeMillis();
|
||||
return isContactConnectionAllowedByLimit(now);
|
||||
LOG.info("Can open contact connection");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contactConnectionOpened(DuplexTransportConnection conn,
|
||||
boolean incoming) {
|
||||
public boolean contactConnectionOpened(DuplexTransportConnection conn) {
|
||||
boolean accept = true;
|
||||
synchronized (lock) {
|
||||
if (keyAgreementInProgress) {
|
||||
LOG.info("Refusing contact connection during key agreement");
|
||||
return false;
|
||||
accept = false;
|
||||
} else {
|
||||
long now = clock.currentTimeMillis();
|
||||
if (incoming || isContactConnectionAllowedByLimit(now)) {
|
||||
connections.add(new ConnectionRecord(conn, now));
|
||||
if (!incoming && connections.size() > connectionLimit) {
|
||||
LOG.info("Attempting to raise connection limit");
|
||||
timeOfLastAttempt = now;
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
LOG.info("Accepting contact connection");
|
||||
connections.add(conn);
|
||||
}
|
||||
}
|
||||
if (!accept) tryToClose(conn);
|
||||
return accept;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void keyAgreementConnectionOpened(DuplexTransportConnection conn) {
|
||||
synchronized (lock) {
|
||||
LOG.info("Accepting key agreement connection");
|
||||
connections.add(
|
||||
new ConnectionRecord(conn, clock.currentTimeMillis()));
|
||||
connections.add(conn);
|
||||
}
|
||||
}
|
||||
|
||||
private void tryToClose(DuplexTransportConnection conn) {
|
||||
try {
|
||||
conn.getWriter().dispose(false);
|
||||
conn.getReader().dispose(false, false);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionClosed(DuplexTransportConnection conn,
|
||||
boolean exception) {
|
||||
public void connectionClosed(DuplexTransportConnection conn) {
|
||||
synchronized (lock) {
|
||||
Iterator<ConnectionRecord> it = connections.iterator();
|
||||
while (it.hasNext()) {
|
||||
if (it.next().connection == conn) {
|
||||
long now = clock.currentTimeMillis();
|
||||
if (exception) connectionFailed(now);
|
||||
else considerRaisingConnectionLimit(now);
|
||||
it.remove();
|
||||
break;
|
||||
}
|
||||
}
|
||||
connections.remove(conn);
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Connection closed, " + connections.size() + " open");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void bluetoothDisabled() {
|
||||
public void allConnectionsClosed() {
|
||||
synchronized (lock) {
|
||||
LOG.info("Bluetooth disabled");
|
||||
considerRaisingConnectionLimit(clock.currentTimeMillis());
|
||||
connections.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@GuardedBy("lock")
|
||||
private boolean isContactConnectionAllowedByLimit(long now) {
|
||||
considerRaisingConnectionLimit(now);
|
||||
if (connections.size() > connectionLimit) {
|
||||
LOG.info("Refusing contact connection, above limit");
|
||||
return false;
|
||||
} else if (connections.size() < connectionLimit) {
|
||||
LOG.info("Allowing contact connection, below limit");
|
||||
return true;
|
||||
} else if (now - timeOfLastAttempt >= attemptInterval) {
|
||||
LOG.info("Allowing contact connection, at limit");
|
||||
return true;
|
||||
} else {
|
||||
LOG.info("Refusing contact connection, at limit");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@GuardedBy("lock")
|
||||
private void considerRaisingConnectionLimit(long now) {
|
||||
int stable = 0;
|
||||
for (ConnectionRecord rec : connections) {
|
||||
if (now - rec.timeOpened >= STABILITY_PERIOD_MS) stable++;
|
||||
}
|
||||
if (stable > connectionLimit) {
|
||||
LOG.info("Raising connection limit");
|
||||
connectionLimit = stable;
|
||||
attemptInterval = MIN_ATTEMPT_INTERVAL_MS;
|
||||
}
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info(stable + " connections are stable, limit is "
|
||||
+ connectionLimit);
|
||||
}
|
||||
}
|
||||
|
||||
@GuardedBy("lock")
|
||||
private void connectionFailed(long now) {
|
||||
if (connections.size() > connectionLimit &&
|
||||
now - timeOfLastAttempt < STABILITY_PERIOD_MS) {
|
||||
LOG.info("Connection failed above limit, increasing interval");
|
||||
attemptInterval = min(attemptInterval * 2, MAX_ATTEMPT_INTERVAL_MS);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ConnectionRecord {
|
||||
|
||||
private final DuplexTransportConnection connection;
|
||||
private final long timeOpened;
|
||||
|
||||
private ConnectionRecord(DuplexTransportConnection connection,
|
||||
long timeOpened) {
|
||||
this.connection = connection;
|
||||
this.timeOpened = timeOpened;
|
||||
LOG.info("All connections closed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,13 @@ import org.briarproject.bramble.api.Pair;
|
||||
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.io.TimeoutMonitor;
|
||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementConnection;
|
||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
|
||||
import org.briarproject.bramble.api.keyagreement.event.KeyAgreementListeningEvent;
|
||||
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.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Backoff;
|
||||
import org.briarproject.bramble.api.plugin.ConnectionHandler;
|
||||
@@ -37,16 +38,21 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
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.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TRANSPORT_ID_BLUETOOTH;
|
||||
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.PROP_ADDRESS;
|
||||
import static org.briarproject.bramble.api.plugin.BluetoothConstants.PROP_UUID;
|
||||
import static org.briarproject.bramble.api.plugin.BluetoothConstants.REASON_NO_BT_ADAPTER;
|
||||
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.util.LogUtils.logException;
|
||||
import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress;
|
||||
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
||||
@@ -61,18 +67,17 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
getLogger(BluetoothPlugin.class.getName());
|
||||
|
||||
final BluetoothConnectionLimiter connectionLimiter;
|
||||
final TimeoutMonitor timeoutMonitor;
|
||||
|
||||
private final Executor ioExecutor;
|
||||
private final SecureRandom secureRandom;
|
||||
private final Backoff backoff;
|
||||
private final PluginCallback callback;
|
||||
private final int maxLatency, maxIdleTime;
|
||||
private final int maxLatency;
|
||||
private final AtomicBoolean used = new AtomicBoolean(false);
|
||||
|
||||
private volatile boolean running = false, contactConnections = false;
|
||||
protected final PluginState state = new PluginState();
|
||||
|
||||
private volatile String contactConnectionsUuid = null;
|
||||
private volatile SS socket = null;
|
||||
|
||||
abstract void initialiseAdapter() throws IOException;
|
||||
|
||||
@@ -107,31 +112,32 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
abstract DuplexTransportConnection discoverAndConnect(String uuid);
|
||||
|
||||
BluetoothPlugin(BluetoothConnectionLimiter connectionLimiter,
|
||||
TimeoutMonitor timeoutMonitor, Executor ioExecutor,
|
||||
SecureRandom secureRandom, Backoff backoff,
|
||||
PluginCallback callback, int maxLatency, int maxIdleTime) {
|
||||
Executor ioExecutor, SecureRandom secureRandom,
|
||||
Backoff backoff, PluginCallback callback, int maxLatency) {
|
||||
this.connectionLimiter = connectionLimiter;
|
||||
this.timeoutMonitor = timeoutMonitor;
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.secureRandom = secureRandom;
|
||||
this.backoff = backoff;
|
||||
this.callback = callback;
|
||||
this.maxLatency = maxLatency;
|
||||
this.maxIdleTime = maxIdleTime;
|
||||
}
|
||||
|
||||
void onAdapterEnabled() {
|
||||
LOG.info("Bluetooth enabled");
|
||||
// We may not have been able to get the local address before
|
||||
ioExecutor.execute(this::updateProperties);
|
||||
if (shouldAllowContactConnections()) bind();
|
||||
if (getState() == INACTIVE) bind();
|
||||
}
|
||||
|
||||
void onAdapterDisabled() {
|
||||
LOG.info("Bluetooth disabled");
|
||||
tryToClose(socket);
|
||||
connectionLimiter.bluetoothDisabled();
|
||||
callback.transportDisabled();
|
||||
connectionLimiter.allConnectionsClosed();
|
||||
// The server socket may not have been closed automatically
|
||||
SS ss = state.clearServerSocket();
|
||||
if (ss != null) {
|
||||
LOG.info("Closing server socket");
|
||||
tryToClose(ss);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -146,7 +152,8 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
|
||||
@Override
|
||||
public int getMaxIdleTime() {
|
||||
return maxIdleTime;
|
||||
// Bluetooth detects dead connections so we don't need keepalives
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -155,28 +162,22 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
try {
|
||||
initialiseAdapter();
|
||||
} catch (IOException e) {
|
||||
state.setNoAdapter();
|
||||
throw new PluginException(e);
|
||||
}
|
||||
updateProperties();
|
||||
running = true;
|
||||
loadSettings(callback.getSettings());
|
||||
if (shouldAllowContactConnections()) {
|
||||
Settings settings = callback.getSettings();
|
||||
boolean enabledByUser = settings.getBoolean(PREF_PLUGIN_ENABLE, false);
|
||||
state.setStarted(enabledByUser);
|
||||
if (enabledByUser) {
|
||||
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() {
|
||||
ioExecutor.execute(() -> {
|
||||
if (!isRunning() || !shouldAllowContactConnections()) return;
|
||||
if (getState() != INACTIVE) return;
|
||||
// Bind a server socket to accept connections from contacts
|
||||
SS ss;
|
||||
try {
|
||||
@@ -185,14 +186,13 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
logException(LOG, WARNING, e);
|
||||
return;
|
||||
}
|
||||
if (!isRunning() || !shouldAllowContactConnections()) {
|
||||
if (!state.setServerSocket(ss)) {
|
||||
LOG.info("Closing redundant server socket");
|
||||
tryToClose(ss);
|
||||
return;
|
||||
}
|
||||
socket = ss;
|
||||
backoff.reset();
|
||||
callback.transportEnabled();
|
||||
acceptContactConnections();
|
||||
acceptContactConnections(ss);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -221,47 +221,39 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
if (changed) callback.mergeLocalProperties(p);
|
||||
}
|
||||
|
||||
private void acceptContactConnections() {
|
||||
private void acceptContactConnections(SS ss) {
|
||||
while (true) {
|
||||
DuplexTransportConnection conn;
|
||||
try {
|
||||
conn = acceptConnection(socket);
|
||||
conn = acceptConnection(ss);
|
||||
} catch (IOException e) {
|
||||
// This is expected when the socket is closed
|
||||
if (LOG.isLoggable(INFO)) LOG.info(e.toString());
|
||||
// This is expected when the server socket is closed
|
||||
LOG.info("Server socket closed");
|
||||
state.clearServerSocket();
|
||||
return;
|
||||
}
|
||||
LOG.info("Connection received");
|
||||
if (connectionLimiter.contactConnectionOpened(conn, true)) {
|
||||
backoff.reset();
|
||||
backoff.reset();
|
||||
if (connectionLimiter.contactConnectionOpened(conn))
|
||||
callback.handleConnection(conn);
|
||||
} else {
|
||||
tryToClose(conn);
|
||||
}
|
||||
if (!running) return;
|
||||
}
|
||||
}
|
||||
|
||||
private void tryToClose(DuplexTransportConnection conn) {
|
||||
try {
|
||||
conn.getWriter().dispose(false);
|
||||
conn.getReader().dispose(false, false);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
running = false;
|
||||
tryToClose(socket);
|
||||
callback.transportDisabled();
|
||||
SS ss = state.setStopped();
|
||||
tryToClose(ss);
|
||||
disableAdapterIfEnabledByUs();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRunning() {
|
||||
return running && isAdapterEnabled();
|
||||
public State getState() {
|
||||
return state.getState();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getReasonDisabled() {
|
||||
return state.getReasonDisabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -277,7 +269,7 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
@Override
|
||||
public void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
||||
properties) {
|
||||
if (!isRunning() || !shouldAllowContactConnections()) return;
|
||||
if (getState() != ACTIVE) return;
|
||||
backoff.increment();
|
||||
for (Pair<TransportProperties, ConnectionHandler> p : properties) {
|
||||
connect(p.getFirst(), p.getSecond());
|
||||
@@ -290,10 +282,13 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
String uuid = p.get(PROP_UUID);
|
||||
if (isNullOrEmpty(uuid)) return;
|
||||
ioExecutor.execute(() -> {
|
||||
if (getState() != ACTIVE) return;
|
||||
if (!connectionLimiter.canOpenContactConnection()) return;
|
||||
DuplexTransportConnection d = createConnection(p);
|
||||
if (d != null) {
|
||||
backoff.reset();
|
||||
h.handleConnection(d);
|
||||
if (connectionLimiter.contactConnectionOpened(d))
|
||||
h.handleConnection(d);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -331,7 +326,7 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
|
||||
@Override
|
||||
public DuplexTransportConnection createConnection(TransportProperties p) {
|
||||
if (!isRunning() || !shouldAllowContactConnections()) return null;
|
||||
if (getState() != ACTIVE) return null;
|
||||
if (!connectionLimiter.canOpenContactConnection()) return null;
|
||||
String address = p.get(PROP_ADDRESS);
|
||||
if (isNullOrEmpty(address)) return null;
|
||||
@@ -339,12 +334,8 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
if (isNullOrEmpty(uuid)) return null;
|
||||
DuplexTransportConnection conn = connect(address, uuid);
|
||||
if (conn == null) return null;
|
||||
if (connectionLimiter.contactConnectionOpened(conn, false)) {
|
||||
return conn;
|
||||
} else {
|
||||
tryToClose(conn);
|
||||
return null;
|
||||
}
|
||||
// TODO: Why don't we reset the backoff here?
|
||||
return connectionLimiter.contactConnectionOpened(conn) ? conn : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -354,7 +345,7 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
|
||||
@Override
|
||||
public KeyAgreementListener createKeyAgreementListener(byte[] commitment) {
|
||||
if (!isRunning()) return null;
|
||||
if (getState() != ACTIVE) return null;
|
||||
// No truncation necessary because COMMIT_LENGTH = 16
|
||||
String uuid = UUID.nameUUIDFromBytes(commitment).toString();
|
||||
if (LOG.isLoggable(INFO)) LOG.info("Key agreement UUID " + uuid);
|
||||
@@ -366,7 +357,7 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
logException(LOG, WARNING, e);
|
||||
return null;
|
||||
}
|
||||
if (!isRunning()) {
|
||||
if (getState() != ACTIVE) {
|
||||
tryToClose(ss);
|
||||
return null;
|
||||
}
|
||||
@@ -380,7 +371,7 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
@Override
|
||||
public DuplexTransportConnection createKeyAgreementConnection(
|
||||
byte[] commitment, BdfList descriptor) {
|
||||
if (!isRunning()) return null;
|
||||
if (getState() != ACTIVE) return null;
|
||||
// No truncation necessary because COMMIT_LENGTH = 16
|
||||
String uuid = UUID.nameUUIDFromBytes(commitment).toString();
|
||||
DuplexTransportConnection conn;
|
||||
@@ -440,17 +431,17 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
}
|
||||
}
|
||||
|
||||
@IoExecutor
|
||||
private void onSettingsUpdated(Settings settings) {
|
||||
boolean wasAllowed = shouldAllowContactConnections();
|
||||
loadSettings(settings);
|
||||
boolean isAllowed = shouldAllowContactConnections();
|
||||
if (wasAllowed && !isAllowed) {
|
||||
LOG.info("Contact connections disabled");
|
||||
tryToClose(socket);
|
||||
callback.transportDisabled();
|
||||
boolean enabledByUser = settings.getBoolean(PREF_PLUGIN_ENABLE, false);
|
||||
SS ss = state.setEnabledByUser(enabledByUser);
|
||||
State s = getState();
|
||||
if (ss != null) {
|
||||
LOG.info("Disabled by user, closing server socket");
|
||||
tryToClose(ss);
|
||||
disableAdapterIfEnabledByUs();
|
||||
} else if (!wasAllowed && isAllowed) {
|
||||
LOG.info("Contact connections enabled");
|
||||
} else if (s == INACTIVE) {
|
||||
LOG.info("Enabled by user, opening server socket");
|
||||
if (isAdapterEnabled()) bind();
|
||||
else enableAdapter();
|
||||
}
|
||||
@@ -478,4 +469,77 @@ abstract class BluetoothPlugin<SS> implements DuplexPlugin, EventListener {
|
||||
tryToClose(ss);
|
||||
}
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
@NotNullByDefault
|
||||
protected class PluginState {
|
||||
|
||||
@GuardedBy("this")
|
||||
private boolean started = false,
|
||||
stopped = false,
|
||||
noAdapter = 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;
|
||||
}
|
||||
|
||||
synchronized void setNoAdapter() {
|
||||
noAdapter = true;
|
||||
callback.pluginStateChanged(getState());
|
||||
}
|
||||
|
||||
@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 || !enabledByUser) return DISABLED;
|
||||
return serverSocket == null ? INACTIVE : ACTIVE;
|
||||
}
|
||||
|
||||
synchronized int getReasonDisabled() {
|
||||
if (noAdapter && !stopped) return REASON_NO_BT_ADAPTER;
|
||||
if (!started || stopped) return REASON_STARTING_STOPPING;
|
||||
return enabledByUser ? -1 : REASON_USER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import java.util.logging.Logger;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
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.StringUtils.isNullOrEmpty;
|
||||
|
||||
@@ -45,7 +46,7 @@ abstract class FilePlugin implements SimplexPlugin {
|
||||
|
||||
@Override
|
||||
public TransportConnectionReader createReader(TransportProperties p) {
|
||||
if (!isRunning()) return null;
|
||||
if (getState() != ACTIVE) return null;
|
||||
String path = p.get(PROP_PATH);
|
||||
if (isNullOrEmpty(path)) return null;
|
||||
try {
|
||||
@@ -60,7 +61,7 @@ abstract class FilePlugin implements SimplexPlugin {
|
||||
|
||||
@Override
|
||||
public TransportConnectionWriter createWriter(TransportProperties p) {
|
||||
if (!isRunning()) return null;
|
||||
if (getState() != ACTIVE) return null;
|
||||
String path = p.get(PROP_PATH);
|
||||
if (isNullOrEmpty(path)) return null;
|
||||
try {
|
||||
|
||||
@@ -11,26 +11,22 @@ import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.settings.Settings;
|
||||
import org.briarproject.bramble.util.IoUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.InterfaceAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import static java.lang.Integer.parseInt;
|
||||
import static java.util.Collections.addAll;
|
||||
import static java.util.Collections.emptyList;
|
||||
import static java.util.Collections.sort;
|
||||
import static java.util.logging.Level.INFO;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
@@ -39,8 +35,8 @@ import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.TR
|
||||
import static org.briarproject.bramble.api.plugin.LanTcpConstants.ID;
|
||||
import static org.briarproject.bramble.api.plugin.LanTcpConstants.PREF_LAN_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.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.StringUtils.isNullOrEmpty;
|
||||
import static org.briarproject.bramble.util.StringUtils.join;
|
||||
@@ -50,36 +46,15 @@ class LanTcpPlugin extends TcpPlugin {
|
||||
|
||||
private static final Logger LOG = getLogger(LanTcpPlugin.class.getName());
|
||||
|
||||
private static final LanAddressComparator ADDRESS_COMPARATOR =
|
||||
new LanAddressComparator();
|
||||
|
||||
private static final int MAX_ADDRESSES = 4;
|
||||
private static final String SEPARATOR = ",";
|
||||
|
||||
/**
|
||||
* The IP address of an Android device providing a wifi access point.
|
||||
*/
|
||||
protected static final InetAddress WIFI_AP_ADDRESS;
|
||||
|
||||
/**
|
||||
* The IP address of an Android device providing a wifi direct
|
||||
* legacy mode access point.
|
||||
*/
|
||||
protected static final InetAddress WIFI_DIRECT_AP_ADDRESS;
|
||||
|
||||
static {
|
||||
try {
|
||||
WIFI_AP_ADDRESS = InetAddress.getByAddress(
|
||||
new byte[] {(byte) 192, (byte) 168, 43, 1});
|
||||
WIFI_DIRECT_AP_ADDRESS = InetAddress.getByAddress(
|
||||
new byte[] {(byte) 192, (byte) 168, 49, 1});
|
||||
} catch (UnknownHostException e) {
|
||||
// Should only be thrown if the address has an illegal length
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
LanTcpPlugin(Executor ioExecutor, Backoff backoff, PluginCallback callback,
|
||||
int maxLatency, int maxIdleTime, int connectionTimeout) {
|
||||
super(ioExecutor, backoff, callback, maxLatency, maxIdleTime,
|
||||
connectionTimeout);
|
||||
int maxLatency, int maxIdleTime) {
|
||||
super(ioExecutor, backoff, callback, maxLatency, maxIdleTime);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -87,82 +62,38 @@ class LanTcpPlugin extends TcpPlugin {
|
||||
return ID;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
if (used.getAndSet(true)) throw new IllegalStateException();
|
||||
initialisePortProperty();
|
||||
running = true;
|
||||
bind();
|
||||
}
|
||||
|
||||
protected void initialisePortProperty() {
|
||||
TransportProperties p = callback.getLocalProperties();
|
||||
if (isNullOrEmpty(p.get(PROP_PORT))) {
|
||||
int port = new Random().nextInt(32768) + 32768;
|
||||
p.put(PROP_PORT, String.valueOf(port));
|
||||
callback.mergeLocalProperties(p);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<InetSocketAddress> getLocalSocketAddresses() {
|
||||
// Use the same address and port as last time if available
|
||||
TransportProperties p = callback.getLocalProperties();
|
||||
int preferredPort = parsePortProperty(p.get(PROP_PORT));
|
||||
String oldIpPorts = p.get(PROP_IP_PORTS);
|
||||
List<InetSocketAddress> olds = parseSocketAddresses(oldIpPorts);
|
||||
|
||||
List<InetSocketAddress> locals = new ArrayList<>();
|
||||
List<InetSocketAddress> fallbacks = new ArrayList<>();
|
||||
for (InetAddress local : getUsableLocalInetAddresses()) {
|
||||
// If we've used this address before, try to use the same port
|
||||
int port = preferredPort;
|
||||
for (InetSocketAddress old : olds) {
|
||||
if (old.getAddress().equals(local)) {
|
||||
port = old.getPort();
|
||||
break;
|
||||
for (InetAddress local : getLocalIpAddresses()) {
|
||||
if (isAcceptableAddress(local)) {
|
||||
// If this is the old address, try to use the same port
|
||||
for (InetSocketAddress old : olds) {
|
||||
if (old.getAddress().equals(local))
|
||||
locals.add(new InetSocketAddress(local, old.getPort()));
|
||||
}
|
||||
locals.add(new InetSocketAddress(local, 0));
|
||||
}
|
||||
locals.add(new InetSocketAddress(local, port));
|
||||
// Fall back to any available port
|
||||
fallbacks.add(new InetSocketAddress(local, 0));
|
||||
}
|
||||
locals.addAll(fallbacks);
|
||||
sort(locals, ADDRESS_COMPARATOR);
|
||||
return locals;
|
||||
}
|
||||
|
||||
private int parsePortProperty(@Nullable String portProperty) {
|
||||
if (isNullOrEmpty(portProperty)) return 0;
|
||||
try {
|
||||
return parseInt(portProperty);
|
||||
} catch (NumberFormatException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private List<InetSocketAddress> parseSocketAddresses(String ipPorts) {
|
||||
if (isNullOrEmpty(ipPorts)) return emptyList();
|
||||
String[] split = ipPorts.split(SEPARATOR);
|
||||
List<InetSocketAddress> addresses = new ArrayList<>();
|
||||
if (isNullOrEmpty(ipPorts)) return addresses;
|
||||
for (String ipPort : ipPorts.split(SEPARATOR)) {
|
||||
for (String ipPort : split) {
|
||||
InetSocketAddress a = parseSocketAddress(ipPort);
|
||||
if (a != null) addresses.add(a);
|
||||
}
|
||||
return addresses;
|
||||
}
|
||||
|
||||
protected List<InetAddress> getUsableLocalInetAddresses() {
|
||||
List<InterfaceAddress> ifAddrs =
|
||||
new ArrayList<>(getLocalInterfaceAddresses());
|
||||
// Prefer longer network prefixes
|
||||
sort(ifAddrs, (a, b) ->
|
||||
b.getNetworkPrefixLength() - a.getNetworkPrefixLength());
|
||||
List<InetAddress> addrs = new ArrayList<>();
|
||||
for (InterfaceAddress ifAddr : ifAddrs) {
|
||||
InetAddress addr = ifAddr.getAddress();
|
||||
if (isAcceptableAddress(addr)) addrs.add(addr);
|
||||
}
|
||||
return addrs;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setLocalSocketAddress(InetSocketAddress a) {
|
||||
String ipPort = getIpPortString(a);
|
||||
@@ -200,20 +131,7 @@ class LanTcpPlugin extends TcpPlugin {
|
||||
@Override
|
||||
protected List<InetSocketAddress> getRemoteSocketAddresses(
|
||||
TransportProperties p) {
|
||||
String ipPorts = p.get(PROP_IP_PORTS);
|
||||
List<InetSocketAddress> remotes = parseSocketAddresses(ipPorts);
|
||||
int port = parsePortProperty(p.get(PROP_PORT));
|
||||
// If the contact has a preferred port, we can guess their IP:port when
|
||||
// they're providing a wifi access point
|
||||
if (port != 0) {
|
||||
InetSocketAddress wifiAp =
|
||||
new InetSocketAddress(WIFI_AP_ADDRESS, port);
|
||||
if (!remotes.contains(wifiAp)) remotes.add(wifiAp);
|
||||
InetSocketAddress wifiDirectAp =
|
||||
new InetSocketAddress(WIFI_DIRECT_AP_ADDRESS, port);
|
||||
if (!remotes.contains(wifiDirectAp)) remotes.add(wifiDirectAp);
|
||||
}
|
||||
return remotes;
|
||||
return parseSocketAddresses(p.get(PROP_IP_PORTS));
|
||||
}
|
||||
|
||||
private boolean isAcceptableAddress(InetAddress a) {
|
||||
@@ -226,33 +144,53 @@ class LanTcpPlugin extends TcpPlugin {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isConnectable(InterfaceAddress local,
|
||||
InetSocketAddress remote) {
|
||||
protected boolean isConnectable(InetSocketAddress remote) {
|
||||
if (remote.getPort() == 0) return false;
|
||||
if (!isAcceptableAddress(remote.getAddress())) return false;
|
||||
// Try to determine whether the address is on the same LAN as us
|
||||
byte[] localIp = local.getAddress().getAddress();
|
||||
ServerSocket ss = state.getServerSocket();
|
||||
if (ss == null) return false;
|
||||
byte[] localIp = ss.getInetAddress().getAddress();
|
||||
byte[] remoteIp = remote.getAddress().getAddress();
|
||||
int prefixLength = local.getNetworkPrefixLength();
|
||||
return areAddressesInSameNetwork(localIp, remoteIp, prefixLength);
|
||||
return addressesAreOnSameLan(localIp, remoteIp);
|
||||
}
|
||||
|
||||
// Package access for testing
|
||||
static boolean areAddressesInSameNetwork(byte[] localIp, byte[] remoteIp,
|
||||
int prefixLength) {
|
||||
if (localIp.length != remoteIp.length) return false;
|
||||
// Compare the first prefixLength bits of the addresses
|
||||
for (int i = 0; i < prefixLength; i++) {
|
||||
int byteIndex = i >> 3;
|
||||
int bitIndex = i & 7; // 0 to 7
|
||||
int mask = 128 >> bitIndex; // Select the bit at bitIndex
|
||||
if ((localIp[byteIndex] & mask) != (remoteIp[byteIndex] & mask)) {
|
||||
return false; // Addresses differ at bit i
|
||||
}
|
||||
}
|
||||
boolean addressesAreOnSameLan(byte[] localIp, byte[] remoteIp) {
|
||||
// 10.0.0.0/8
|
||||
if (isPrefix10(localIp)) return isPrefix10(remoteIp);
|
||||
// 172.16.0.0/12
|
||||
if (isPrefix172(localIp)) return isPrefix172(remoteIp);
|
||||
// 192.168.0.0/16
|
||||
if (isPrefix192(localIp)) return isPrefix192(remoteIp);
|
||||
// Unrecognised prefix - may be compatible
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean isPrefix10(byte[] ipv4) {
|
||||
return ipv4[0] == 10;
|
||||
}
|
||||
|
||||
private static boolean isPrefix172(byte[] ipv4) {
|
||||
return ipv4[0] == (byte) 172 && (ipv4[1] & 0xF0) == 16;
|
||||
}
|
||||
|
||||
private static boolean isPrefix192(byte[] ipv4) {
|
||||
return ipv4[0] == (byte) 192 && ipv4[1] == (byte) 168;
|
||||
}
|
||||
|
||||
// Returns the prefix length for an RFC 1918 address, or 0 for any other
|
||||
// address
|
||||
private static int getRfc1918PrefixLength(InetAddress addr) {
|
||||
if (!(addr instanceof Inet4Address)) return 0;
|
||||
if (!addr.isSiteLocalAddress()) return 0;
|
||||
byte[] ipv4 = addr.getAddress();
|
||||
if (isPrefix10(ipv4)) return 8;
|
||||
if (isPrefix172(ipv4)) return 12;
|
||||
if (isPrefix192(ipv4)) return 16;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsKeyAgreement() {
|
||||
return true;
|
||||
@@ -271,10 +209,10 @@ class LanTcpPlugin extends TcpPlugin {
|
||||
} catch (IOException e) {
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Failed to bind " + scrubSocketAddress(addr));
|
||||
tryToClose(ss);
|
||||
tryToClose(ss, LOG, WARNING);
|
||||
}
|
||||
}
|
||||
if (ss == null || !ss.isBound()) {
|
||||
if (ss == null) {
|
||||
LOG.info("Could not bind server socket for key agreement");
|
||||
return null;
|
||||
}
|
||||
@@ -290,13 +228,8 @@ class LanTcpPlugin extends TcpPlugin {
|
||||
@Override
|
||||
public DuplexTransportConnection createKeyAgreementConnection(
|
||||
byte[] commitment, BdfList descriptor) {
|
||||
if (!isRunning()) return null;
|
||||
ServerSocket ss = socket;
|
||||
InterfaceAddress local = getLocalInterfaceAddress(ss.getInetAddress());
|
||||
if (local == null) {
|
||||
LOG.warning("No interface for key agreement server socket");
|
||||
return null;
|
||||
}
|
||||
ServerSocket ss = state.getServerSocket();
|
||||
if (ss == null) return null;
|
||||
InetSocketAddress remote;
|
||||
try {
|
||||
remote = parseSocketAddress(descriptor);
|
||||
@@ -304,7 +237,7 @@ class LanTcpPlugin extends TcpPlugin {
|
||||
LOG.info("Invalid IP/port in key agreement descriptor");
|
||||
return null;
|
||||
}
|
||||
if (!isConnectable(local, remote)) {
|
||||
if (!isConnectable(remote)) {
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info(scrubSocketAddress(remote) +
|
||||
" is not connectable from " +
|
||||
@@ -317,7 +250,7 @@ class LanTcpPlugin extends TcpPlugin {
|
||||
LOG.info("Connecting to " + scrubSocketAddress(remote));
|
||||
Socket s = createSocket();
|
||||
s.bind(new InetSocketAddress(ss.getInetAddress(), 0));
|
||||
s.connect(remote, connectionTimeout);
|
||||
s.connect(remote);
|
||||
s.setSoTimeout(socketTimeout);
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Connected to " + scrubSocketAddress(remote));
|
||||
@@ -363,7 +296,22 @@ class LanTcpPlugin extends TcpPlugin {
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
IoUtils.tryToClose(ss, LOG, WARNING);
|
||||
tryToClose(ss, LOG, WARNING);
|
||||
}
|
||||
}
|
||||
|
||||
static class LanAddressComparator implements Comparator<InetSocketAddress> {
|
||||
|
||||
@Override
|
||||
public int compare(InetSocketAddress a, InetSocketAddress b) {
|
||||
// Prefer addresses with non-zero ports
|
||||
int aPort = a.getPort(), bPort = b.getPort();
|
||||
if (aPort > 0 && bPort == 0) return -1;
|
||||
if (aPort == 0 && bPort > 0) return 1;
|
||||
// Prefer addresses with longer RFC 1918 prefixes
|
||||
int aPrefix = getRfc1918PrefixLength(a.getAddress());
|
||||
int bPrefix = getRfc1918PrefixLength(b.getAddress());
|
||||
return bPrefix - aPrefix;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.briarproject.bramble.plugin.tcp;
|
||||
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Backoff;
|
||||
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
||||
@@ -18,19 +19,20 @@ import static org.briarproject.bramble.api.plugin.LanTcpConstants.ID;
|
||||
@NotNullByDefault
|
||||
public class LanTcpPluginFactory implements DuplexPluginFactory {
|
||||
|
||||
private static final int MAX_LATENCY = 30_000; // 30 seconds
|
||||
private static final int MAX_IDLE_TIME = 30_000; // 30 seconds
|
||||
private static final int CONNECTION_TIMEOUT = 3_000; // 3 seconds
|
||||
private static final int MIN_POLLING_INTERVAL = 60_000; // 1 minute
|
||||
private static final int MAX_POLLING_INTERVAL = 600_000; // 10 mins
|
||||
private static final int MAX_LATENCY = 30 * 1000; // 30 seconds
|
||||
private static final int MAX_IDLE_TIME = 30 * 1000; // 30 seconds
|
||||
private static final int MIN_POLLING_INTERVAL = 60 * 1000; // 1 minute
|
||||
private static final int MAX_POLLING_INTERVAL = 10 * 60 * 1000; // 10 mins
|
||||
private static final double BACKOFF_BASE = 1.2;
|
||||
|
||||
private final Executor ioExecutor;
|
||||
private final EventBus eventBus;
|
||||
private final BackoffFactory backoffFactory;
|
||||
|
||||
public LanTcpPluginFactory(Executor ioExecutor,
|
||||
public LanTcpPluginFactory(Executor ioExecutor, EventBus eventBus,
|
||||
BackoffFactory backoffFactory) {
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.eventBus = eventBus;
|
||||
this.backoffFactory = backoffFactory;
|
||||
}
|
||||
|
||||
@@ -48,7 +50,9 @@ public class LanTcpPluginFactory implements DuplexPluginFactory {
|
||||
public DuplexPlugin createPlugin(PluginCallback callback) {
|
||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||
return new LanTcpPlugin(ioExecutor, backoff, callback, MAX_LATENCY,
|
||||
MAX_IDLE_TIME, CONNECTION_TIMEOUT);
|
||||
LanTcpPlugin plugin = new LanTcpPlugin(ioExecutor, backoff, callback,
|
||||
MAX_LATENCY, MAX_IDLE_TIME);
|
||||
eventBus.addListener(plugin);
|
||||
return plugin;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,12 @@ package org.briarproject.bramble.plugin.tcp;
|
||||
import org.briarproject.bramble.PoliteExecutor;
|
||||
import org.briarproject.bramble.api.Pair;
|
||||
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.lifecycle.IoExecutor;
|
||||
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.plugin.Backoff;
|
||||
import org.briarproject.bramble.api.plugin.ConnectionHandler;
|
||||
@@ -14,12 +18,12 @@ import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
||||
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.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.InterfaceAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
@@ -35,19 +39,26 @@ import java.util.logging.Logger;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
|
||||
import static java.net.NetworkInterface.getNetworkInterfaces;
|
||||
import static java.util.Collections.emptyList;
|
||||
import static java.util.Collections.list;
|
||||
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.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.util.IoUtils.tryToClose;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
import static org.briarproject.bramble.util.PrivacyUtils.scrubSocketAddress;
|
||||
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
abstract class TcpPlugin implements DuplexPlugin {
|
||||
abstract class TcpPlugin implements DuplexPlugin, EventListener {
|
||||
|
||||
private static final Logger LOG = getLogger(TcpPlugin.class.getName());
|
||||
|
||||
@@ -57,12 +68,9 @@ abstract class TcpPlugin implements DuplexPlugin {
|
||||
protected final Executor ioExecutor, bindExecutor;
|
||||
protected final Backoff backoff;
|
||||
protected final PluginCallback callback;
|
||||
protected final int maxLatency, maxIdleTime;
|
||||
protected final int connectionTimeout, socketTimeout;
|
||||
protected final int maxLatency, maxIdleTime, socketTimeout;
|
||||
protected final AtomicBoolean used = new AtomicBoolean(false);
|
||||
|
||||
protected volatile boolean running = false;
|
||||
protected volatile ServerSocket socket = null;
|
||||
protected final PluginState state = new PluginState();
|
||||
|
||||
/**
|
||||
* Returns zero or more socket addresses on which the plugin should listen,
|
||||
@@ -87,17 +95,15 @@ abstract class TcpPlugin implements DuplexPlugin {
|
||||
* Returns true if connections to the given address can be attempted.
|
||||
*/
|
||||
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
|
||||
protected abstract boolean isConnectable(InterfaceAddress local,
|
||||
InetSocketAddress remote);
|
||||
protected abstract boolean isConnectable(InetSocketAddress remote);
|
||||
|
||||
TcpPlugin(Executor ioExecutor, Backoff backoff, PluginCallback callback,
|
||||
int maxLatency, int maxIdleTime, int connectionTimeout) {
|
||||
int maxLatency, int maxIdleTime) {
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.backoff = backoff;
|
||||
this.callback = callback;
|
||||
this.maxLatency = maxLatency;
|
||||
this.maxIdleTime = maxIdleTime;
|
||||
this.connectionTimeout = connectionTimeout;
|
||||
if (maxIdleTime > Integer.MAX_VALUE / 2)
|
||||
socketTimeout = Integer.MAX_VALUE;
|
||||
else socketTimeout = maxIdleTime * 2;
|
||||
@@ -118,14 +124,14 @@ abstract class TcpPlugin implements DuplexPlugin {
|
||||
@Override
|
||||
public void start() {
|
||||
if (used.getAndSet(true)) throw new IllegalStateException();
|
||||
running = true;
|
||||
Settings settings = callback.getSettings();
|
||||
state.setStarted(settings.getBoolean(PREF_PLUGIN_ENABLE, false));
|
||||
bind();
|
||||
}
|
||||
|
||||
protected void bind() {
|
||||
bindExecutor.execute(() -> {
|
||||
if (!running) return;
|
||||
if (socket != null && !socket.isClosed()) return;
|
||||
if (getState() != INACTIVE) return;
|
||||
ServerSocket ss = null;
|
||||
for (InetSocketAddress addr : getLocalSocketAddresses()) {
|
||||
try {
|
||||
@@ -135,34 +141,28 @@ abstract class TcpPlugin implements DuplexPlugin {
|
||||
} catch (IOException e) {
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Failed to bind " + scrubSocketAddress(addr));
|
||||
tryToClose(ss);
|
||||
tryToClose(ss, LOG, WARNING);
|
||||
}
|
||||
}
|
||||
if (ss == null || !ss.isBound()) {
|
||||
if (ss == null) {
|
||||
LOG.info("Could not bind server socket");
|
||||
return;
|
||||
}
|
||||
if (!running) {
|
||||
tryToClose(ss);
|
||||
if (!state.setServerSocket(ss)) {
|
||||
LOG.info("Closing redundant server socket");
|
||||
tryToClose(ss, LOG, WARNING);
|
||||
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();
|
||||
acceptContactConnections(ss);
|
||||
});
|
||||
}
|
||||
|
||||
protected void tryToClose(@Nullable ServerSocket ss) {
|
||||
IoUtils.tryToClose(ss, LOG, WARNING);
|
||||
callback.transportDisabled();
|
||||
}
|
||||
|
||||
String getIpPortString(InetSocketAddress a) {
|
||||
String addr = a.getAddress().getHostAddress();
|
||||
int percent = addr.indexOf('%');
|
||||
@@ -170,15 +170,16 @@ abstract class TcpPlugin implements DuplexPlugin {
|
||||
return addr + ":" + a.getPort();
|
||||
}
|
||||
|
||||
private void acceptContactConnections() {
|
||||
while (isRunning()) {
|
||||
private void acceptContactConnections(ServerSocket ss) {
|
||||
while (true) {
|
||||
Socket s;
|
||||
try {
|
||||
s = socket.accept();
|
||||
s = ss.accept();
|
||||
s.setSoTimeout(socketTimeout);
|
||||
} catch (IOException e) {
|
||||
// This is expected when the socket is closed
|
||||
if (LOG.isLoggable(INFO)) LOG.info(e.toString());
|
||||
// This is expected when the server socket is closed
|
||||
LOG.info("Server socket closed");
|
||||
state.clearServerSocket(ss);
|
||||
return;
|
||||
}
|
||||
if (LOG.isLoggable(INFO))
|
||||
@@ -191,13 +192,18 @@ abstract class TcpPlugin implements DuplexPlugin {
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
running = false;
|
||||
tryToClose(socket);
|
||||
ServerSocket ss = state.setStopped();
|
||||
tryToClose(ss, LOG, WARNING);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRunning() {
|
||||
return running && socket != null && !socket.isClosed();
|
||||
public State getState() {
|
||||
return state.getState();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getReasonDisabled() {
|
||||
return state.getReasonDisabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -213,7 +219,7 @@ abstract class TcpPlugin implements DuplexPlugin {
|
||||
@Override
|
||||
public void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
||||
properties) {
|
||||
if (!isRunning()) return;
|
||||
if (getState() != ACTIVE) return;
|
||||
backoff.increment();
|
||||
for (Pair<TransportProperties, ConnectionHandler> p : properties) {
|
||||
connect(p.getFirst(), p.getSecond());
|
||||
@@ -232,20 +238,10 @@ abstract class TcpPlugin implements DuplexPlugin {
|
||||
|
||||
@Override
|
||||
public DuplexTransportConnection createConnection(TransportProperties p) {
|
||||
if (!isRunning()) return null;
|
||||
ServerSocket ss = socket;
|
||||
InterfaceAddress local = getLocalInterfaceAddress(ss.getInetAddress());
|
||||
if (local == null) {
|
||||
LOG.warning("No interface for server socket");
|
||||
return null;
|
||||
}
|
||||
ServerSocket ss = state.getServerSocket();
|
||||
if (ss == null) return null;
|
||||
for (InetSocketAddress remote : getRemoteSocketAddresses(p)) {
|
||||
// Don't try to connect to our own address
|
||||
if (!canConnectToOwnAddress() &&
|
||||
remote.getAddress().equals(ss.getInetAddress())) {
|
||||
continue;
|
||||
}
|
||||
if (!isConnectable(local, remote)) {
|
||||
if (!isConnectable(remote)) {
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info(scrubSocketAddress(remote) +
|
||||
" is not connectable from " +
|
||||
@@ -258,7 +254,7 @@ abstract class TcpPlugin implements DuplexPlugin {
|
||||
LOG.info("Connecting to " + scrubSocketAddress(remote));
|
||||
Socket s = createSocket();
|
||||
s.bind(new InetSocketAddress(ss.getInetAddress(), 0));
|
||||
s.connect(remote, connectionTimeout);
|
||||
s.connect(remote);
|
||||
s.setSoTimeout(socketTimeout);
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Connected to " + scrubSocketAddress(remote));
|
||||
@@ -272,19 +268,6 @@ abstract class TcpPlugin implements DuplexPlugin {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
InterfaceAddress getLocalInterfaceAddress(InetAddress a) {
|
||||
for (InterfaceAddress ifAddr : getLocalInterfaceAddresses()) {
|
||||
if (ifAddr.getAddress().equals(a)) return ifAddr;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Override for testing
|
||||
protected boolean canConnectToOwnAddress() {
|
||||
return false;
|
||||
}
|
||||
|
||||
protected Socket createSocket() throws IOException {
|
||||
return new Socket();
|
||||
}
|
||||
@@ -340,30 +323,106 @@ abstract class TcpPlugin implements DuplexPlugin {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
List<InterfaceAddress> getLocalInterfaceAddresses() {
|
||||
List<InterfaceAddress> addrs = new ArrayList<>();
|
||||
for (NetworkInterface iface : getNetworkInterfaces()) {
|
||||
addrs.addAll(iface.getInterfaceAddresses());
|
||||
}
|
||||
return addrs;
|
||||
}
|
||||
|
||||
List<InetAddress> getLocalInetAddresses() {
|
||||
List<InetAddress> addrs = new ArrayList<>();
|
||||
for (NetworkInterface iface : getNetworkInterfaces()) {
|
||||
addrs.addAll(list(iface.getInetAddresses()));
|
||||
}
|
||||
return addrs;
|
||||
}
|
||||
|
||||
private List<NetworkInterface> getNetworkInterfaces() {
|
||||
Collection<InetAddress> getLocalIpAddresses() {
|
||||
try {
|
||||
Enumeration<NetworkInterface> ifaces =
|
||||
NetworkInterface.getNetworkInterfaces();
|
||||
return ifaces == null ? emptyList() : list(ifaces);
|
||||
Enumeration<NetworkInterface> ifaces = getNetworkInterfaces();
|
||||
if (ifaces == null) return emptyList();
|
||||
List<InetAddress> addrs = new ArrayList<>();
|
||||
for (NetworkInterface iface : list(ifaces))
|
||||
addrs.addAll(list(iface.getInetAddresses()));
|
||||
return addrs;
|
||||
} catch (SocketException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
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, false);
|
||||
ServerSocket ss = state.setEnabledByUser(enabledByUser);
|
||||
State s = getState();
|
||||
if (ss != null) {
|
||||
LOG.info("Disabled by user, closing server socket");
|
||||
tryToClose(ss, LOG, WARNING);
|
||||
} else if (s == INACTIVE) {
|
||||
LOG.info("Enabled by user, opening server socket");
|
||||
bind();
|
||||
}
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
@NotNullByDefault
|
||||
protected class PluginState {
|
||||
|
||||
@GuardedBy("this")
|
||||
private boolean started = false, stopped = false, enabledByUser = false;
|
||||
|
||||
@GuardedBy("this")
|
||||
@Nullable
|
||||
private ServerSocket serverSocket = null;
|
||||
|
||||
synchronized void setStarted(boolean enabledByUser) {
|
||||
started = true;
|
||||
this.enabledByUser = enabledByUser;
|
||||
callback.pluginStateChanged(getState());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
synchronized ServerSocket setStopped() {
|
||||
stopped = true;
|
||||
ServerSocket ss = serverSocket;
|
||||
serverSocket = null;
|
||||
callback.pluginStateChanged(getState());
|
||||
return ss;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
synchronized ServerSocket setEnabledByUser(boolean enabledByUser) {
|
||||
this.enabledByUser = enabledByUser;
|
||||
ServerSocket ss = null;
|
||||
if (!enabledByUser) {
|
||||
ss = serverSocket;
|
||||
serverSocket = null;
|
||||
}
|
||||
callback.pluginStateChanged(getState());
|
||||
return ss;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
synchronized ServerSocket getServerSocket() {
|
||||
return serverSocket;
|
||||
}
|
||||
|
||||
synchronized boolean setServerSocket(ServerSocket ss) {
|
||||
if (stopped || serverSocket != null) return false;
|
||||
serverSocket = ss;
|
||||
callback.pluginStateChanged(getState());
|
||||
return true;
|
||||
}
|
||||
|
||||
synchronized void clearServerSocket(ServerSocket ss) {
|
||||
if (serverSocket == ss) serverSocket = null;
|
||||
callback.pluginStateChanged(getState());
|
||||
}
|
||||
|
||||
synchronized State getState() {
|
||||
if (!started || stopped || !enabledByUser) return DISABLED;
|
||||
return serverSocket == null ? INACTIVE : ACTIVE;
|
||||
}
|
||||
|
||||
synchronized int getReasonDisabled() {
|
||||
if (!started || stopped) return REASON_STARTING_STOPPING;
|
||||
return enabledByUser ? -1 : REASON_USER;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.InterfaceAddress;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
@@ -30,10 +29,8 @@ class WanTcpPlugin extends TcpPlugin {
|
||||
private volatile MappingResult mappingResult;
|
||||
|
||||
WanTcpPlugin(Executor ioExecutor, Backoff backoff, PortMapper portMapper,
|
||||
PluginCallback callback, int maxLatency, int maxIdleTime,
|
||||
int connectionTimeout) {
|
||||
super(ioExecutor, backoff, callback, maxLatency, maxIdleTime,
|
||||
connectionTimeout);
|
||||
PluginCallback callback, int maxLatency, int maxIdleTime) {
|
||||
super(ioExecutor, backoff, callback, maxLatency, maxIdleTime);
|
||||
this.portMapper = portMapper;
|
||||
}
|
||||
|
||||
@@ -48,7 +45,7 @@ class WanTcpPlugin extends TcpPlugin {
|
||||
TransportProperties p = callback.getLocalProperties();
|
||||
InetSocketAddress old = parseSocketAddress(p.get(PROP_IP_PORT));
|
||||
List<InetSocketAddress> addrs = new LinkedList<>();
|
||||
for (InetAddress a : getLocalInetAddresses()) {
|
||||
for (InetAddress a : getLocalIpAddresses()) {
|
||||
if (isAcceptableAddress(a)) {
|
||||
// If this is the old address, try to use the same port
|
||||
if (old != null && old.getAddress().equals(a))
|
||||
@@ -89,8 +86,7 @@ class WanTcpPlugin extends TcpPlugin {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isConnectable(InterfaceAddress local,
|
||||
InetSocketAddress remote) {
|
||||
protected boolean isConnectable(InetSocketAddress remote) {
|
||||
if (remote.getPort() == 0) return false;
|
||||
return isAcceptableAddress(remote.getAddress());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.briarproject.bramble.plugin.tcp;
|
||||
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.lifecycle.ShutdownManager;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Backoff;
|
||||
@@ -19,20 +20,21 @@ import static org.briarproject.bramble.api.plugin.WanTcpConstants.ID;
|
||||
@NotNullByDefault
|
||||
public class WanTcpPluginFactory implements DuplexPluginFactory {
|
||||
|
||||
private static final int MAX_LATENCY = 30_000; // 30 seconds
|
||||
private static final int MAX_IDLE_TIME = 30_000; // 30 seconds
|
||||
private static final int CONNECTION_TIMEOUT = 30_000; // 30 seconds
|
||||
private static final int MIN_POLLING_INTERVAL = 60_000; // 1 minute
|
||||
private static final int MAX_POLLING_INTERVAL = 600_000; // 10 mins
|
||||
private static final int MAX_LATENCY = 30 * 1000; // 30 seconds
|
||||
private static final int MAX_IDLE_TIME = 30 * 1000; // 30 seconds
|
||||
private static final int MIN_POLLING_INTERVAL = 60 * 1000; // 1 minute
|
||||
private static final int MAX_POLLING_INTERVAL = 10 * 60 * 1000; // 10 mins
|
||||
private static final double BACKOFF_BASE = 1.2;
|
||||
|
||||
private final Executor ioExecutor;
|
||||
private final EventBus eventBus;
|
||||
private final BackoffFactory backoffFactory;
|
||||
private final ShutdownManager shutdownManager;
|
||||
|
||||
public WanTcpPluginFactory(Executor ioExecutor,
|
||||
public WanTcpPluginFactory(Executor ioExecutor, EventBus eventBus,
|
||||
BackoffFactory backoffFactory, ShutdownManager shutdownManager) {
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.eventBus = eventBus;
|
||||
this.backoffFactory = backoffFactory;
|
||||
this.shutdownManager = shutdownManager;
|
||||
}
|
||||
@@ -51,8 +53,10 @@ public class WanTcpPluginFactory implements DuplexPluginFactory {
|
||||
public DuplexPlugin createPlugin(PluginCallback callback) {
|
||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||
return new WanTcpPlugin(ioExecutor, backoff,
|
||||
WanTcpPlugin plugin = new WanTcpPlugin(ioExecutor, backoff,
|
||||
new PortMapperImpl(shutdownManager), callback, MAX_LATENCY,
|
||||
MAX_IDLE_TIME, CONNECTION_TIMEOUT);
|
||||
MAX_IDLE_TIME);
|
||||
eventBus.addListener(plugin);
|
||||
return plugin;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import org.briarproject.bramble.api.network.NetworkManager;
|
||||
import org.briarproject.bramble.api.network.NetworkStatus;
|
||||
import org.briarproject.bramble.api.network.event.NetworkStatusEvent;
|
||||
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.plugin.Backoff;
|
||||
import org.briarproject.bramble.api.plugin.ConnectionHandler;
|
||||
@@ -54,6 +55,9 @@ import java.util.logging.Logger;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
import javax.net.SocketFactory;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
@@ -65,6 +69,10 @@ import static java.util.logging.Logger.getLogger;
|
||||
import static net.freehaven.tor.control.TorControlCommands.HS_ADDRESS;
|
||||
import static net.freehaven.tor.control.TorControlCommands.HS_PRIVKEY;
|
||||
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.TorConstants.CONTROL_PORT;
|
||||
import static org.briarproject.bramble.api.plugin.TorConstants.ID;
|
||||
import static org.briarproject.bramble.api.plugin.TorConstants.PREF_TOR_MOBILE;
|
||||
@@ -76,6 +84,9 @@ 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.PROP_ONION_V2;
|
||||
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.plugin.tor.TorRendezvousCrypto.SEED_BYTES;
|
||||
import static org.briarproject.bramble.util.IoUtils.copyAndClose;
|
||||
import static org.briarproject.bramble.util.IoUtils.tryToClose;
|
||||
@@ -113,16 +124,14 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
private final int maxLatency, maxIdleTime, socketTimeout;
|
||||
private final File torDirectory, torFile, geoIpFile, obfs4File, configFile;
|
||||
private final File doneFile, cookieFile;
|
||||
private final ConnectionStatus connectionStatus;
|
||||
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 TorControlConnection controlConnection = null;
|
||||
private volatile Settings settings = null;
|
||||
|
||||
protected volatile boolean running = false;
|
||||
|
||||
protected abstract int getProcessId();
|
||||
|
||||
protected abstract long getLastUpdateTime();
|
||||
@@ -159,7 +168,6 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
configFile = new File(torDirectory, "torrc");
|
||||
doneFile = new File(torDirectory, "done");
|
||||
cookieFile = new File(torDirectory, ".tor/control_auth_cookie");
|
||||
connectionStatus = new ConnectionStatus();
|
||||
// Don't execute more than one connection status check at a time
|
||||
connectionStatusExecutor =
|
||||
new PoliteExecutor("TorPlugin", ioExecutor, 1);
|
||||
@@ -183,6 +191,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
@Override
|
||||
public void start() throws PluginException {
|
||||
if (used.getAndSet(true)) throw new IllegalStateException();
|
||||
state.setStarted();
|
||||
if (!torDirectory.exists()) {
|
||||
if (!torDirectory.mkdirs()) {
|
||||
LOG.warning("Could not create Tor directory.");
|
||||
@@ -190,7 +199,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
}
|
||||
// Load the settings
|
||||
settings = callback.getSettings();
|
||||
settings = migrateSettings(callback.getSettings());
|
||||
// Install or update the assets if necessary
|
||||
if (!assetsAreUpToDate()) installAssets();
|
||||
if (cookieFile.exists() && !cookieFile.delete())
|
||||
@@ -258,7 +267,6 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
// Tell Tor to exit when the control connection is closed
|
||||
controlConnection.takeOwnership();
|
||||
controlConnection.resetConf(singletonList(OWNER));
|
||||
running = true;
|
||||
// Register to receive events from the Tor process
|
||||
controlConnection.setEventHandler(this);
|
||||
controlConnection.setEvents(asList(EVENTS));
|
||||
@@ -266,11 +274,12 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
String phase = controlConnection.getInfo("status/bootstrap-phase");
|
||||
if (phase != null && phase.contains("PROGRESS=100")) {
|
||||
LOG.info("Tor has already bootstrapped");
|
||||
connectionStatus.setBootstrapped();
|
||||
state.setBootstrapped();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new PluginException(e);
|
||||
}
|
||||
state.setTorStarted();
|
||||
// Check whether we're online
|
||||
updateConnectionStatus(networkManager.getNetworkStatus(),
|
||||
batteryManager.isCharging());
|
||||
@@ -278,6 +287,18 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
bind();
|
||||
}
|
||||
|
||||
// TODO: Remove after a reasonable migration period (added 2020-01-16)
|
||||
private Settings migrateSettings(Settings settings) {
|
||||
int network = settings.getInt(PREF_TOR_NETWORK,
|
||||
PREF_TOR_NETWORK_AUTOMATIC);
|
||||
if (network == PREF_TOR_NETWORK_NEVER) {
|
||||
settings.putInt(PREF_TOR_NETWORK, PREF_TOR_NETWORK_AUTOMATIC);
|
||||
settings.putBoolean(PREF_PLUGIN_ENABLE, false);
|
||||
callback.mergeSettings(settings);
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
private boolean assetsAreUpToDate() {
|
||||
return doneFile.lastModified() > getLastUpdateTime();
|
||||
}
|
||||
@@ -393,11 +414,11 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
tryToClose(ss, LOG, WARNING);
|
||||
return;
|
||||
}
|
||||
if (!running) {
|
||||
if (!state.setServerSocket(ss)) {
|
||||
LOG.info("Closing redundant server socket");
|
||||
tryToClose(ss, LOG, WARNING);
|
||||
return;
|
||||
}
|
||||
socket = ss;
|
||||
// Store the port number
|
||||
String localPort = String.valueOf(ss.getLocalPort());
|
||||
Settings s = new Settings();
|
||||
@@ -412,7 +433,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
|
||||
private void publishHiddenService(String port) {
|
||||
if (!running) return;
|
||||
if (!state.isTorRunning()) return;
|
||||
LOG.info("Creating hidden service");
|
||||
String privKey = settings.get(HS_PRIVKEY);
|
||||
Map<Integer, String> portLines = singletonMap(80, "127.0.0.1:" + port);
|
||||
@@ -450,14 +471,15 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
|
||||
private void acceptContactConnections(ServerSocket ss) {
|
||||
while (running) {
|
||||
while (true) {
|
||||
Socket s;
|
||||
try {
|
||||
s = ss.accept();
|
||||
s.setSoTimeout(socketTimeout);
|
||||
} catch (IOException e) {
|
||||
// This is expected when the socket is closed
|
||||
if (LOG.isLoggable(INFO)) LOG.info(e.toString());
|
||||
// This is expected when the server socket is closed
|
||||
LOG.info("Server socket closed");
|
||||
state.clearServerSocket(ss);
|
||||
return;
|
||||
}
|
||||
LOG.info("Connection received");
|
||||
@@ -467,10 +489,8 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
|
||||
protected void enableNetwork(boolean enable) throws IOException {
|
||||
if (!running) return;
|
||||
connectionStatus.enableNetwork(enable);
|
||||
state.enableNetwork(enable);
|
||||
controlConnection.setConf("DisableNetwork", enable ? "0" : "1");
|
||||
if (!enable) callback.transportDisabled();
|
||||
}
|
||||
|
||||
private void enableBridges(boolean enable, boolean needsMeek)
|
||||
@@ -494,9 +514,8 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
running = false;
|
||||
tryToClose(socket, LOG, WARNING);
|
||||
callback.transportDisabled();
|
||||
ServerSocket ss = state.setStopped();
|
||||
tryToClose(ss, LOG, WARNING);
|
||||
if (controlSocket != null && controlConnection != null) {
|
||||
try {
|
||||
LOG.info("Stopping Tor");
|
||||
@@ -510,8 +529,13 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRunning() {
|
||||
return running && connectionStatus.isConnected();
|
||||
public State getState() {
|
||||
return state.getState();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getReasonDisabled() {
|
||||
return state.getReasonDisabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -527,7 +551,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
@Override
|
||||
public void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
||||
properties) {
|
||||
if (!isRunning()) return;
|
||||
if (getState() != ACTIVE) return;
|
||||
backoff.increment();
|
||||
for (Pair<TransportProperties, ConnectionHandler> p : properties) {
|
||||
connect(p.getFirst(), p.getSecond());
|
||||
@@ -546,7 +570,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
|
||||
@Override
|
||||
public DuplexTransportConnection createConnection(TransportProperties p) {
|
||||
if (!isRunning()) return null;
|
||||
if (getState() != ACTIVE) return null;
|
||||
String bestOnion = null;
|
||||
String onion2 = p.get(PROP_ONION_V2);
|
||||
String onion3 = p.get(PROP_ONION_V3);
|
||||
@@ -634,8 +658,8 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
new TorTransportConnection(this, s));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// This is expected when the socket is closed
|
||||
if (LOG.isLoggable(INFO)) LOG.info(e.toString());
|
||||
// This is expected when the server socket is closed
|
||||
LOG.info("Rendezvous server socket closed");
|
||||
}
|
||||
});
|
||||
Map<Integer, String> portLines =
|
||||
@@ -663,10 +687,9 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
@Override
|
||||
public void circuitStatus(String status, String id, String path) {
|
||||
if (status.equals("BUILT") &&
|
||||
connectionStatus.getAndSetCircuitBuilt()) {
|
||||
state.getAndSetCircuitBuilt()) {
|
||||
LOG.info("First circuit built");
|
||||
backoff.reset();
|
||||
if (isRunning()) callback.transportEnabled();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -697,9 +720,8 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
public void message(String severity, String msg) {
|
||||
if (LOG.isLoggable(INFO)) LOG.info(severity + " " + msg);
|
||||
if (severity.equals("NOTICE") && msg.startsWith("Bootstrapped 100%")) {
|
||||
connectionStatus.setBootstrapped();
|
||||
state.setBootstrapped();
|
||||
backoff.reset();
|
||||
if (isRunning()) callback.transportEnabled();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -736,7 +758,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
private void disableNetwork() {
|
||||
connectionStatusExecutor.execute(() -> {
|
||||
try {
|
||||
enableNetwork(false);
|
||||
if (state.isTorRunning()) enableNetwork(false);
|
||||
} catch (IOException ex) {
|
||||
logException(LOG, WARNING, ex);
|
||||
}
|
||||
@@ -746,12 +768,13 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
private void updateConnectionStatus(NetworkStatus status,
|
||||
boolean charging) {
|
||||
connectionStatusExecutor.execute(() -> {
|
||||
if (!running) return;
|
||||
if (!state.isTorRunning()) return;
|
||||
boolean online = status.isConnected();
|
||||
boolean wifi = status.isWifi();
|
||||
String country = locationUtils.getCurrentCountry();
|
||||
boolean blocked =
|
||||
circumventionProvider.isTorProbablyBlocked(country);
|
||||
boolean enabledByUser = settings.getBoolean(PREF_PLUGIN_ENABLE, true);
|
||||
int network = settings.getInt(PREF_TOR_NETWORK,
|
||||
PREF_TOR_NETWORK_AUTOMATIC);
|
||||
boolean useMobile = settings.getBoolean(PREF_TOR_MOBILE, true);
|
||||
@@ -762,47 +785,67 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
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);
|
||||
LOG.info("Charging: " + charging);
|
||||
}
|
||||
|
||||
try {
|
||||
if (!online) {
|
||||
LOG.info("Disabling network, device is offline");
|
||||
enableNetwork(false);
|
||||
} else if (!charging && onlyWhenCharging) {
|
||||
LOG.info("Disabling network, device is on battery");
|
||||
enableNetwork(false);
|
||||
} else if (network == PREF_TOR_NETWORK_NEVER ||
|
||||
(!useMobile && !wifi)) {
|
||||
LOG.info("Disabling network, device is using mobile data");
|
||||
enableNetwork(false);
|
||||
} else if (automatic && blocked && !bridgesWork) {
|
||||
LOG.info("Disabling network, country is blocked");
|
||||
enableNetwork(false);
|
||||
} else if (network == PREF_TOR_NETWORK_WITH_BRIDGES ||
|
||||
boolean enableNetwork = false, enableBridges = false;
|
||||
boolean useMeek = false, enableConnectionPadding = false;
|
||||
boolean disabledBySettings = false;
|
||||
int reasonDisabled = REASON_STARTING_STOPPING;
|
||||
|
||||
if (!online) {
|
||||
LOG.info("Disabling network, device is offline");
|
||||
} else if (!enabledByUser) {
|
||||
LOG.info("Disabling network, user has disabled Tor");
|
||||
disabledBySettings = true;
|
||||
reasonDisabled = REASON_USER;
|
||||
} else if (!charging && onlyWhenCharging) {
|
||||
LOG.info("Disabling network, device is on battery");
|
||||
disabledBySettings = true;
|
||||
reasonDisabled = REASON_BATTERY;
|
||||
} else if (!useMobile && !wifi) {
|
||||
LOG.info("Disabling network, device is using mobile data");
|
||||
disabledBySettings = true;
|
||||
reasonDisabled = REASON_MOBILE_DATA;
|
||||
} else if (automatic && blocked && !bridgesWork) {
|
||||
LOG.info("Disabling network, country is blocked");
|
||||
disabledBySettings = true;
|
||||
reasonDisabled = REASON_COUNTRY_BLOCKED;
|
||||
} else {
|
||||
LOG.info("Enabling network");
|
||||
enableNetwork = true;
|
||||
if (network == PREF_TOR_NETWORK_WITH_BRIDGES ||
|
||||
(automatic && bridgesWork)) {
|
||||
if (circumventionProvider.needsMeek(country)) {
|
||||
LOG.info("Enabling network, using meek bridges");
|
||||
enableBridges(true, true);
|
||||
LOG.info("Using meek bridges");
|
||||
enableBridges = true;
|
||||
useMeek = true;
|
||||
} else {
|
||||
LOG.info("Enabling network, using obfs4 bridges");
|
||||
enableBridges(true, false);
|
||||
LOG.info("Using obfs4 bridges");
|
||||
enableBridges = true;
|
||||
}
|
||||
enableNetwork(true);
|
||||
} else {
|
||||
LOG.info("Enabling network, not using bridges");
|
||||
enableBridges(false, false);
|
||||
enableNetwork(true);
|
||||
LOG.info("Not using bridges");
|
||||
}
|
||||
if (online && wifi && charging) {
|
||||
if (wifi && charging) {
|
||||
LOG.info("Enabling connection padding");
|
||||
enableConnectionPadding(true);
|
||||
enableConnectionPadding = true;
|
||||
} else {
|
||||
LOG.info("Disabling connection padding");
|
||||
enableConnectionPadding(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
state.setDisabledBySettings(disabledBySettings, reasonDisabled);
|
||||
|
||||
try {
|
||||
if (enableNetwork) {
|
||||
enableBridges(enableBridges, useMeek);
|
||||
enableConnectionPadding(enableConnectionPadding);
|
||||
}
|
||||
enableNetwork(enableNetwork);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
@@ -810,33 +853,100 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
|
||||
private void enableConnectionPadding(boolean enable) throws IOException {
|
||||
if (!running) return;
|
||||
controlConnection.setConf("ConnectionPadding", enable ? "1" : "0");
|
||||
}
|
||||
|
||||
private static class ConnectionStatus {
|
||||
@ThreadSafe
|
||||
@NotNullByDefault
|
||||
protected class PluginState {
|
||||
|
||||
// All of the following are locking: this
|
||||
private boolean networkEnabled = false;
|
||||
private boolean bootstrapped = false, circuitBuilt = false;
|
||||
@GuardedBy("this")
|
||||
private boolean started = false,
|
||||
stopped = false,
|
||||
torStarted = false,
|
||||
networkInitialised = false,
|
||||
networkEnabled = false,
|
||||
bootstrapped = false,
|
||||
circuitBuilt = false,
|
||||
disabledBySettings = false;
|
||||
|
||||
private synchronized void setBootstrapped() {
|
||||
bootstrapped = true;
|
||||
@GuardedBy("this")
|
||||
private int reasonDisabled = REASON_STARTING_STOPPING;
|
||||
|
||||
@GuardedBy("this")
|
||||
@Nullable
|
||||
private ServerSocket serverSocket = null;
|
||||
|
||||
synchronized void setStarted() {
|
||||
started = true;
|
||||
callback.pluginStateChanged(getState());
|
||||
}
|
||||
|
||||
private synchronized boolean getAndSetCircuitBuilt() {
|
||||
// Doesn't affect getState()
|
||||
synchronized void setTorStarted() {
|
||||
torStarted = true;
|
||||
}
|
||||
|
||||
synchronized boolean isTorRunning() {
|
||||
return torStarted && !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;
|
||||
circuitBuilt = true;
|
||||
callback.pluginStateChanged(getState());
|
||||
return firstCircuit;
|
||||
}
|
||||
|
||||
private synchronized void enableNetwork(boolean enable) {
|
||||
synchronized void enableNetwork(boolean enable) {
|
||||
networkInitialised = true;
|
||||
networkEnabled = enable;
|
||||
if (!enable) circuitBuilt = false;
|
||||
callback.pluginStateChanged(getState());
|
||||
}
|
||||
|
||||
private synchronized boolean isConnected() {
|
||||
return networkEnabled && bootstrapped && circuitBuilt;
|
||||
synchronized void setDisabledBySettings(boolean disabledBySettings,
|
||||
int reasonDisabled) {
|
||||
this.disabledBySettings = disabledBySettings;
|
||||
this.reasonDisabled = reasonDisabled;
|
||||
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 || disabledBySettings) return DISABLED;
|
||||
if (!networkInitialised) return ENABLING;
|
||||
if (!networkEnabled) return INACTIVE;
|
||||
return bootstrapped && circuitBuilt ? ACTIVE : ENABLING;
|
||||
}
|
||||
|
||||
synchronized int getReasonDisabled() {
|
||||
return getState() == DISABLED ? reasonDisabled : -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,11 +37,6 @@ import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.GROUP_KEY_DISCOVERED;
|
||||
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_VERSION;
|
||||
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
@@ -116,10 +111,10 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
try {
|
||||
// Find the latest update for this transport, if any
|
||||
BdfDictionary d = metadataParser.parse(meta);
|
||||
TransportId t = new TransportId(d.getString(MSG_KEY_TRANSPORT_ID));
|
||||
TransportId t = new TransportId(d.getString("transportId"));
|
||||
LatestUpdate latest = findLatest(txn, m.getGroupId(), t, false);
|
||||
if (latest != null) {
|
||||
if (d.getLong(MSG_KEY_VERSION) > latest.version) {
|
||||
if (d.getLong("version") > latest.version) {
|
||||
// This update is newer - delete the previous update
|
||||
db.deleteMessage(txn, latest.messageId);
|
||||
db.deleteMessageMetadata(txn, latest.messageId);
|
||||
@@ -145,27 +140,6 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addRemotePropertiesFromConnection(ContactId c, TransportId t,
|
||||
TransportProperties props) throws DbException {
|
||||
if (props.isEmpty()) return;
|
||||
try {
|
||||
db.transaction(false, txn -> {
|
||||
Group g = getContactGroup(db.getContact(txn, c));
|
||||
BdfDictionary meta = clientHelper.getGroupMetadataAsDictionary(
|
||||
txn, g.getId());
|
||||
BdfDictionary discovered =
|
||||
meta.getOptionalDictionary(GROUP_KEY_DISCOVERED);
|
||||
if (discovered == null) discovered = new BdfDictionary();
|
||||
discovered.putAll(props);
|
||||
meta.put(GROUP_KEY_DISCOVERED, discovered);
|
||||
clientHelper.mergeGroupMetadata(txn, g.getId(), meta);
|
||||
});
|
||||
} catch (FormatException e) {
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<TransportId, TransportProperties> getLocalProperties()
|
||||
throws DbException {
|
||||
@@ -229,26 +203,12 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
Group g = getContactGroup(c);
|
||||
try {
|
||||
// Find the latest remote update
|
||||
TransportProperties remote;
|
||||
LatestUpdate latest = findLatest(txn, g.getId(), t, false);
|
||||
if (latest == null) {
|
||||
remote = new TransportProperties();
|
||||
} else {
|
||||
// Retrieve and parse the latest remote properties
|
||||
BdfList message =
|
||||
clientHelper.getMessageAsList(txn, latest.messageId);
|
||||
remote = parseProperties(message);
|
||||
}
|
||||
// Merge in any discovered properties
|
||||
BdfDictionary meta =
|
||||
clientHelper.getGroupMetadataAsDictionary(txn, g.getId());
|
||||
BdfDictionary d = meta.getOptionalDictionary(GROUP_KEY_DISCOVERED);
|
||||
if (d == null) return remote;
|
||||
TransportProperties merged =
|
||||
clientHelper.parseAndValidateTransportProperties(d);
|
||||
// Received properties override discovered properties
|
||||
merged.putAll(remote);
|
||||
return merged;
|
||||
if (latest == null) return new TransportProperties();
|
||||
// Retrieve and parse the latest remote properties
|
||||
BdfList message =
|
||||
clientHelper.getMessageAsList(txn, latest.messageId);
|
||||
return parseProperties(message);
|
||||
} catch (FormatException e) {
|
||||
throw new DbException(e);
|
||||
}
|
||||
@@ -321,9 +281,9 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
long now = clock.currentTimeMillis();
|
||||
Message m = clientHelper.createMessage(g, now, body);
|
||||
BdfDictionary meta = new BdfDictionary();
|
||||
meta.put(MSG_KEY_TRANSPORT_ID, t.getString());
|
||||
meta.put(MSG_KEY_VERSION, version);
|
||||
meta.put(MSG_KEY_LOCAL, local);
|
||||
meta.put("transportId", t.getString());
|
||||
meta.put("version", version);
|
||||
meta.put("local", local);
|
||||
clientHelper.addLocalMessage(txn, m, meta, shared, false);
|
||||
} catch (FormatException e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -342,9 +302,8 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
.getMessageMetadataAsDictionary(txn, localGroup.getId());
|
||||
for (Entry<MessageId, BdfDictionary> e : metadata.entrySet()) {
|
||||
BdfDictionary meta = e.getValue();
|
||||
TransportId t =
|
||||
new TransportId(meta.getString(MSG_KEY_TRANSPORT_ID));
|
||||
long version = meta.getLong(MSG_KEY_VERSION);
|
||||
TransportId t = new TransportId(meta.getString("transportId"));
|
||||
long version = meta.getLong("version");
|
||||
latestUpdates.put(t, new LatestUpdate(e.getKey(), version));
|
||||
}
|
||||
return latestUpdates;
|
||||
@@ -357,10 +316,9 @@ class TransportPropertyManagerImpl implements TransportPropertyManager,
|
||||
clientHelper.getMessageMetadataAsDictionary(txn, g);
|
||||
for (Entry<MessageId, BdfDictionary> e : metadata.entrySet()) {
|
||||
BdfDictionary meta = e.getValue();
|
||||
if (meta.getString(MSG_KEY_TRANSPORT_ID).equals(t.getString())
|
||||
&& meta.getBoolean(MSG_KEY_LOCAL) == local) {
|
||||
return new LatestUpdate(e.getKey(),
|
||||
meta.getLong(MSG_KEY_VERSION));
|
||||
if (meta.getString("transportId").equals(t.getString())
|
||||
&& meta.getBoolean("local") == local) {
|
||||
return new LatestUpdate(e.getKey(), meta.getLong("version"));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -31,8 +31,8 @@ import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportDisabledEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportActiveEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
||||
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
||||
@@ -269,11 +269,11 @@ class RendezvousPollerImpl implements RendezvousPoller, Service, EventListener {
|
||||
} else if (e instanceof PendingContactRemovedEvent) {
|
||||
PendingContactRemovedEvent p = (PendingContactRemovedEvent) e;
|
||||
removePendingContactAsync(p.getId());
|
||||
} else if (e instanceof TransportEnabledEvent) {
|
||||
TransportEnabledEvent t = (TransportEnabledEvent) e;
|
||||
} else if (e instanceof TransportActiveEvent) {
|
||||
TransportActiveEvent t = (TransportActiveEvent) e;
|
||||
addTransportAsync(t.getTransportId());
|
||||
} else if (e instanceof TransportDisabledEvent) {
|
||||
TransportDisabledEvent t = (TransportDisabledEvent) e;
|
||||
} else if (e instanceof TransportInactiveEvent) {
|
||||
TransportInactiveEvent t = (TransportInactiveEvent) e;
|
||||
removeTransportAsync(t.getTransportId());
|
||||
} else if (e instanceof RendezvousConnectionOpenedEvent) {
|
||||
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.nullsafety.NotNullByDefault;
|
||||
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.DevReporter;
|
||||
import org.briarproject.bramble.util.IoUtils;
|
||||
@@ -92,8 +92,8 @@ class DevReporterImpl implements DevReporter, EventListener {
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (e instanceof TransportEnabledEvent) {
|
||||
TransportEnabledEvent t = (TransportEnabledEvent) e;
|
||||
if (e instanceof TransportActiveEvent) {
|
||||
TransportActiveEvent t = (TransportActiveEvent) e;
|
||||
if (t.getTransportId().equals(TorConstants.ID))
|
||||
ioExecutor.execute(this::sendReports);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import org.briarproject.bramble.api.event.EventListener;
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.lifecycle.event.LifecycleEvent;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.sync.Ack;
|
||||
import org.briarproject.bramble.api.sync.Message;
|
||||
import org.briarproject.bramble.api.sync.Offer;
|
||||
@@ -19,7 +18,6 @@ import org.briarproject.bramble.api.sync.Request;
|
||||
import org.briarproject.bramble.api.sync.SyncRecordWriter;
|
||||
import org.briarproject.bramble.api.sync.SyncSession;
|
||||
import org.briarproject.bramble.api.sync.Versions;
|
||||
import org.briarproject.bramble.api.sync.event.CloseSyncConnectionsEvent;
|
||||
import org.briarproject.bramble.api.sync.event.GroupVisibilityUpdatedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageRequestedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageSharedEvent;
|
||||
@@ -73,7 +71,6 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
|
||||
private final EventBus eventBus;
|
||||
private final Clock clock;
|
||||
private final ContactId contactId;
|
||||
private final TransportId transportId;
|
||||
private final int maxLatency, maxIdleTime;
|
||||
private final StreamWriter streamWriter;
|
||||
private final SyncRecordWriter recordWriter;
|
||||
@@ -89,15 +86,14 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
|
||||
private volatile boolean interrupted = false;
|
||||
|
||||
DuplexOutgoingSession(DatabaseComponent db, Executor dbExecutor,
|
||||
EventBus eventBus, Clock clock, ContactId contactId,
|
||||
TransportId transportId, int maxLatency, int maxIdleTime,
|
||||
StreamWriter streamWriter, SyncRecordWriter recordWriter) {
|
||||
EventBus eventBus, Clock clock, ContactId contactId, int maxLatency,
|
||||
int maxIdleTime, StreamWriter streamWriter,
|
||||
SyncRecordWriter recordWriter) {
|
||||
this.db = db;
|
||||
this.dbExecutor = dbExecutor;
|
||||
this.eventBus = eventBus;
|
||||
this.clock = clock;
|
||||
this.contactId = contactId;
|
||||
this.transportId = transportId;
|
||||
this.maxLatency = maxLatency;
|
||||
this.maxIdleTime = maxIdleTime;
|
||||
this.streamWriter = streamWriter;
|
||||
@@ -227,9 +223,6 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
|
||||
} else if (e instanceof LifecycleEvent) {
|
||||
LifecycleEvent l = (LifecycleEvent) e;
|
||||
if (l.getLifecycleState() == STOPPING) interrupt();
|
||||
} else if (e instanceof CloseSyncConnectionsEvent) {
|
||||
CloseSyncConnectionsEvent c = (CloseSyncConnectionsEvent) e;
|
||||
if (c.getTransportId().equals(transportId)) interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,13 +11,11 @@ import org.briarproject.bramble.api.event.EventListener;
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.lifecycle.event.LifecycleEvent;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.sync.Ack;
|
||||
import org.briarproject.bramble.api.sync.Message;
|
||||
import org.briarproject.bramble.api.sync.SyncRecordWriter;
|
||||
import org.briarproject.bramble.api.sync.SyncSession;
|
||||
import org.briarproject.bramble.api.sync.Versions;
|
||||
import org.briarproject.bramble.api.sync.event.CloseSyncConnectionsEvent;
|
||||
import org.briarproject.bramble.api.transport.StreamWriter;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -58,7 +56,6 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
|
||||
private final Executor dbExecutor;
|
||||
private final EventBus eventBus;
|
||||
private final ContactId contactId;
|
||||
private final TransportId transportId;
|
||||
private final int maxLatency;
|
||||
private final StreamWriter streamWriter;
|
||||
private final SyncRecordWriter recordWriter;
|
||||
@@ -68,14 +65,12 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
|
||||
private volatile boolean interrupted = false;
|
||||
|
||||
SimplexOutgoingSession(DatabaseComponent db, Executor dbExecutor,
|
||||
EventBus eventBus, ContactId contactId, TransportId transportId,
|
||||
int maxLatency, StreamWriter streamWriter,
|
||||
SyncRecordWriter recordWriter) {
|
||||
EventBus eventBus, ContactId contactId, int maxLatency,
|
||||
StreamWriter streamWriter, SyncRecordWriter recordWriter) {
|
||||
this.db = db;
|
||||
this.dbExecutor = dbExecutor;
|
||||
this.eventBus = eventBus;
|
||||
this.contactId = contactId;
|
||||
this.transportId = transportId;
|
||||
this.maxLatency = maxLatency;
|
||||
this.streamWriter = streamWriter;
|
||||
this.recordWriter = recordWriter;
|
||||
@@ -128,9 +123,6 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
|
||||
} else if (e instanceof LifecycleEvent) {
|
||||
LifecycleEvent l = (LifecycleEvent) e;
|
||||
if (l.getLifecycleState() == STOPPING) interrupt();
|
||||
} else if (e instanceof CloseSyncConnectionsEvent) {
|
||||
CloseSyncConnectionsEvent c = (CloseSyncConnectionsEvent) e;
|
||||
if (c.getTransportId().equals(transportId)) interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import org.briarproject.bramble.api.db.DatabaseComponent;
|
||||
import org.briarproject.bramble.api.db.DatabaseExecutor;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.sync.SyncRecordReader;
|
||||
import org.briarproject.bramble.api.sync.SyncRecordReaderFactory;
|
||||
import org.briarproject.bramble.api.sync.SyncRecordWriter;
|
||||
@@ -54,23 +53,22 @@ class SyncSessionFactoryImpl implements SyncSessionFactory {
|
||||
}
|
||||
|
||||
@Override
|
||||
public SyncSession createSimplexOutgoingSession(ContactId c, TransportId t,
|
||||
public SyncSession createSimplexOutgoingSession(ContactId c,
|
||||
int maxLatency, StreamWriter streamWriter) {
|
||||
OutputStream out = streamWriter.getOutputStream();
|
||||
SyncRecordWriter recordWriter =
|
||||
recordWriterFactory.createRecordWriter(out);
|
||||
return new SimplexOutgoingSession(db, dbExecutor, eventBus, c, t,
|
||||
return new SimplexOutgoingSession(db, dbExecutor, eventBus, c,
|
||||
maxLatency, streamWriter, recordWriter);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SyncSession createDuplexOutgoingSession(ContactId c,
|
||||
TransportId t, int maxLatency, int maxIdleTime,
|
||||
StreamWriter streamWriter) {
|
||||
public SyncSession createDuplexOutgoingSession(ContactId c, int maxLatency,
|
||||
int maxIdleTime, StreamWriter streamWriter) {
|
||||
OutputStream out = streamWriter.getOutputStream();
|
||||
SyncRecordWriter recordWriter =
|
||||
recordWriterFactory.createRecordWriter(out);
|
||||
return new DuplexOutgoingSession(db, dbExecutor, eventBus, clock, c, t,
|
||||
return new DuplexOutgoingSession(db, dbExecutor, eventBus, clock, c,
|
||||
maxLatency, maxIdleTime, streamWriter, recordWriter);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package org.briarproject.bramble.account;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.CryptoComponent;
|
||||
import org.briarproject.bramble.api.crypto.DecryptionException;
|
||||
import org.briarproject.bramble.api.crypto.KeyStrengthener;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
@@ -20,15 +19,12 @@ import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.Charset;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import static junit.framework.Assert.assertFalse;
|
||||
import static junit.framework.Assert.assertNull;
|
||||
import static junit.framework.Assert.assertTrue;
|
||||
import static org.briarproject.bramble.api.crypto.DecryptionResult.INVALID_CIPHERTEXT;
|
||||
import static org.briarproject.bramble.api.crypto.DecryptionResult.INVALID_PASSWORD;
|
||||
import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory;
|
||||
import static org.briarproject.bramble.test.TestUtils.getIdentity;
|
||||
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
|
||||
@@ -39,7 +35,6 @@ import static org.briarproject.bramble.util.StringUtils.toHexString;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
|
||||
@@ -88,13 +83,8 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSignInThrowsExceptionIfDbKeyCannotBeLoaded() {
|
||||
try {
|
||||
accountManager.signIn(password);
|
||||
fail();
|
||||
} catch (DecryptionException expected) {
|
||||
assertEquals(INVALID_CIPHERTEXT, expected.getDecryptionResult());
|
||||
}
|
||||
public void testSignInReturnsFalseIfDbKeyCannotBeLoaded() {
|
||||
assertFalse(accountManager.signIn(password));
|
||||
assertFalse(accountManager.hasDatabaseKey());
|
||||
|
||||
assertFalse(keyFile.exists());
|
||||
@@ -102,11 +92,11 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSignInThrowsExceptionIfPasswordIsWrong() throws Exception {
|
||||
public void testSignInReturnsFalseIfPasswordIsWrong() throws Exception {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(crypto).decryptWithPassword(encryptedKey, password,
|
||||
keyStrengthener);
|
||||
will(throwException(new DecryptionException(INVALID_PASSWORD)));
|
||||
will(returnValue(null));
|
||||
}});
|
||||
|
||||
storeDatabaseKey(keyFile, encryptedKeyHex);
|
||||
@@ -115,12 +105,7 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyFile));
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyBackupFile));
|
||||
|
||||
try {
|
||||
accountManager.signIn(password);
|
||||
fail();
|
||||
} catch (DecryptionException expected) {
|
||||
assertEquals(INVALID_PASSWORD, expected.getDecryptionResult());
|
||||
}
|
||||
assertFalse(accountManager.signIn(password));
|
||||
assertFalse(accountManager.hasDatabaseKey());
|
||||
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyFile));
|
||||
@@ -143,7 +128,7 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyFile));
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyBackupFile));
|
||||
|
||||
accountManager.signIn(password);
|
||||
assertTrue(accountManager.signIn(password));
|
||||
assertTrue(accountManager.hasDatabaseKey());
|
||||
SecretKey decrypted = accountManager.getDatabaseKey();
|
||||
assertNotNull(decrypted);
|
||||
@@ -172,7 +157,7 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyFile));
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyBackupFile));
|
||||
|
||||
accountManager.signIn(password);
|
||||
assertTrue(accountManager.signIn(password));
|
||||
assertTrue(accountManager.hasDatabaseKey());
|
||||
SecretKey decrypted = accountManager.getDatabaseKey();
|
||||
assertNotNull(decrypted);
|
||||
@@ -254,6 +239,55 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
assertFalse(keyBackupFile.exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAccountExistsReturnsFalseIfDbDirectoryDoesNotExist()
|
||||
throws Exception {
|
||||
storeDatabaseKey(keyFile, encryptedKeyHex);
|
||||
storeDatabaseKey(keyBackupFile, encryptedKeyHex);
|
||||
|
||||
assertFalse(dbDir.exists());
|
||||
|
||||
assertFalse(accountManager.accountExists());
|
||||
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyFile));
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyBackupFile));
|
||||
assertFalse(dbDir.exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAccountExistsReturnsFalseIfDbDirectoryIsNotDirectory()
|
||||
throws Exception {
|
||||
storeDatabaseKey(keyFile, encryptedKeyHex);
|
||||
storeDatabaseKey(keyBackupFile, encryptedKeyHex);
|
||||
|
||||
assertTrue(dbDir.createNewFile());
|
||||
assertFalse(dbDir.isDirectory());
|
||||
|
||||
assertFalse(accountManager.accountExists());
|
||||
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyFile));
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyBackupFile));
|
||||
assertTrue(dbDir.exists());
|
||||
assertFalse(dbDir.isDirectory());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAccountExistsReturnsTrueIfDbDirectoryIsDirectory()
|
||||
throws Exception {
|
||||
storeDatabaseKey(keyFile, encryptedKeyHex);
|
||||
storeDatabaseKey(keyBackupFile, encryptedKeyHex);
|
||||
|
||||
assertTrue(dbDir.mkdirs());
|
||||
assertTrue(dbDir.isDirectory());
|
||||
|
||||
assertTrue(accountManager.accountExists());
|
||||
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyFile));
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyBackupFile));
|
||||
assertTrue(dbDir.exists());
|
||||
assertTrue(dbDir.isDirectory());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateAccountStoresDbKey() throws Exception {
|
||||
context.checking(new Expectations() {{
|
||||
@@ -281,36 +315,26 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testChangePasswordThrowsExceptionIfDbKeyCannotBeLoaded() {
|
||||
try {
|
||||
accountManager.changePassword(password, newPassword);
|
||||
fail();
|
||||
} catch (DecryptionException expected) {
|
||||
assertEquals(INVALID_CIPHERTEXT, expected.getDecryptionResult());
|
||||
}
|
||||
public void testChangePasswordReturnsFalseIfDbKeyCannotBeLoaded() {
|
||||
assertFalse(accountManager.changePassword(password, newPassword));
|
||||
|
||||
assertFalse(keyFile.exists());
|
||||
assertFalse(keyBackupFile.exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testChangePasswordThrowsExceptionIfPasswordIsWrong()
|
||||
public void testChangePasswordReturnsFalseIfPasswordIsWrong()
|
||||
throws Exception {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(crypto).decryptWithPassword(encryptedKey, password,
|
||||
keyStrengthener);
|
||||
will(throwException(new DecryptionException(INVALID_PASSWORD)));
|
||||
will(returnValue(null));
|
||||
}});
|
||||
|
||||
storeDatabaseKey(keyFile, encryptedKeyHex);
|
||||
storeDatabaseKey(keyBackupFile, encryptedKeyHex);
|
||||
|
||||
try {
|
||||
accountManager.changePassword(password, newPassword);
|
||||
fail();
|
||||
} catch (DecryptionException expected) {
|
||||
assertEquals(INVALID_PASSWORD, expected.getDecryptionResult());
|
||||
}
|
||||
assertFalse(accountManager.changePassword(password, newPassword));
|
||||
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyFile));
|
||||
assertEquals(encryptedKeyHex, loadDatabaseKey(keyBackupFile));
|
||||
@@ -333,7 +357,7 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
storeDatabaseKey(keyFile, encryptedKeyHex);
|
||||
storeDatabaseKey(keyBackupFile, encryptedKeyHex);
|
||||
|
||||
accountManager.changePassword(password, newPassword);
|
||||
assertTrue(accountManager.changePassword(password, newPassword));
|
||||
|
||||
assertEquals(newEncryptedKeyHex, loadDatabaseKey(keyFile));
|
||||
assertEquals(newEncryptedKeyHex, loadDatabaseKey(keyBackupFile));
|
||||
@@ -342,7 +366,7 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
private void storeDatabaseKey(File f, String hex) throws IOException {
|
||||
f.getParentFile().mkdirs();
|
||||
FileOutputStream out = new FileOutputStream(f);
|
||||
out.write(hex.getBytes(Charset.forName("UTF-8")));
|
||||
out.write(hex.getBytes("UTF-8"));
|
||||
out.flush();
|
||||
out.close();
|
||||
}
|
||||
@@ -350,7 +374,7 @@ public class AccountManagerImplTest extends BrambleMockTestCase {
|
||||
@Nullable
|
||||
private String loadDatabaseKey(File f) throws IOException {
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(
|
||||
new FileInputStream(f), Charset.forName("UTF-8")));
|
||||
new FileInputStream(f), "UTF-8"));
|
||||
String hex = reader.readLine();
|
||||
reader.close();
|
||||
return hex;
|
||||
|
||||
@@ -1,35 +1,25 @@
|
||||
package org.briarproject.bramble.crypto;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.DecryptionException;
|
||||
import org.briarproject.bramble.api.crypto.KeyStrengthener;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.system.SystemClock;
|
||||
import org.briarproject.bramble.test.BrambleMockTestCase;
|
||||
import org.briarproject.bramble.test.BrambleTestCase;
|
||||
import org.briarproject.bramble.test.TestSecureRandomProvider;
|
||||
import org.jmock.Expectations;
|
||||
import org.briarproject.bramble.test.TestUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.briarproject.bramble.api.crypto.DecryptionResult.INVALID_CIPHERTEXT;
|
||||
import static org.briarproject.bramble.api.crypto.DecryptionResult.INVALID_PASSWORD;
|
||||
import static org.briarproject.bramble.api.crypto.DecryptionResult.KEY_STRENGTHENER_ERROR;
|
||||
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
|
||||
import static org.briarproject.bramble.test.TestUtils.getSecretKey;
|
||||
import java.util.Random;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
public class PasswordBasedEncryptionTest extends BrambleMockTestCase {
|
||||
|
||||
private final KeyStrengthener keyStrengthener =
|
||||
context.mock(KeyStrengthener.class);
|
||||
public class PasswordBasedEncryptionTest extends BrambleTestCase {
|
||||
|
||||
private final CryptoComponentImpl crypto =
|
||||
new CryptoComponentImpl(new TestSecureRandomProvider(),
|
||||
new ScryptKdf(new SystemClock()));
|
||||
|
||||
@Test
|
||||
public void testEncryptionAndDecryption() throws Exception {
|
||||
byte[] input = getRandomBytes(1234);
|
||||
public void testEncryptionAndDecryption() {
|
||||
byte[] input = TestUtils.getRandomBytes(1234);
|
||||
String password = "password";
|
||||
byte[] ciphertext = crypto.encryptWithPassword(input, password, null);
|
||||
byte[] output = crypto.decryptWithPassword(ciphertext, password, null);
|
||||
@@ -37,80 +27,14 @@ public class PasswordBasedEncryptionTest extends BrambleMockTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvalidFormatVersionThrowsException() {
|
||||
byte[] input = getRandomBytes(1234);
|
||||
public void testInvalidCiphertextReturnsNull() {
|
||||
byte[] input = TestUtils.getRandomBytes(1234);
|
||||
String password = "password";
|
||||
byte[] ciphertext = crypto.encryptWithPassword(input, password, null);
|
||||
|
||||
// Modify the format version
|
||||
ciphertext[0] ^= (byte) 0xFF;
|
||||
try {
|
||||
crypto.decryptWithPassword(ciphertext, password, null);
|
||||
fail();
|
||||
} catch (DecryptionException expected) {
|
||||
assertEquals(INVALID_CIPHERTEXT, expected.getDecryptionResult());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvalidPasswordThrowsException() {
|
||||
byte[] input = getRandomBytes(1234);
|
||||
byte[] ciphertext = crypto.encryptWithPassword(input, "password", null);
|
||||
|
||||
// Try to decrypt with the wrong password
|
||||
try {
|
||||
crypto.decryptWithPassword(ciphertext, "wrong", null);
|
||||
fail();
|
||||
} catch (DecryptionException expected) {
|
||||
assertEquals(INVALID_PASSWORD, expected.getDecryptionResult());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMissingKeyStrengthenerThrowsException() {
|
||||
SecretKey strengthened = getSecretKey();
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(keyStrengthener).strengthenKey(with(any(SecretKey.class)));
|
||||
will(returnValue(strengthened));
|
||||
}});
|
||||
|
||||
// Use the key strengthener during encryption
|
||||
byte[] input = getRandomBytes(1234);
|
||||
String password = "password";
|
||||
byte[] ciphertext =
|
||||
crypto.encryptWithPassword(input, password, keyStrengthener);
|
||||
|
||||
// The key strengthener is missing during decryption
|
||||
try {
|
||||
crypto.decryptWithPassword(ciphertext, password, null);
|
||||
fail();
|
||||
} catch (DecryptionException expected) {
|
||||
assertEquals(KEY_STRENGTHENER_ERROR, expected.getDecryptionResult());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testKeyStrengthenerFailureThrowsException() {
|
||||
SecretKey strengthened = getSecretKey();
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(keyStrengthener).strengthenKey(with(any(SecretKey.class)));
|
||||
will(returnValue(strengthened));
|
||||
oneOf(keyStrengthener).isInitialised();
|
||||
will(returnValue(false));
|
||||
}});
|
||||
|
||||
// Use the key strengthener during encryption
|
||||
byte[] input = getRandomBytes(1234);
|
||||
String password = "password";
|
||||
byte[] ciphertext =
|
||||
crypto.encryptWithPassword(input, password, keyStrengthener);
|
||||
|
||||
// The key strengthener fails during decryption
|
||||
try {
|
||||
crypto.decryptWithPassword(ciphertext, password, keyStrengthener);
|
||||
fail();
|
||||
} catch (DecryptionException expected) {
|
||||
assertEquals(KEY_STRENGTHENER_ERROR, expected.getDecryptionResult());
|
||||
}
|
||||
// Modify the ciphertext
|
||||
int position = new Random().nextInt(ciphertext.length);
|
||||
ciphertext[position] = (byte) (ciphertext[position] ^ 0xFF);
|
||||
byte[] output = crypto.decryptWithPassword(ciphertext, password, null);
|
||||
assertNull(output);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
package org.briarproject.bramble.io;
|
||||
|
||||
import org.briarproject.bramble.test.BrambleTestCase;
|
||||
import org.briarproject.bramble.test.SettableClock;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MINUTES;
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class TimeoutInputStreamTest extends BrambleTestCase {
|
||||
|
||||
private static final long TIMEOUT_MS = MINUTES.toMillis(1);
|
||||
|
||||
private final long now = System.currentTimeMillis();
|
||||
|
||||
private AtomicLong time;
|
||||
private UnresponsiveInputStream in;
|
||||
private AtomicBoolean listenerCalled;
|
||||
private TimeoutInputStream stream;
|
||||
private CountDownLatch readReturned;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
time = new AtomicLong(now);
|
||||
in = new UnresponsiveInputStream();
|
||||
listenerCalled = new AtomicBoolean(false);
|
||||
stream = new TimeoutInputStream(new SettableClock(time), in,
|
||||
TIMEOUT_MS, stream -> listenerCalled.set(true));
|
||||
readReturned = new CountDownLatch(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTimeoutIsReportedIfReadDoesNotReturn() throws Exception {
|
||||
startReading();
|
||||
try {
|
||||
// The stream should not report a timeout
|
||||
assertFalse(stream.hasTimedOut());
|
||||
|
||||
// Time passes
|
||||
time.set(now + TIMEOUT_MS);
|
||||
|
||||
// The stream still shouldn't report a timeout
|
||||
assertFalse(stream.hasTimedOut());
|
||||
|
||||
// Time passes
|
||||
time.set(now + TIMEOUT_MS + 1);
|
||||
|
||||
// The stream should report a timeout
|
||||
assertTrue(stream.hasTimedOut());
|
||||
|
||||
// The listener should not have been called yet
|
||||
assertFalse(listenerCalled.get());
|
||||
|
||||
// Close the stream
|
||||
stream.close();
|
||||
|
||||
// The listener should have been called
|
||||
assertTrue(listenerCalled.get());
|
||||
} finally {
|
||||
// Allow the read to return
|
||||
in.readFinished.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTimeoutIsNotReportedIfReadReturns() throws Exception {
|
||||
startReading();
|
||||
try {
|
||||
// The stream should not report a timeout
|
||||
assertFalse(stream.hasTimedOut());
|
||||
|
||||
// Time passes
|
||||
time.set(now + TIMEOUT_MS);
|
||||
|
||||
// The stream still shouldn't report a timeout
|
||||
assertFalse(stream.hasTimedOut());
|
||||
|
||||
// Allow the read to finish and wait for it to return
|
||||
in.readFinished.countDown();
|
||||
readReturned.await(10, SECONDS);
|
||||
|
||||
// Time passes
|
||||
time.set(now + TIMEOUT_MS + 1);
|
||||
|
||||
// The stream should not report a timeout as the read has returned
|
||||
assertFalse(stream.hasTimedOut());
|
||||
|
||||
// The listener should not have been called yet
|
||||
assertFalse(listenerCalled.get());
|
||||
|
||||
// Close the stream
|
||||
stream.close();
|
||||
|
||||
// The listener should have been called
|
||||
assertTrue(listenerCalled.get());
|
||||
} finally {
|
||||
// Allow the read to return in case an assertion was thrown
|
||||
in.readFinished.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
private void startReading() throws Exception {
|
||||
// Start a background thread to read from the unresponsive stream
|
||||
new Thread(() -> {
|
||||
try {
|
||||
assertEquals(123, stream.read());
|
||||
readReturned.countDown();
|
||||
} catch (IOException e) {
|
||||
fail();
|
||||
}
|
||||
}).start();
|
||||
// Wait for the background thread to start reading
|
||||
assertTrue(in.readStarted.await(10, SECONDS));
|
||||
}
|
||||
|
||||
private class UnresponsiveInputStream extends InputStream {
|
||||
|
||||
private final CountDownLatch readStarted = new CountDownLatch(1);
|
||||
private final CountDownLatch readFinished = new CountDownLatch(1);
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
readStarted.countDown();
|
||||
try {
|
||||
readFinished.await();
|
||||
return 123;
|
||||
} catch (InterruptedException e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,8 @@ import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.plugin.event.ConnectionClosedEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.ConnectionOpenedEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportDisabledEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportActiveEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||
import org.briarproject.bramble.api.plugin.simplex.SimplexPlugin;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
||||
@@ -322,7 +322,7 @@ public class PollerImplTest extends BrambleMockTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPollsOnTransportEnabled() throws Exception {
|
||||
public void testPollsOnTransportActivated() throws Exception {
|
||||
DuplexPlugin plugin = context.mock(DuplexPlugin.class);
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
@@ -361,7 +361,7 @@ public class PollerImplTest extends BrambleMockTestCase {
|
||||
pairOf(equal(properties), any(ConnectionHandler.class)))));
|
||||
}});
|
||||
|
||||
poller.eventOccurred(new TransportEnabledEvent(transportId));
|
||||
poller.eventOccurred(new TransportActiveEvent(transportId));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -402,11 +402,11 @@ public class PollerImplTest extends BrambleMockTestCase {
|
||||
// All contacts are connected, so don't poll the plugin
|
||||
}});
|
||||
|
||||
poller.eventOccurred(new TransportEnabledEvent(transportId));
|
||||
poller.eventOccurred(new TransportActiveEvent(transportId));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCancelsPollingOnTransportDisabled() {
|
||||
public void testCancelsPollingOnTransportDeactivated() {
|
||||
Plugin plugin = context.mock(Plugin.class);
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
@@ -424,11 +424,11 @@ public class PollerImplTest extends BrambleMockTestCase {
|
||||
oneOf(scheduler).schedule(with(any(Runnable.class)), with(0L),
|
||||
with(MILLISECONDS));
|
||||
will(returnValue(future));
|
||||
// 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);
|
||||
}});
|
||||
|
||||
poller.eventOccurred(new TransportEnabledEvent(transportId));
|
||||
poller.eventOccurred(new TransportDisabledEvent(transportId));
|
||||
poller.eventOccurred(new TransportActiveEvent(transportId));
|
||||
poller.eventOccurred(new TransportInactiveEvent(transportId));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,182 +0,0 @@
|
||||
package org.briarproject.bramble.plugin.bluetooth;
|
||||
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.sync.event.CloseSyncConnectionsEvent;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.test.BrambleMockTestCase;
|
||||
import org.briarproject.bramble.test.SettableClock;
|
||||
import org.jmock.Expectations;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static org.briarproject.bramble.plugin.bluetooth.BluetoothConnectionLimiter.MIN_ATTEMPT_INTERVAL_MS;
|
||||
import static org.briarproject.bramble.plugin.bluetooth.BluetoothConnectionLimiter.STABILITY_PERIOD_MS;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class BluetoothConnectionLimiterImplTest extends BrambleMockTestCase {
|
||||
|
||||
private final EventBus eventBus = context.mock(EventBus.class);
|
||||
|
||||
private final DuplexTransportConnection conn1 =
|
||||
context.mock(DuplexTransportConnection.class, "conn1");
|
||||
private final DuplexTransportConnection conn2 =
|
||||
context.mock(DuplexTransportConnection.class, "conn2");
|
||||
private final DuplexTransportConnection conn3 =
|
||||
context.mock(DuplexTransportConnection.class, "conn3");
|
||||
|
||||
private final long now = System.currentTimeMillis();
|
||||
|
||||
private AtomicLong time;
|
||||
private BluetoothConnectionLimiter limiter;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
time = new AtomicLong(now);
|
||||
Clock clock = new SettableClock(time);
|
||||
limiter = new BluetoothConnectionLimiterImpl(eventBus, clock);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLimiterDoesNotAllowContactConnectionsDuringKeyAgreement() {
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
|
||||
expectCloseSyncConnectionsEvent();
|
||||
limiter.keyAgreementStarted();
|
||||
|
||||
assertFalse(limiter.canOpenContactConnection());
|
||||
|
||||
limiter.keyAgreementEnded();
|
||||
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLimiterAllowsAttemptToRaiseLimitAtStartup() {
|
||||
// First outgoing connection is allowed - we're below the limit of 1
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
assertTrue(limiter.contactConnectionOpened(conn1, false));
|
||||
|
||||
// Second outgoing connection is allowed - it's time to try raising
|
||||
// the limit to 2
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
assertTrue(limiter.contactConnectionOpened(conn2, false));
|
||||
|
||||
// Third outgoing connection is not allowed - we're above the limit of 1
|
||||
assertFalse(limiter.canOpenContactConnection());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLimiterAllowsThirdConnectionAfterFirstTwoAreClosed() {
|
||||
// First outgoing connection is allowed - we're below the limit of 1
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
assertTrue(limiter.contactConnectionOpened(conn1, false));
|
||||
|
||||
// Second outgoing connection is allowed - it's time to try raising
|
||||
// the limit to 2
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
assertTrue(limiter.contactConnectionOpened(conn2, false));
|
||||
|
||||
// Third outgoing connection is not allowed - we're above the limit of 1
|
||||
assertFalse(limiter.canOpenContactConnection());
|
||||
|
||||
// Close the first connection
|
||||
limiter.connectionClosed(conn1, false);
|
||||
|
||||
// Third outgoing connection is not allowed - we're at the limit of 1
|
||||
assertFalse(limiter.canOpenContactConnection());
|
||||
|
||||
// Close the second connection
|
||||
limiter.connectionClosed(conn2, false);
|
||||
|
||||
// Third outgoing connection is allowed - we're below the limit of 1
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
assertTrue(limiter.contactConnectionOpened(conn3, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLimiterRaisesLimitWhenConnectionsAreStable() {
|
||||
// First outgoing connection is allowed - we're below the limit of 1
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
assertTrue(limiter.contactConnectionOpened(conn1, false));
|
||||
|
||||
// Second outgoing connection is allowed - it's time to try raising
|
||||
// the limit to 2
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
assertTrue(limiter.contactConnectionOpened(conn2, false));
|
||||
|
||||
// Third outgoing connection is not allowed - we're above the limit of 1
|
||||
assertFalse(limiter.canOpenContactConnection());
|
||||
|
||||
// Time passes
|
||||
time.set(now + STABILITY_PERIOD_MS);
|
||||
|
||||
// Third outgoing connection is still not allowed - first two are now
|
||||
// stable so limit is raised to 2, but we're already at the new limit
|
||||
assertFalse(limiter.canOpenContactConnection());
|
||||
|
||||
// Time passes
|
||||
time.set(now + MIN_ATTEMPT_INTERVAL_MS);
|
||||
|
||||
// Third outgoing connection is allowed - it's time to try raising
|
||||
// the limit to 3
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
assertTrue(limiter.contactConnectionOpened(conn3, false));
|
||||
|
||||
// Fourth outgoing connection is not allowed - we're above the limit
|
||||
// of 2
|
||||
assertFalse(limiter.canOpenContactConnection());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLimiterIncreasesIntervalWhenConnectionFailsAboveLimit() {
|
||||
// First outgoing connection is allowed - we're below the limit of 1
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
assertTrue(limiter.contactConnectionOpened(conn1, false));
|
||||
|
||||
// Time passes
|
||||
time.set(now + 1);
|
||||
|
||||
// Second outgoing connection is allowed - it's time to try raising
|
||||
// the limit to 2
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
assertTrue(limiter.contactConnectionOpened(conn2, false));
|
||||
|
||||
// Time passes - the first connection is stable, the second isn't
|
||||
time.set(now + STABILITY_PERIOD_MS);
|
||||
|
||||
// First connection fails. The second connection isn't stable yet, so
|
||||
// the limiter considers this a failed attempt and doubles the interval
|
||||
// between attempts
|
||||
limiter.connectionClosed(conn1, true);
|
||||
|
||||
// Third outgoing connection is not allowed - we're still at the limit
|
||||
// of 1
|
||||
assertFalse(limiter.canOpenContactConnection());
|
||||
|
||||
// Time passes - nearly time for the second attempt
|
||||
time.set(now + MIN_ATTEMPT_INTERVAL_MS * 2);
|
||||
|
||||
// Third outgoing connection is not allowed - we're still at the limit
|
||||
// of 1
|
||||
assertFalse(limiter.canOpenContactConnection());
|
||||
|
||||
// Time passes - now it's time for the second attempt
|
||||
time.set(now + 1 + MIN_ATTEMPT_INTERVAL_MS * 2);
|
||||
|
||||
// Third outgoing connection is allowed - it's time to try raising the
|
||||
// limit to 2 again
|
||||
assertTrue(limiter.canOpenContactConnection());
|
||||
assertTrue(limiter.contactConnectionOpened(conn3, false));
|
||||
}
|
||||
|
||||
private void expectCloseSyncConnectionsEvent() {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(eventBus).broadcast(with(any(
|
||||
CloseSyncConnectionsEvent.class)));
|
||||
}});
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,16 @@ import org.briarproject.bramble.api.data.BdfList;
|
||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
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.TransportConnectionReader;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.settings.Settings;
|
||||
import org.briarproject.bramble.plugin.tcp.LanTcpPlugin.LanAddressComparator;
|
||||
import org.briarproject.bramble.test.BrambleTestCase;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -21,6 +23,7 @@ import java.net.InetSocketAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.util.Comparator;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
@@ -31,89 +34,57 @@ import static java.util.concurrent.Executors.newCachedThreadPool;
|
||||
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.TRANSPORT_ID_LAN;
|
||||
import static org.briarproject.bramble.plugin.tcp.LanTcpPlugin.areAddressesInSameNetwork;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.PREF_PLUGIN_ENABLE;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assume.assumeTrue;
|
||||
|
||||
public class LanTcpPluginTest extends BrambleTestCase {
|
||||
|
||||
private final Backoff backoff = new TestBackoff();
|
||||
private final ExecutorService ioExecutor = newCachedThreadPool();
|
||||
|
||||
private Callback callback = null;
|
||||
private LanTcpPlugin plugin = null;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
callback = new Callback();
|
||||
plugin = new LanTcpPlugin(ioExecutor, backoff, callback, 0, 0, 1000) {
|
||||
@Override
|
||||
protected boolean canConnectToOwnAddress() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAreAddressesInSameNetwork() {
|
||||
// Local and remote in 10.0.0.0/8
|
||||
assertTrue(areAddressesInSameNetwork(makeAddress(10, 0, 0, 0),
|
||||
makeAddress(10, 255, 255, 255), 8));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(10, 0, 0, 0),
|
||||
makeAddress(10, 255, 255, 255), 9));
|
||||
|
||||
// Local and remote in 172.16.0.0/12
|
||||
assertTrue(areAddressesInSameNetwork(makeAddress(172, 16, 0, 0),
|
||||
makeAddress(172, 31, 255, 255), 12));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(172, 16, 0, 0),
|
||||
makeAddress(172, 31, 255, 255), 13));
|
||||
|
||||
// Local and remote in 192.168.0.0/16
|
||||
assertTrue(areAddressesInSameNetwork(makeAddress(192, 168, 0, 0),
|
||||
makeAddress(192, 168, 255, 255), 16));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(192, 168, 0, 0),
|
||||
makeAddress(192, 168, 255, 255), 17));
|
||||
|
||||
// Local and remote in 169.254.0.0/16
|
||||
assertTrue(areAddressesInSameNetwork(makeAddress(169, 254, 0, 0),
|
||||
makeAddress(169, 254, 255, 255), 16));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(169, 254, 0, 0),
|
||||
makeAddress(169, 254, 255, 255), 17));
|
||||
|
||||
// Local in 10.0.0.0/8, remote in a different network
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(10, 0, 0, 0),
|
||||
makeAddress(172, 31, 255, 255), 8));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(10, 0, 0, 0),
|
||||
makeAddress(192, 168, 255, 255), 8));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(10, 0, 0, 0),
|
||||
makeAddress(169, 254, 255, 255), 8));
|
||||
|
||||
// Local in 172.16.0.0/12, remote in a different network
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(172, 16, 0, 0),
|
||||
makeAddress(10, 255, 255, 255), 12));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(172, 16, 0, 0),
|
||||
makeAddress(192, 168, 255, 255), 12));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(172, 16, 0, 0),
|
||||
makeAddress(169, 254, 255, 255), 12));
|
||||
|
||||
// Local in 192.168.0.0/16, remote in a different network
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(192, 168, 0, 0),
|
||||
makeAddress(10, 255, 255, 255), 16));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(192, 168, 0, 0),
|
||||
makeAddress(172, 31, 255, 255), 16));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(192, 168, 0, 0),
|
||||
makeAddress(169, 254, 255, 255), 16));
|
||||
|
||||
// Local in 169.254.0.0/16, remote in a different network
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(169, 254, 0, 0),
|
||||
makeAddress(10, 255, 255, 255), 16));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(169, 254, 0, 0),
|
||||
makeAddress(172, 31, 255, 255), 16));
|
||||
assertFalse(areAddressesInSameNetwork(makeAddress(169, 254, 0, 0),
|
||||
makeAddress(192, 168, 255, 255), 16));
|
||||
public void testAddressesAreOnSameLan() {
|
||||
Callback callback = new Callback();
|
||||
LanTcpPlugin plugin = new LanTcpPlugin(ioExecutor, backoff, callback,
|
||||
0, 0);
|
||||
// Local and remote in 10.0.0.0/8 should return true
|
||||
assertTrue(plugin.addressesAreOnSameLan(makeAddress(10, 0, 0, 0),
|
||||
makeAddress(10, 255, 255, 255)));
|
||||
// Local and remote in 172.16.0.0/12 should return true
|
||||
assertTrue(plugin.addressesAreOnSameLan(makeAddress(172, 16, 0, 0),
|
||||
makeAddress(172, 31, 255, 255)));
|
||||
// Local and remote in 192.168.0.0/16 should return true
|
||||
assertTrue(plugin.addressesAreOnSameLan(makeAddress(192, 168, 0, 0),
|
||||
makeAddress(192, 168, 255, 255)));
|
||||
// Local and remote in 169.254.0.0/16 (link-local) should return true
|
||||
assertTrue(plugin.addressesAreOnSameLan(makeAddress(169, 254, 0, 0),
|
||||
makeAddress(169, 254, 255, 255)));
|
||||
// Local and remote in different recognised prefixes should return false
|
||||
assertFalse(plugin.addressesAreOnSameLan(makeAddress(10, 0, 0, 0),
|
||||
makeAddress(172, 31, 255, 255)));
|
||||
assertFalse(plugin.addressesAreOnSameLan(makeAddress(10, 0, 0, 0),
|
||||
makeAddress(192, 168, 255, 255)));
|
||||
assertFalse(plugin.addressesAreOnSameLan(makeAddress(172, 16, 0, 0),
|
||||
makeAddress(10, 255, 255, 255)));
|
||||
assertFalse(plugin.addressesAreOnSameLan(makeAddress(172, 16, 0, 0),
|
||||
makeAddress(192, 168, 255, 255)));
|
||||
assertFalse(plugin.addressesAreOnSameLan(makeAddress(192, 168, 0, 0),
|
||||
makeAddress(10, 255, 255, 255)));
|
||||
assertFalse(plugin.addressesAreOnSameLan(makeAddress(192, 168, 0, 0),
|
||||
makeAddress(172, 31, 255, 255)));
|
||||
// Remote prefix unrecognised should return false
|
||||
assertFalse(plugin.addressesAreOnSameLan(makeAddress(10, 0, 0, 0),
|
||||
makeAddress(1, 2, 3, 4)));
|
||||
assertFalse(plugin.addressesAreOnSameLan(makeAddress(172, 16, 0, 0),
|
||||
makeAddress(1, 2, 3, 4)));
|
||||
assertFalse(plugin.addressesAreOnSameLan(makeAddress(192, 168, 0, 0),
|
||||
makeAddress(1, 2, 3, 4)));
|
||||
// Both prefixes unrecognised should return true (could be link-local)
|
||||
assertTrue(plugin.addressesAreOnSameLan(makeAddress(1, 2, 3, 4),
|
||||
makeAddress(5, 6, 7, 8)));
|
||||
}
|
||||
|
||||
private byte[] makeAddress(int... parts) {
|
||||
@@ -124,7 +95,13 @@ public class LanTcpPluginTest extends BrambleTestCase {
|
||||
|
||||
@Test
|
||||
public void testIncomingConnection() throws Exception {
|
||||
assumeTrue(systemHasLocalIpv4Address());
|
||||
if (!systemHasLocalIpv4Address()) {
|
||||
System.err.println("WARNING: Skipping test, no local IPv4 address");
|
||||
return;
|
||||
}
|
||||
Callback callback = new Callback();
|
||||
DuplexPlugin plugin = new LanTcpPlugin(ioExecutor, backoff, callback,
|
||||
0, 0);
|
||||
plugin.start();
|
||||
// The plugin should have bound a socket and stored the port number
|
||||
assertTrue(callback.propertiesLatch.await(5, SECONDS));
|
||||
@@ -153,7 +130,13 @@ public class LanTcpPluginTest extends BrambleTestCase {
|
||||
|
||||
@Test
|
||||
public void testOutgoingConnection() throws Exception {
|
||||
assumeTrue(systemHasLocalIpv4Address());
|
||||
if (!systemHasLocalIpv4Address()) {
|
||||
System.err.println("WARNING: Skipping test, no local IPv4 address");
|
||||
return;
|
||||
}
|
||||
Callback callback = new Callback();
|
||||
DuplexPlugin plugin = new LanTcpPlugin(ioExecutor, backoff, callback,
|
||||
0, 0);
|
||||
plugin.start();
|
||||
// The plugin should have bound a socket and stored the port number
|
||||
assertTrue(callback.propertiesLatch.await(5, SECONDS));
|
||||
@@ -196,7 +179,13 @@ public class LanTcpPluginTest extends BrambleTestCase {
|
||||
|
||||
@Test
|
||||
public void testIncomingKeyAgreementConnection() throws Exception {
|
||||
assumeTrue(systemHasLocalIpv4Address());
|
||||
if (!systemHasLocalIpv4Address()) {
|
||||
System.err.println("WARNING: Skipping test, no local IPv4 address");
|
||||
return;
|
||||
}
|
||||
Callback callback = new Callback();
|
||||
DuplexPlugin plugin = new LanTcpPlugin(ioExecutor, backoff, callback,
|
||||
0, 0);
|
||||
plugin.start();
|
||||
assertTrue(callback.propertiesLatch.await(5, SECONDS));
|
||||
KeyAgreementListener kal =
|
||||
@@ -238,7 +227,13 @@ public class LanTcpPluginTest extends BrambleTestCase {
|
||||
|
||||
@Test
|
||||
public void testOutgoingKeyAgreementConnection() throws Exception {
|
||||
assumeTrue(systemHasLocalIpv4Address());
|
||||
if (!systemHasLocalIpv4Address()) {
|
||||
System.err.println("WARNING: Skipping test, no local IPv4 address");
|
||||
return;
|
||||
}
|
||||
Callback callback = new Callback();
|
||||
DuplexPlugin plugin = new LanTcpPlugin(ioExecutor, backoff, callback,
|
||||
0, 0);
|
||||
plugin.start();
|
||||
// The plugin should have bound a socket and stored the port number
|
||||
assertTrue(callback.propertiesLatch.await(5, SECONDS));
|
||||
@@ -283,12 +278,63 @@ public class LanTcpPluginTest extends BrambleTestCase {
|
||||
plugin.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testComparatorPrefersNonZeroPorts() {
|
||||
Comparator<InetSocketAddress> comparator = new LanAddressComparator();
|
||||
InetSocketAddress nonZero = new InetSocketAddress("1.2.3.4", 1234);
|
||||
InetSocketAddress zero = new InetSocketAddress("1.2.3.4", 0);
|
||||
|
||||
assertEquals(0, comparator.compare(nonZero, nonZero));
|
||||
assertTrue(comparator.compare(nonZero, zero) < 0);
|
||||
|
||||
assertTrue(comparator.compare(zero, nonZero) > 0);
|
||||
assertEquals(0, comparator.compare(zero, zero));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testComparatorPrefersLongerPrefixes() {
|
||||
Comparator<InetSocketAddress> comparator = new LanAddressComparator();
|
||||
InetSocketAddress prefix192 = new InetSocketAddress("192.168.0.1", 0);
|
||||
InetSocketAddress prefix172 = new InetSocketAddress("172.16.0.1", 0);
|
||||
InetSocketAddress prefix10 = new InetSocketAddress("10.0.0.1", 0);
|
||||
|
||||
assertEquals(0, comparator.compare(prefix192, prefix192));
|
||||
assertTrue(comparator.compare(prefix192, prefix172) < 0);
|
||||
assertTrue(comparator.compare(prefix192, prefix10) < 0);
|
||||
|
||||
assertTrue(comparator.compare(prefix172, prefix192) > 0);
|
||||
assertEquals(0, comparator.compare(prefix172, prefix172));
|
||||
assertTrue(comparator.compare(prefix172, prefix10) < 0);
|
||||
|
||||
assertTrue(comparator.compare(prefix10, prefix192) > 0);
|
||||
assertTrue(comparator.compare(prefix10, prefix172) > 0);
|
||||
assertEquals(0, comparator.compare(prefix10, prefix10));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testComparatorPrefersSiteLocalToLinkLocal() {
|
||||
Comparator<InetSocketAddress> comparator = new LanAddressComparator();
|
||||
InetSocketAddress prefix192 = new InetSocketAddress("192.168.0.1", 0);
|
||||
InetSocketAddress prefix172 = new InetSocketAddress("172.16.0.1", 0);
|
||||
InetSocketAddress prefix10 = new InetSocketAddress("10.0.0.1", 0);
|
||||
InetSocketAddress linkLocal = new InetSocketAddress("169.254.0.1", 0);
|
||||
|
||||
assertTrue(comparator.compare(prefix192, linkLocal) < 0);
|
||||
assertTrue(comparator.compare(prefix172, linkLocal) < 0);
|
||||
assertTrue(comparator.compare(prefix10, linkLocal) < 0);
|
||||
|
||||
assertTrue(comparator.compare(linkLocal, prefix192) > 0);
|
||||
assertTrue(comparator.compare(linkLocal, prefix172) > 0);
|
||||
assertTrue(comparator.compare(linkLocal, prefix10) > 0);
|
||||
assertEquals(0, comparator.compare(linkLocal, linkLocal));
|
||||
}
|
||||
|
||||
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
|
||||
private boolean systemHasLocalIpv4Address() throws Exception {
|
||||
for (NetworkInterface i : list(getNetworkInterfaces())) {
|
||||
for (InetAddress a : list(i.getInetAddresses())) {
|
||||
if (a instanceof Inet4Address) {
|
||||
if (a instanceof Inet4Address)
|
||||
return a.isLinkLocalAddress() || a.isSiteLocalAddress();
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
@@ -297,15 +343,18 @@ public class LanTcpPluginTest extends BrambleTestCase {
|
||||
@NotNullByDefault
|
||||
private static class Callback implements PluginCallback {
|
||||
|
||||
// Properties will be stored twice: the preferred port at startup,
|
||||
// and the IP:port when the server socket is bound
|
||||
private final CountDownLatch propertiesLatch = new CountDownLatch(2);
|
||||
private final CountDownLatch propertiesLatch = new CountDownLatch(1);
|
||||
private final CountDownLatch connectionsLatch = new CountDownLatch(1);
|
||||
private final TransportProperties local = new TransportProperties();
|
||||
private final Settings settings = new Settings();
|
||||
|
||||
private Callback() {
|
||||
settings.putBoolean(PREF_PLUGIN_ENABLE, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Settings getSettings() {
|
||||
return new Settings();
|
||||
return settings;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -324,11 +373,7 @@ public class LanTcpPluginTest extends BrambleTestCase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transportEnabled() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transportDisabled() {
|
||||
public void pluginStateChanged(State newState) {
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -24,18 +24,14 @@ import org.briarproject.bramble.test.DbExpectations;
|
||||
import org.jmock.Expectations;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.Collections.emptyMap;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static java.util.Collections.singletonMap;
|
||||
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.GROUP_KEY_DISCOVERED;
|
||||
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_VERSION;
|
||||
import static org.briarproject.bramble.api.properties.TransportPropertyManager.CLIENT_ID;
|
||||
import static org.briarproject.bramble.api.properties.TransportPropertyManager.MAJOR_VERSION;
|
||||
import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED;
|
||||
@@ -190,25 +186,25 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
Message message = getMessage(contactGroupId);
|
||||
Metadata meta = new Metadata();
|
||||
BdfDictionary metaDictionary = BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 2),
|
||||
new BdfEntry(MSG_KEY_LOCAL, false)
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 2),
|
||||
new BdfEntry("local", false)
|
||||
);
|
||||
Map<MessageId, BdfDictionary> messageMetadata =
|
||||
new LinkedHashMap<>();
|
||||
// A remote update for another transport should be ignored
|
||||
MessageId barUpdateId = new MessageId(getRandomId());
|
||||
messageMetadata.put(barUpdateId, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "bar"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||
new BdfEntry(MSG_KEY_LOCAL, false)
|
||||
new BdfEntry("transportId", "bar"),
|
||||
new BdfEntry("version", 1),
|
||||
new BdfEntry("local", false)
|
||||
));
|
||||
// A local update for the same transport should be ignored
|
||||
MessageId localUpdateId = new MessageId(getRandomId());
|
||||
messageMetadata.put(localUpdateId, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||
new BdfEntry(MSG_KEY_LOCAL, true)
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 1),
|
||||
new BdfEntry("local", true)
|
||||
));
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
@@ -232,18 +228,18 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
Metadata meta = new Metadata();
|
||||
// Version 4 is being delivered
|
||||
BdfDictionary metaDictionary = BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 4),
|
||||
new BdfEntry(MSG_KEY_LOCAL, false)
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 4),
|
||||
new BdfEntry("local", false)
|
||||
);
|
||||
Map<MessageId, BdfDictionary> messageMetadata =
|
||||
new LinkedHashMap<>();
|
||||
// An older remote update for the same transport should be deleted
|
||||
MessageId fooVersion3 = new MessageId(getRandomId());
|
||||
messageMetadata.put(fooVersion3, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 3),
|
||||
new BdfEntry(MSG_KEY_LOCAL, false)
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 3),
|
||||
new BdfEntry("local", false)
|
||||
));
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
@@ -269,18 +265,18 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
Metadata meta = new Metadata();
|
||||
// Version 3 is being delivered
|
||||
BdfDictionary metaDictionary = BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 3),
|
||||
new BdfEntry(MSG_KEY_LOCAL, false)
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 3),
|
||||
new BdfEntry("local", false)
|
||||
);
|
||||
Map<MessageId, BdfDictionary> messageMetadata =
|
||||
new LinkedHashMap<>();
|
||||
// A newer remote update for the same transport should not be deleted
|
||||
MessageId fooVersion4 = new MessageId(getRandomId());
|
||||
messageMetadata.put(fooVersion4, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 4),
|
||||
new BdfEntry(MSG_KEY_LOCAL, false)
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 4),
|
||||
new BdfEntry("local", false)
|
||||
));
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
@@ -346,9 +342,9 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
// A local update for another transport should be ignored
|
||||
MessageId barUpdateId = new MessageId(getRandomId());
|
||||
messageMetadata.put(barUpdateId, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "bar"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||
new BdfEntry(MSG_KEY_LOCAL, true)
|
||||
new BdfEntry("transportId", "bar"),
|
||||
new BdfEntry("version", 1),
|
||||
new BdfEntry("local", true)
|
||||
));
|
||||
|
||||
context.checking(new DbExpectations() {{
|
||||
@@ -370,16 +366,16 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
// A local update for another transport should be ignored
|
||||
MessageId barUpdateId = new MessageId(getRandomId());
|
||||
messageMetadata.put(barUpdateId, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "bar"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||
new BdfEntry(MSG_KEY_LOCAL, true)
|
||||
new BdfEntry("transportId", "bar"),
|
||||
new BdfEntry("version", 1),
|
||||
new BdfEntry("local", true)
|
||||
));
|
||||
// A local update for the right transport should be returned
|
||||
MessageId fooUpdateId = new MessageId(getRandomId());
|
||||
messageMetadata.put(fooUpdateId, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||
new BdfEntry(MSG_KEY_LOCAL, true)
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 1),
|
||||
new BdfEntry("local", true)
|
||||
));
|
||||
BdfList fooUpdate = BdfList.of("foo", 1, fooPropertiesDict);
|
||||
|
||||
@@ -409,28 +405,28 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
List<Contact> contacts = asList(contact1, contact2);
|
||||
Group contactGroup1 = getGroup(CLIENT_ID, MAJOR_VERSION);
|
||||
Group contactGroup2 = getGroup(CLIENT_ID, MAJOR_VERSION);
|
||||
Map<MessageId, BdfDictionary> messageMetadata =
|
||||
Map<MessageId, BdfDictionary> messageMetadata2 =
|
||||
new LinkedHashMap<>();
|
||||
// A remote update for another transport should be ignored
|
||||
MessageId barUpdateId = new MessageId(getRandomId());
|
||||
messageMetadata.put(barUpdateId, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "bar"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||
new BdfEntry(MSG_KEY_LOCAL, false)
|
||||
messageMetadata2.put(barUpdateId, BdfDictionary.of(
|
||||
new BdfEntry("transportId", "bar"),
|
||||
new BdfEntry("version", 1),
|
||||
new BdfEntry("local", false)
|
||||
));
|
||||
// A local update for the right transport should be ignored
|
||||
MessageId localUpdateId = new MessageId(getRandomId());
|
||||
messageMetadata.put(localUpdateId, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||
new BdfEntry(MSG_KEY_LOCAL, true)
|
||||
messageMetadata2.put(localUpdateId, BdfDictionary.of(
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 1),
|
||||
new BdfEntry("local", true)
|
||||
));
|
||||
// A remote update for the right transport should be returned
|
||||
MessageId fooUpdateId = new MessageId(getRandomId());
|
||||
messageMetadata.put(fooUpdateId, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||
new BdfEntry(MSG_KEY_LOCAL, false)
|
||||
messageMetadata2.put(fooUpdateId, BdfDictionary.of(
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 1),
|
||||
new BdfEntry("local", false)
|
||||
));
|
||||
BdfList fooUpdate = BdfList.of("foo", 1, fooPropertiesDict);
|
||||
|
||||
@@ -444,25 +440,19 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
will(returnValue(contactGroup1));
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup1.getId());
|
||||
will(returnValue(emptyMap()));
|
||||
oneOf(clientHelper).getGroupMetadataAsDictionary(txn,
|
||||
contactGroup1.getId());
|
||||
will(returnValue(new BdfDictionary()));
|
||||
will(returnValue(Collections.emptyMap()));
|
||||
// Second contact: returns an update
|
||||
oneOf(contactGroupFactory).createContactGroup(CLIENT_ID,
|
||||
MAJOR_VERSION, contact2);
|
||||
will(returnValue(contactGroup2));
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup2.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
will(returnValue(messageMetadata2));
|
||||
oneOf(clientHelper).getMessageAsList(txn, fooUpdateId);
|
||||
will(returnValue(fooUpdate));
|
||||
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||
fooPropertiesDict);
|
||||
will(returnValue(fooProperties));
|
||||
oneOf(clientHelper).getGroupMetadataAsDictionary(txn,
|
||||
contactGroup2.getId());
|
||||
will(returnValue(new BdfDictionary()));
|
||||
}});
|
||||
|
||||
TransportPropertyManagerImpl t = createInstance();
|
||||
@@ -473,62 +463,6 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
assertEquals(fooProperties, properties.get(contact2.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReceivePropertiesOverrideDiscoveredProperties()
|
||||
throws Exception {
|
||||
Transaction txn = new Transaction(null, true);
|
||||
Contact contact = getContact();
|
||||
List<Contact> contacts = singletonList(contact);
|
||||
Group contactGroup = getGroup(CLIENT_ID, MAJOR_VERSION);
|
||||
MessageId updateId = new MessageId(getRandomId());
|
||||
Map<MessageId, BdfDictionary> messageMetadata = singletonMap(updateId,
|
||||
BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||
new BdfEntry(MSG_KEY_LOCAL, false)
|
||||
));
|
||||
BdfList update = BdfList.of("foo", 1, fooPropertiesDict);
|
||||
TransportProperties discovered = new TransportProperties();
|
||||
discovered.put("fooKey1", "overridden");
|
||||
discovered.put("fooKey3", "fooValue3");
|
||||
BdfDictionary discoveredDict = new BdfDictionary(discovered);
|
||||
BdfDictionary groupMeta = BdfDictionary.of(
|
||||
new BdfEntry(GROUP_KEY_DISCOVERED, discoveredDict)
|
||||
);
|
||||
TransportProperties merged = new TransportProperties();
|
||||
merged.putAll(fooProperties);
|
||||
merged.put("fooKey3", "fooValue3");
|
||||
|
||||
context.checking(new DbExpectations() {{
|
||||
oneOf(db).transactionWithResult(with(true), withDbCallable(txn));
|
||||
oneOf(db).getContacts(txn);
|
||||
will(returnValue(contacts));
|
||||
// One update
|
||||
oneOf(contactGroupFactory).createContactGroup(CLIENT_ID,
|
||||
MAJOR_VERSION, contact);
|
||||
will(returnValue(contactGroup));
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
oneOf(clientHelper).getMessageAsList(txn, updateId);
|
||||
will(returnValue(update));
|
||||
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||
fooPropertiesDict);
|
||||
will(returnValue(fooProperties));
|
||||
oneOf(clientHelper).getGroupMetadataAsDictionary(txn,
|
||||
contactGroup.getId());
|
||||
will(returnValue(groupMeta));
|
||||
oneOf(clientHelper).parseAndValidateTransportProperties(
|
||||
discoveredDict);
|
||||
will(returnValue(discovered));
|
||||
}});
|
||||
|
||||
TransportPropertyManagerImpl t = createInstance();
|
||||
Map<ContactId, TransportProperties> properties =
|
||||
t.getRemoteProperties(new TransportId("foo"));
|
||||
assertEquals(merged, properties.get(contact.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMergingUnchangedPropertiesDoesNotCreateUpdate()
|
||||
throws Exception {
|
||||
@@ -536,9 +470,9 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
MessageId updateId = new MessageId(getRandomId());
|
||||
Map<MessageId, BdfDictionary> messageMetadata = singletonMap(updateId,
|
||||
BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||
new BdfEntry(MSG_KEY_LOCAL, true)
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 1),
|
||||
new BdfEntry("local", true)
|
||||
));
|
||||
BdfList update = BdfList.of("foo", 1, fooPropertiesDict);
|
||||
|
||||
@@ -571,7 +505,7 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
// There are no existing properties to merge with
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
localGroup.getId());
|
||||
will(returnValue(emptyMap()));
|
||||
will(returnValue(Collections.emptyMap()));
|
||||
// Store the new properties in the local group, version 1
|
||||
expectStoreMessage(txn, localGroup.getId(), "foo",
|
||||
fooPropertiesDict, 1, true, false);
|
||||
@@ -583,7 +517,7 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
will(returnValue(contactGroup));
|
||||
oneOf(clientHelper).getMessageMetadataAsDictionary(txn,
|
||||
contactGroup.getId());
|
||||
will(returnValue(emptyMap()));
|
||||
will(returnValue(Collections.emptyMap()));
|
||||
expectStoreMessage(txn, contactGroup.getId(), "foo",
|
||||
fooPropertiesDict, 1, true, true);
|
||||
}});
|
||||
@@ -598,9 +532,9 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
Contact contact = getContact();
|
||||
Group contactGroup = getGroup(CLIENT_ID, MAJOR_VERSION);
|
||||
BdfDictionary oldMetadata = BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 1),
|
||||
new BdfEntry(MSG_KEY_LOCAL, true)
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 1),
|
||||
new BdfEntry("local", true)
|
||||
);
|
||||
MessageId localGroupUpdateId = new MessageId(getRandomId());
|
||||
Map<MessageId, BdfDictionary> localGroupMessageMetadata =
|
||||
@@ -655,14 +589,14 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
// The latest update for transport "foo" should be returned
|
||||
MessageId fooVersion999 = new MessageId(getRandomId());
|
||||
messageMetadata.put(fooVersion999, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "foo"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 999)
|
||||
new BdfEntry("transportId", "foo"),
|
||||
new BdfEntry("version", 999)
|
||||
));
|
||||
// The latest update for transport "bar" should be returned
|
||||
MessageId barVersion3 = new MessageId(getRandomId());
|
||||
messageMetadata.put(barVersion3, BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, "bar"),
|
||||
new BdfEntry(MSG_KEY_VERSION, 3)
|
||||
new BdfEntry("transportId", "bar"),
|
||||
new BdfEntry("version", 3)
|
||||
));
|
||||
BdfList fooUpdate = BdfList.of("foo", 999, fooPropertiesDict);
|
||||
BdfList barUpdate = BdfList.of("bar", 3, barPropertiesDict);
|
||||
@@ -693,9 +627,9 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
|
||||
Message message = getMessage(g);
|
||||
long timestamp = message.getTimestamp();
|
||||
BdfDictionary meta = BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_TRANSPORT_ID, transportId),
|
||||
new BdfEntry(MSG_KEY_VERSION, version),
|
||||
new BdfEntry(MSG_KEY_LOCAL, local)
|
||||
new BdfEntry("transportId", transportId),
|
||||
new BdfEntry("version", version),
|
||||
new BdfEntry("local", local)
|
||||
);
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
|
||||
@@ -17,8 +17,8 @@ import org.briarproject.bramble.api.plugin.ConnectionManager;
|
||||
import org.briarproject.bramble.api.plugin.PluginManager;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportDisabledEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportActiveEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.TransportInactiveEvent;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
||||
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
||||
@@ -178,10 +178,10 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
rendezvousPoller.startService();
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Enable the transport - no endpoints should be created yet
|
||||
// Activate the transport - no endpoints should be created yet
|
||||
expectGetPlugin();
|
||||
|
||||
rendezvousPoller.eventOccurred(new TransportEnabledEvent(transportId));
|
||||
rendezvousPoller.eventOccurred(new TransportActiveEvent(transportId));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Add the pending contact - endpoint should be created and polled
|
||||
@@ -212,8 +212,8 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
new PendingContactRemovedEvent(pendingContact.getId()));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Disable the transport - endpoint is already closed
|
||||
rendezvousPoller.eventOccurred(new TransportDisabledEvent(transportId));
|
||||
// Deactivate the transport - endpoint is already closed
|
||||
rendezvousPoller.eventOccurred(new TransportInactiveEvent(transportId));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -230,10 +230,10 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
rendezvousPoller.startService();
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Enable the transport - no endpoints should be created yet
|
||||
// Activate the transport - no endpoints should be created yet
|
||||
expectGetPlugin();
|
||||
|
||||
rendezvousPoller.eventOccurred(new TransportEnabledEvent(transportId));
|
||||
rendezvousPoller.eventOccurred(new TransportActiveEvent(transportId));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Add the pending contact - endpoint should be created and polled
|
||||
@@ -269,12 +269,12 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
new PendingContactRemovedEvent(pendingContact.getId()));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Disable the transport - endpoint is already closed
|
||||
rendezvousPoller.eventOccurred(new TransportDisabledEvent(transportId));
|
||||
// Deactivate the transport - endpoint is already closed
|
||||
rendezvousPoller.eventOccurred(new TransportInactiveEvent(transportId));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreatesAndClosesEndpointsWhenTransportIsEnabledAndDisabled()
|
||||
public void testCreatesAndClosesEndpointsWhenTransportIsActivatedAndDeactivated()
|
||||
throws Exception {
|
||||
long beforeExpiry = pendingContact.getTimestamp();
|
||||
|
||||
@@ -292,19 +292,19 @@ public class RendezvousPollerImplTest extends BrambleMockTestCase {
|
||||
new PendingContactAddedEvent(pendingContact));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Enable the transport - endpoint should be created
|
||||
// Activate the transport - endpoint should be created
|
||||
expectGetPlugin();
|
||||
expectCreateEndpoint();
|
||||
expectStateChangedEvent(WAITING_FOR_CONNECTION);
|
||||
|
||||
rendezvousPoller.eventOccurred(new TransportEnabledEvent(transportId));
|
||||
rendezvousPoller.eventOccurred(new TransportActiveEvent(transportId));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Disable the transport - endpoint should be closed
|
||||
// Deactivate the transport - endpoint should be closed
|
||||
expectCloseEndpoint();
|
||||
expectStateChangedEvent(OFFLINE);
|
||||
|
||||
rendezvousPoller.eventOccurred(new TransportDisabledEvent(transportId));
|
||||
rendezvousPoller.eventOccurred(new TransportInactiveEvent(transportId));
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Remove the pending contact - endpoint is already closed
|
||||
|
||||
@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.db.DatabaseComponent;
|
||||
import org.briarproject.bramble.api.db.Transaction;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.sync.Ack;
|
||||
import org.briarproject.bramble.api.sync.GroupId;
|
||||
import org.briarproject.bramble.api.sync.Message;
|
||||
@@ -24,7 +23,6 @@ import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_IDS;
|
||||
import static org.briarproject.bramble.test.TestUtils.getContactId;
|
||||
import static org.briarproject.bramble.test.TestUtils.getMessage;
|
||||
import static org.briarproject.bramble.test.TestUtils.getRandomId;
|
||||
import static org.briarproject.bramble.test.TestUtils.getTransportId;
|
||||
|
||||
public class SimplexOutgoingSessionTest extends BrambleMockTestCase {
|
||||
|
||||
@@ -38,15 +36,14 @@ public class SimplexOutgoingSessionTest extends BrambleMockTestCase {
|
||||
|
||||
private final Executor dbExecutor = new ImmediateExecutor();
|
||||
private final ContactId contactId = getContactId();
|
||||
private final TransportId transportId = getTransportId();
|
||||
private final Message message = getMessage(new GroupId(getRandomId()));
|
||||
private final MessageId messageId = message.getId();
|
||||
|
||||
@Test
|
||||
public void testNothingToSend() throws Exception {
|
||||
SimplexOutgoingSession session = new SimplexOutgoingSession(db,
|
||||
dbExecutor, eventBus, contactId, transportId, MAX_LATENCY,
|
||||
streamWriter, recordWriter);
|
||||
dbExecutor, eventBus, contactId, MAX_LATENCY, streamWriter,
|
||||
recordWriter);
|
||||
Transaction noAckTxn = new Transaction(null, false);
|
||||
Transaction noMsgTxn = new Transaction(null, false);
|
||||
|
||||
@@ -79,8 +76,8 @@ public class SimplexOutgoingSessionTest extends BrambleMockTestCase {
|
||||
public void testSomethingToSend() throws Exception {
|
||||
Ack ack = new Ack(singletonList(messageId));
|
||||
SimplexOutgoingSession session = new SimplexOutgoingSession(db,
|
||||
dbExecutor, eventBus, contactId, transportId, MAX_LATENCY,
|
||||
streamWriter, recordWriter);
|
||||
dbExecutor, eventBus, contactId, MAX_LATENCY, streamWriter,
|
||||
recordWriter);
|
||||
Transaction ackTxn = new Transaction(null, false);
|
||||
Transaction noAckTxn = new Transaction(null, false);
|
||||
Transaction msgTxn = new Transaction(null, false);
|
||||
|
||||
@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -38,11 +37,6 @@ public class TestDuplexTransportConnection
|
||||
return writer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public TransportProperties getRemoteProperties() {
|
||||
return new TransportProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and returns a pair of TestDuplexTransportConnections that are
|
||||
* connected to each other.
|
||||
|
||||
@@ -16,7 +16,7 @@ dependencies {
|
||||
implementation fileTree(dir: 'libs', include: '*.jar')
|
||||
implementation 'net.java.dev.jna:jna:4.5.2'
|
||||
implementation 'net.java.dev.jna:jna-platform:4.5.2'
|
||||
tor 'org.briarproject:tor:0.3.5.10@zip'
|
||||
tor 'org.briarproject:tor:0.3.5.9@zip'
|
||||
tor 'org.briarproject:obfs4proxy:0.0.7@zip'
|
||||
|
||||
annotationProcessor 'com.google.dagger:dagger-compiler:2.24'
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package org.briarproject.bramble.plugin;
|
||||
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.lifecycle.ShutdownManager;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
@@ -10,7 +9,6 @@ import org.briarproject.bramble.api.plugin.PluginConfig;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||
import org.briarproject.bramble.api.plugin.simplex.SimplexPluginFactory;
|
||||
import org.briarproject.bramble.api.reliability.ReliabilityLayerFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.plugin.bluetooth.JavaBluetoothPluginFactory;
|
||||
import org.briarproject.bramble.plugin.modem.ModemPluginFactory;
|
||||
import org.briarproject.bramble.plugin.tcp.LanTcpPluginFactory;
|
||||
@@ -33,16 +31,15 @@ public class DesktopPluginModule extends PluginModule {
|
||||
PluginConfig getPluginConfig(@IoExecutor Executor ioExecutor,
|
||||
SecureRandom random, BackoffFactory backoffFactory,
|
||||
ReliabilityLayerFactory reliabilityFactory,
|
||||
ShutdownManager shutdownManager, EventBus eventBus, Clock clock,
|
||||
TimeoutMonitor timeoutMonitor) {
|
||||
DuplexPluginFactory bluetooth = new JavaBluetoothPluginFactory(
|
||||
ioExecutor, random, eventBus, clock, timeoutMonitor,
|
||||
backoffFactory);
|
||||
ShutdownManager shutdownManager, EventBus eventBus) {
|
||||
DuplexPluginFactory bluetooth =
|
||||
new JavaBluetoothPluginFactory(ioExecutor, random, eventBus,
|
||||
backoffFactory);
|
||||
DuplexPluginFactory modem = new ModemPluginFactory(ioExecutor,
|
||||
reliabilityFactory);
|
||||
DuplexPluginFactory lan = new LanTcpPluginFactory(ioExecutor,
|
||||
DuplexPluginFactory lan = new LanTcpPluginFactory(ioExecutor, eventBus,
|
||||
backoffFactory);
|
||||
DuplexPluginFactory wan = new WanTcpPluginFactory(ioExecutor,
|
||||
DuplexPluginFactory wan = new WanTcpPluginFactory(ioExecutor, eventBus,
|
||||
backoffFactory, shutdownManager);
|
||||
Collection<DuplexPluginFactory> duplex =
|
||||
asList(bluetooth, modem, lan, wan);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.briarproject.bramble.plugin.bluetooth;
|
||||
|
||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Backoff;
|
||||
@@ -35,11 +34,10 @@ class JavaBluetoothPlugin extends BluetoothPlugin<StreamConnectionNotifier> {
|
||||
private volatile LocalDevice localDevice = null;
|
||||
|
||||
JavaBluetoothPlugin(BluetoothConnectionLimiter connectionManager,
|
||||
TimeoutMonitor timeoutMonitor, Executor ioExecutor,
|
||||
SecureRandom secureRandom, Backoff backoff,
|
||||
PluginCallback callback, int maxLatency, int maxIdleTime) {
|
||||
super(connectionManager, timeoutMonitor, ioExecutor, secureRandom,
|
||||
backoff, callback, maxLatency, maxIdleTime);
|
||||
Executor ioExecutor, SecureRandom secureRandom,
|
||||
Backoff backoff, PluginCallback callback, int maxLatency) {
|
||||
super(connectionManager, ioExecutor, secureRandom, backoff, callback,
|
||||
maxLatency);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -121,9 +119,7 @@ class JavaBluetoothPlugin extends BluetoothPlugin<StreamConnectionNotifier> {
|
||||
return "btspp://" + address + ":" + uuid + ";name=RFCOMM";
|
||||
}
|
||||
|
||||
private DuplexTransportConnection wrapSocket(StreamConnection s)
|
||||
throws IOException {
|
||||
return new JavaBluetoothTransportConnection(this, connectionLimiter,
|
||||
timeoutMonitor, s);
|
||||
private DuplexTransportConnection wrapSocket(StreamConnection s) {
|
||||
return new JavaBluetoothTransportConnection(this, connectionLimiter, s);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package org.briarproject.bramble.plugin.bluetooth;
|
||||
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Backoff;
|
||||
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
||||
@@ -9,7 +8,6 @@ import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.concurrent.Executor;
|
||||
@@ -23,27 +21,22 @@ import static org.briarproject.bramble.api.plugin.BluetoothConstants.ID;
|
||||
public class JavaBluetoothPluginFactory implements DuplexPluginFactory {
|
||||
|
||||
private static final int MAX_LATENCY = 30 * 1000; // 30 seconds
|
||||
private static final int MAX_IDLE_TIME = 30 * 1000; // 30 seconds
|
||||
private static final int MIN_POLLING_INTERVAL = 60 * 1000; // 1 minute
|
||||
private static final int MAX_POLLING_INTERVAL = 10 * 60 * 1000; // 10 mins
|
||||
private static final double BACKOFF_BASE = 1.2;
|
||||
|
||||
private final Executor ioExecutor;
|
||||
private final SecureRandom secureRandom;
|
||||
private final EventBus eventBus;
|
||||
private final Clock clock;
|
||||
private final TimeoutMonitor timeoutMonitor;
|
||||
private final BackoffFactory backoffFactory;
|
||||
private final EventBus eventBus;
|
||||
|
||||
public JavaBluetoothPluginFactory(Executor ioExecutor,
|
||||
SecureRandom secureRandom, EventBus eventBus, Clock clock,
|
||||
TimeoutMonitor timeoutMonitor, BackoffFactory backoffFactory) {
|
||||
SecureRandom secureRandom, EventBus eventBus,
|
||||
BackoffFactory backoffFactory) {
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.secureRandom = secureRandom;
|
||||
this.eventBus = eventBus;
|
||||
this.clock = clock;
|
||||
this.timeoutMonitor = timeoutMonitor;
|
||||
this.backoffFactory = backoffFactory;
|
||||
this.eventBus = eventBus;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -59,12 +52,11 @@ public class JavaBluetoothPluginFactory implements DuplexPluginFactory {
|
||||
@Override
|
||||
public DuplexPlugin createPlugin(PluginCallback callback) {
|
||||
BluetoothConnectionLimiter connectionLimiter =
|
||||
new BluetoothConnectionLimiterImpl(eventBus, clock);
|
||||
new BluetoothConnectionLimiterImpl();
|
||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||
JavaBluetoothPlugin plugin = new JavaBluetoothPlugin(connectionLimiter,
|
||||
timeoutMonitor, ioExecutor, secureRandom, backoff, callback,
|
||||
MAX_LATENCY, MAX_IDLE_TIME);
|
||||
ioExecutor, secureRandom, backoff, callback, MAX_LATENCY);
|
||||
eventBus.addListener(plugin);
|
||||
return plugin;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.briarproject.bramble.plugin.bluetooth;
|
||||
|
||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Plugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.AbstractDuplexTransportConnection;
|
||||
@@ -15,24 +14,20 @@ import javax.microedition.io.StreamConnection;
|
||||
class JavaBluetoothTransportConnection
|
||||
extends AbstractDuplexTransportConnection {
|
||||
|
||||
private final BluetoothConnectionLimiter connectionLimiter;
|
||||
private final BluetoothConnectionLimiter connectionManager;
|
||||
private final StreamConnection stream;
|
||||
private final InputStream in;
|
||||
|
||||
JavaBluetoothTransportConnection(Plugin plugin,
|
||||
BluetoothConnectionLimiter connectionLimiter,
|
||||
TimeoutMonitor timeoutMonitor,
|
||||
StreamConnection stream) throws IOException {
|
||||
BluetoothConnectionLimiter connectionManager,
|
||||
StreamConnection stream) {
|
||||
super(plugin);
|
||||
this.connectionLimiter = connectionLimiter;
|
||||
this.stream = stream;
|
||||
in = timeoutMonitor.createTimeoutInputStream(
|
||||
stream.openInputStream(), plugin.getMaxIdleTime() * 2);
|
||||
this.connectionManager = connectionManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected InputStream getInputStream() {
|
||||
return in;
|
||||
protected InputStream getInputStream() throws IOException {
|
||||
return stream.openInputStream();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -45,7 +40,7 @@ class JavaBluetoothTransportConnection
|
||||
try {
|
||||
stream.close();
|
||||
} finally {
|
||||
connectionLimiter.connectionClosed(this, exception);
|
||||
connectionManager.connectionClosed(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import org.briarproject.bramble.api.Pair;
|
||||
import org.briarproject.bramble.api.data.BdfList;
|
||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
|
||||
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.plugin.ConnectionHandler;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
@@ -23,9 +24,16 @@ import java.util.Collection;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
|
||||
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.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.util.LogUtils.logException;
|
||||
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
|
||||
|
||||
@@ -44,8 +52,8 @@ class ModemPlugin implements DuplexPlugin, Modem.Callback {
|
||||
private final PluginCallback callback;
|
||||
private final int maxLatency;
|
||||
private final AtomicBoolean used = new AtomicBoolean(false);
|
||||
private final PluginState state = new PluginState();
|
||||
|
||||
private volatile boolean running = false;
|
||||
private volatile Modem modem = null;
|
||||
|
||||
ModemPlugin(ModemFactory modemFactory, SerialPortList serialPortList,
|
||||
@@ -75,6 +83,7 @@ class ModemPlugin implements DuplexPlugin, Modem.Callback {
|
||||
@Override
|
||||
public void start() throws PluginException {
|
||||
if (used.getAndSet(true)) throw new IllegalStateException();
|
||||
state.setStarted();
|
||||
for (String portName : serialPortList.getPortNames()) {
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Trying to initialise modem on " + portName);
|
||||
@@ -83,18 +92,20 @@ class ModemPlugin implements DuplexPlugin, Modem.Callback {
|
||||
if (!modem.start()) continue;
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Initialised modem on " + portName);
|
||||
running = true;
|
||||
state.setInitialised();
|
||||
return;
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
}
|
||||
LOG.warning("Failed to initialised modem");
|
||||
state.setFailed();
|
||||
throw new PluginException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
running = false;
|
||||
state.setStopped();
|
||||
if (modem != null) {
|
||||
try {
|
||||
modem.stop();
|
||||
@@ -105,8 +116,13 @@ class ModemPlugin implements DuplexPlugin, Modem.Callback {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRunning() {
|
||||
return running;
|
||||
public State getState() {
|
||||
return state.getState();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getReasonDisabled() {
|
||||
return getState() == DISABLED ? REASON_STARTING_STOPPING : -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -125,8 +141,8 @@ class ModemPlugin implements DuplexPlugin, Modem.Callback {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
private boolean resetModem() {
|
||||
if (!running) return false;
|
||||
private void resetModem() {
|
||||
if (getState() != ACTIVE) return;
|
||||
for (String portName : serialPortList.getPortNames()) {
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Trying to initialise modem on " + portName);
|
||||
@@ -135,18 +151,18 @@ class ModemPlugin implements DuplexPlugin, Modem.Callback {
|
||||
if (!modem.start()) continue;
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Initialised modem on " + portName);
|
||||
return true;
|
||||
return;
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
}
|
||||
running = false;
|
||||
return false;
|
||||
LOG.warning("Failed to initialise modem");
|
||||
state.setFailed();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DuplexTransportConnection createConnection(TransportProperties p) {
|
||||
if (!running) return null;
|
||||
if (getState() != ACTIVE) return null;
|
||||
// Get the ISO 3166 code for the caller's country
|
||||
String fromIso = callback.getLocalProperties().get("iso3166");
|
||||
if (isNullOrEmpty(fromIso)) return null;
|
||||
@@ -232,4 +248,41 @@ class ModemPlugin implements DuplexPlugin, Modem.Callback {
|
||||
if (exception) resetModem();
|
||||
}
|
||||
}
|
||||
|
||||
@ThreadSafe
|
||||
@NotNullByDefault
|
||||
private class PluginState {
|
||||
|
||||
@GuardedBy("this")
|
||||
private boolean started = false,
|
||||
stopped = false,
|
||||
initialised = false,
|
||||
failed = false;
|
||||
|
||||
private synchronized void setStarted() {
|
||||
started = true;
|
||||
callback.pluginStateChanged(getState());
|
||||
}
|
||||
|
||||
private synchronized void setStopped() {
|
||||
stopped = true;
|
||||
callback.pluginStateChanged(getState());
|
||||
}
|
||||
|
||||
private synchronized void setInitialised() {
|
||||
initialised = true;
|
||||
callback.pluginStateChanged(getState());
|
||||
}
|
||||
|
||||
private synchronized void setFailed() {
|
||||
failed = true;
|
||||
callback.pluginStateChanged(getState());
|
||||
}
|
||||
|
||||
private State getState() {
|
||||
if (!started || stopped) return DISABLED;
|
||||
if (failed) return INACTIVE;
|
||||
return initialised ? ACTIVE : ENABLING;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.ACTIVE;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.ENABLING;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
@@ -33,6 +35,7 @@ public class ModemPluginTest extends BrambleMockTestCase {
|
||||
@Test
|
||||
public void testModemCreation() throws Exception {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(callback).pluginStateChanged(ENABLING);
|
||||
oneOf(serialPortList).getPortNames();
|
||||
will(returnValue(new String[] {"foo", "bar", "baz"}));
|
||||
// First call to createModem() returns false
|
||||
@@ -50,6 +53,7 @@ public class ModemPluginTest extends BrambleMockTestCase {
|
||||
will(returnValue(modem));
|
||||
oneOf(modem).start();
|
||||
will(returnValue(true));
|
||||
oneOf(callback).pluginStateChanged(ACTIVE);
|
||||
}});
|
||||
|
||||
plugin.start();
|
||||
@@ -65,12 +69,14 @@ public class ModemPluginTest extends BrambleMockTestCase {
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
// start()
|
||||
oneOf(callback).pluginStateChanged(ENABLING);
|
||||
oneOf(serialPortList).getPortNames();
|
||||
will(returnValue(new String[] {"foo"}));
|
||||
oneOf(modemFactory).createModem(plugin, "foo");
|
||||
will(returnValue(modem));
|
||||
oneOf(modem).start();
|
||||
will(returnValue(true));
|
||||
oneOf(callback).pluginStateChanged(ACTIVE);
|
||||
// createConnection()
|
||||
oneOf(callback).getLocalProperties();
|
||||
will(returnValue(local));
|
||||
@@ -93,12 +99,14 @@ public class ModemPluginTest extends BrambleMockTestCase {
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
// start()
|
||||
oneOf(callback).pluginStateChanged(ENABLING);
|
||||
oneOf(serialPortList).getPortNames();
|
||||
will(returnValue(new String[] {"foo"}));
|
||||
oneOf(modemFactory).createModem(plugin, "foo");
|
||||
will(returnValue(modem));
|
||||
oneOf(modem).start();
|
||||
will(returnValue(true));
|
||||
oneOf(callback).pluginStateChanged(ACTIVE);
|
||||
// createConnection()
|
||||
oneOf(callback).getLocalProperties();
|
||||
will(returnValue(local));
|
||||
@@ -121,12 +129,14 @@ public class ModemPluginTest extends BrambleMockTestCase {
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
// start()
|
||||
oneOf(callback).pluginStateChanged(ENABLING);
|
||||
oneOf(serialPortList).getPortNames();
|
||||
will(returnValue(new String[] {"foo"}));
|
||||
oneOf(modemFactory).createModem(plugin, "foo");
|
||||
will(returnValue(modem));
|
||||
oneOf(modem).start();
|
||||
will(returnValue(true));
|
||||
oneOf(callback).pluginStateChanged(ACTIVE);
|
||||
// createConnection()
|
||||
oneOf(callback).getLocalProperties();
|
||||
will(returnValue(local));
|
||||
|
||||
@@ -32,6 +32,7 @@ import javax.net.SocketFactory;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static java.util.concurrent.TimeUnit.SECONDS;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.api.plugin.Plugin.State.ACTIVE;
|
||||
import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory;
|
||||
import static org.briarproject.bramble.test.TestUtils.getTestDirectory;
|
||||
import static org.briarproject.bramble.test.TestUtils.isOptionalTestEnabled;
|
||||
@@ -141,10 +142,10 @@ public class BridgeTest extends BrambleTestCase {
|
||||
plugin.start();
|
||||
long start = clock.currentTimeMillis();
|
||||
while (clock.currentTimeMillis() - start < TIMEOUT) {
|
||||
if (plugin.isRunning()) return;
|
||||
if (plugin.getState() == ACTIVE) return;
|
||||
clock.sleep(500);
|
||||
}
|
||||
if (!plugin.isRunning()) {
|
||||
if (plugin.getState() != ACTIVE) {
|
||||
fail("Could not connect to Tor within timeout.");
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.briarproject.bramble.plugin.tor;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Plugin.State;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
||||
@@ -30,11 +31,7 @@ public class TestPluginCallback implements PluginCallback {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transportEnabled() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transportDisabled() {
|
||||
public void pluginStateChanged(State state) {
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -24,7 +24,7 @@ dependencyVerification {
|
||||
'org.apache.ant:ant:1.9.4:ant-1.9.4.jar:649ae0730251de07b8913f49286d46bba7b92d47c5f332610aa426c4f02161d8',
|
||||
'org.beanshell:bsh:1.3.0:bsh-1.3.0.jar:9b04edc75d19db54f1b4e8b5355e9364384c6cf71eb0a1b9724c159d779879f8',
|
||||
'org.briarproject:obfs4proxy:0.0.7:obfs4proxy-0.0.7.zip:5b2f693262ce43a7e130f7cc7d5d1617925330640a2eb6d71085e95df8ee0642',
|
||||
'org.briarproject:tor:0.3.5.10:tor-0.3.5.10.zip:7b387d3523ae8af289c23be59dc4c64ec5d3721385d7825a09705095e3318d5c',
|
||||
'org.briarproject:tor:0.3.5.9:tor-0.3.5.9.zip:6c3994b129db019cc23caaf50d6b4383903c40d05fbc47fc94211170a3e5d38c',
|
||||
'org.checkerframework:checker-compat-qual:2.5.3:checker-compat-qual-2.5.3.jar:d76b9afea61c7c082908023f0cbc1427fab9abd2df915c8b8a3e7a509bccbc6d',
|
||||
'org.checkerframework:checker-qual:2.5.2:checker-qual-2.5.2.jar:64b02691c8b9d4e7700f8ee2e742dce7ea2c6e81e662b7522c9ee3bf568c040a',
|
||||
'org.codehaus.mojo:animal-sniffer-annotations:1.17:animal-sniffer-annotations-1.17.jar:92654f493ecfec52082e76354f0ebf87648dc3d5cec2e3c3cdb947c016747a53',
|
||||
|
||||
85
briar-android/artwork/transport_tor.svg
Normal file
85
briar-android/artwork/transport_tor.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 11 KiB |
117
briar-android/artwork/transports_list_scene.xml
Normal file
117
briar-android/artwork/transports_list_scene.xml
Normal file
@@ -0,0 +1,117 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto">
|
||||
|
||||
<Transition
|
||||
app:constraintSetEnd="@+id/end"
|
||||
app:constraintSetStart="@id/start"
|
||||
app:duration="1000">
|
||||
<OnClick app:targetId="@+id/chevronView" />
|
||||
</Transition>
|
||||
|
||||
<ConstraintSet android:id="@+id/start">
|
||||
<Constraint
|
||||
android:id="@+id/chevronView"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="24dp"
|
||||
android:layout_marginBottom="8dp"
|
||||
app:layout_constraintBottom_toTopOf="@+id/longRangeLabel"
|
||||
app:layout_constraintEnd_toEndOf="parent"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toBottomOf="@+id/navigation"
|
||||
app:layout_constraintVertical_bias="1.0">
|
||||
<CustomAttribute
|
||||
app:attributeName="crossfade"
|
||||
app:customFloatValue="0" />
|
||||
</Constraint>
|
||||
</ConstraintSet>
|
||||
|
||||
<ConstraintSet android:id="@+id/end">
|
||||
<Constraint
|
||||
android:id="@+id/chevronView"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="24dp"
|
||||
android:layout_marginBottom="8dp"
|
||||
app:layout_constraintBottom_toTopOf="@+id/connectionsLabel"
|
||||
app:layout_constraintEnd_toEndOf="parent"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintVertical_bias="1.0">
|
||||
<CustomAttribute
|
||||
app:attributeName="crossfade"
|
||||
app:customFloatValue="1" />
|
||||
</Constraint>
|
||||
<Constraint
|
||||
android:id="@+id/backgroundView"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="0dp"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintEnd_toEndOf="parent"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toBottomOf="@+id/chevronView" />
|
||||
<Constraint
|
||||
android:id="@+id/torSwitch"
|
||||
android:visibility="gone"
|
||||
app:layout_constraintBottom_toTopOf="@id/nearbyLabel"
|
||||
app:layout_constraintStart_toEndOf="parent" />
|
||||
<Constraint
|
||||
android:id="@+id/wifiSwitch"
|
||||
android:visibility="gone"
|
||||
app:layout_constraintBottom_toTopOf="@+id/btSwitch"
|
||||
app:layout_constraintStart_toEndOf="parent" />
|
||||
<Constraint
|
||||
android:id="@+id/btSwitch"
|
||||
android:visibility="gone"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintStart_toEndOf="parent" />
|
||||
<Constraint
|
||||
android:id="@+id/longRangeLabel"
|
||||
android:visibility="gone"
|
||||
app:layout_constraintBottom_toTopOf="@+id/torSwitch"
|
||||
app:layout_constraintStart_toEndOf="parent" />
|
||||
<Constraint
|
||||
android:id="@+id/nearbyLabel"
|
||||
android:visibility="gone"
|
||||
app:layout_constraintBottom_toTopOf="@+id/wifiSwitch"
|
||||
app:layout_constraintStart_toEndOf="parent" />
|
||||
<Constraint
|
||||
android:id="@+id/torIcon"
|
||||
android:layout_width="20dp"
|
||||
android:layout_height="20dp"
|
||||
android:layout_marginEnd="8dp"
|
||||
android:layout_marginRight="8dp"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintEnd_toStartOf="@+id/wifiIcon"
|
||||
app:layout_constraintTop_toBottomOf="@+id/chevronView" />
|
||||
<Constraint
|
||||
android:id="@+id/wifiIcon"
|
||||
android:layout_width="20dp"
|
||||
android:layout_height="20dp"
|
||||
android:layout_marginEnd="8dp"
|
||||
android:layout_marginRight="8dp"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintEnd_toStartOf="@+id/btIcon"
|
||||
app:layout_constraintTop_toBottomOf="@+id/chevronView" />
|
||||
<Constraint
|
||||
android:id="@+id/btIcon"
|
||||
android:layout_width="20dp"
|
||||
android:layout_height="20dp"
|
||||
android:layout_marginTop="8dp"
|
||||
android:layout_marginEnd="8dp"
|
||||
android:layout_marginRight="8dp"
|
||||
android:layout_marginBottom="8dp"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintEnd_toEndOf="parent"
|
||||
app:layout_constraintTop_toBottomOf="@+id/chevronView" />
|
||||
<Constraint
|
||||
android:id="@+id/connectionsLabel"
|
||||
android:layout_marginStart="8dp"
|
||||
android:layout_marginLeft="8dp"
|
||||
android:layout_marginEnd="8dp"
|
||||
android:layout_marginRight="8dp"
|
||||
android:visibility="visible"
|
||||
app:layout_constraintBottom_toBottomOf="@+id/torIcon"
|
||||
app:layout_constraintEnd_toStartOf="@+id/torIcon"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toTopOf="@+id/torIcon" />
|
||||
</ConstraintSet>
|
||||
</MotionScene>
|
||||
@@ -22,8 +22,8 @@ android {
|
||||
defaultConfig {
|
||||
minSdkVersion 16
|
||||
targetSdkVersion 28
|
||||
versionCode 10207
|
||||
versionName "1.2.7"
|
||||
versionCode 10205
|
||||
versionName "1.2.5"
|
||||
applicationId "org.briarproject.briar.android"
|
||||
buildConfigField "String", "GitHash",
|
||||
"\"${getStdout(['git', 'rev-parse', '--short=7', 'HEAD'], 'No commit hash')}\""
|
||||
@@ -98,7 +98,7 @@ dependencies {
|
||||
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
|
||||
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
|
||||
implementation 'com.google.android.material:material:1.1.0-beta01'
|
||||
implementation 'androidx.recyclerview:recyclerview-selection:1.1.0-rc01'
|
||||
implementation 'androidx.recyclerview:recyclerview-selection:1.0.0'
|
||||
|
||||
implementation 'ch.acra:acra:4.11'
|
||||
implementation 'info.guardianproject.panic:panic:1.0'
|
||||
|
||||
@@ -28,9 +28,7 @@ import static android.security.keystore.KeyProperties.PURPOSE_SIGN;
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.Collections.singletonList;
|
||||
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.util.LogUtils.logException;
|
||||
|
||||
@RequiresApi(23)
|
||||
@NotNullByDefault
|
||||
@@ -81,10 +79,7 @@ class AndroidKeyStrengthener implements KeyStrengthener {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (GeneralSecurityException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
return false;
|
||||
} catch (IOException e) {
|
||||
} catch (GeneralSecurityException | IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ import org.briarproject.bramble.api.crypto.KeyStrengthener;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.io.TimeoutMonitor;
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
|
||||
import org.briarproject.bramble.api.network.NetworkManager;
|
||||
@@ -37,7 +36,7 @@ import org.briarproject.bramble.util.AndroidUtils;
|
||||
import org.briarproject.bramble.util.StringUtils;
|
||||
import org.briarproject.briar.android.account.LockManagerImpl;
|
||||
import org.briarproject.briar.android.keyagreement.ContactExchangeModule;
|
||||
import org.briarproject.briar.android.login.LoginModule;
|
||||
import org.briarproject.briar.android.navdrawer.NavDrawerModule;
|
||||
import org.briarproject.briar.android.viewmodel.ViewModelModule;
|
||||
import org.briarproject.briar.api.android.AndroidNotificationManager;
|
||||
import org.briarproject.briar.api.android.DozeWatchdog;
|
||||
@@ -67,8 +66,8 @@ import static org.briarproject.bramble.api.reporting.ReportingConstants.DEV_PUBL
|
||||
import static org.briarproject.briar.android.TestingConstants.IS_DEBUG_BUILD;
|
||||
|
||||
@Module(includes = {
|
||||
NavDrawerModule.class,
|
||||
ContactExchangeModule.class,
|
||||
LoginModule.class,
|
||||
ViewModelModule.class
|
||||
})
|
||||
public class AppModule {
|
||||
@@ -123,12 +122,11 @@ public class AppModule {
|
||||
LocationUtils locationUtils, EventBus eventBus,
|
||||
ResourceProvider resourceProvider,
|
||||
CircumventionProvider circumventionProvider,
|
||||
BatteryManager batteryManager, Clock clock,
|
||||
TimeoutMonitor timeoutMonitor) {
|
||||
BatteryManager batteryManager, Clock clock) {
|
||||
Context appContext = app.getApplicationContext();
|
||||
DuplexPluginFactory bluetooth = new AndroidBluetoothPluginFactory(
|
||||
ioExecutor, androidExecutor, appContext, random, eventBus,
|
||||
clock, timeoutMonitor, backoffFactory);
|
||||
DuplexPluginFactory bluetooth =
|
||||
new AndroidBluetoothPluginFactory(ioExecutor, androidExecutor,
|
||||
appContext, random, eventBus, clock, backoffFactory);
|
||||
DuplexPluginFactory tor = new AndroidTorPluginFactory(ioExecutor,
|
||||
scheduler, appContext, networkManager, locationUtils, eventBus,
|
||||
torSocketFactory, backoffFactory, resourceProvider,
|
||||
|
||||
@@ -8,8 +8,8 @@ import org.briarproject.briar.android.controller.BriarController;
|
||||
import org.briarproject.briar.android.controller.BriarControllerImpl;
|
||||
import org.briarproject.briar.android.controller.DbController;
|
||||
import org.briarproject.briar.android.controller.DbControllerImpl;
|
||||
import org.briarproject.briar.android.navdrawer.NavDrawerController;
|
||||
import org.briarproject.briar.android.navdrawer.NavDrawerControllerImpl;
|
||||
import org.briarproject.briar.android.login.ChangePasswordController;
|
||||
import org.briarproject.briar.android.login.ChangePasswordControllerImpl;
|
||||
|
||||
import dagger.Module;
|
||||
import dagger.Provides;
|
||||
@@ -44,6 +44,13 @@ public class ActivityModule {
|
||||
return setupController;
|
||||
}
|
||||
|
||||
@ActivityScope
|
||||
@Provides
|
||||
ChangePasswordController providePasswordController(
|
||||
ChangePasswordControllerImpl passwordController) {
|
||||
return passwordController;
|
||||
}
|
||||
|
||||
@ActivityScope
|
||||
@Provides
|
||||
protected BriarController provideBriarController(
|
||||
@@ -58,17 +65,10 @@ public class ActivityModule {
|
||||
return dbController;
|
||||
}
|
||||
|
||||
@ActivityScope
|
||||
@Provides
|
||||
NavDrawerController provideNavDrawerController(
|
||||
NavDrawerControllerImpl navDrawerController) {
|
||||
activity.addLifecycleController(navDrawerController);
|
||||
return navDrawerController;
|
||||
}
|
||||
|
||||
@ActivityScope
|
||||
@Provides
|
||||
BriarServiceConnection provideBriarServiceConnection() {
|
||||
return new BriarServiceConnection();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -92,9 +92,6 @@ public abstract class BaseActivity extends AppCompatActivity
|
||||
.build();
|
||||
injectActivity(activityComponent);
|
||||
super.onCreate(state);
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Creating " + getClass().getSimpleName());
|
||||
}
|
||||
|
||||
// WARNING: When removing this or making it possible to turn it off,
|
||||
// we need a solution for the app lock feature.
|
||||
@@ -130,9 +127,8 @@ public abstract class BaseActivity extends AppCompatActivity
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Starting " + getClass().getSimpleName());
|
||||
}
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Starting " + this.getClass().getSimpleName());
|
||||
for (ActivityLifecycleController alc : lifecycleControllers) {
|
||||
alc.onActivityStart();
|
||||
}
|
||||
@@ -148,28 +144,11 @@ public abstract class BaseActivity extends AppCompatActivity
|
||||
return (ScreenFilterDialogFragment) f;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onResume() {
|
||||
super.onResume();
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Resuming " + getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPause() {
|
||||
super.onPause();
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Pausing " + getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
super.onStop();
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Stopping " + getClass().getSimpleName());
|
||||
}
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info("Stopping " + this.getClass().getSimpleName());
|
||||
for (ActivityLifecycleController alc : lifecycleControllers) {
|
||||
alc.onActivityStop();
|
||||
}
|
||||
@@ -224,9 +203,6 @@ public abstract class BaseActivity extends AppCompatActivity
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Destroying " + getClass().getSimpleName());
|
||||
}
|
||||
destroyed = true;
|
||||
for (ActivityLifecycleController alc : lifecycleControllers) {
|
||||
alc.onActivityDestroy();
|
||||
|
||||
@@ -95,14 +95,12 @@ public abstract class BriarActivity extends BaseActivity {
|
||||
// Also check that the activity isn't finishing already.
|
||||
// This is possible if we finished in onActivityResult().
|
||||
// Launching another StartupActivity would cause a loop.
|
||||
LOG.info("Not signed in, launching StartupActivity");
|
||||
Intent i = new Intent(this, StartupActivity.class);
|
||||
startActivityForResult(i, REQUEST_PASSWORD);
|
||||
} else if (lockManager.isLocked() && !isFinishing()) {
|
||||
// Also check that the activity isn't finishing already.
|
||||
// This is possible if we finished in onActivityResult().
|
||||
// Launching another UnlockActivity would cause a loop.
|
||||
LOG.info("Locked, launching UnlockActivity");
|
||||
Intent i = new Intent(this, UnlockActivity.class);
|
||||
startActivityForResult(i, REQUEST_UNLOCK);
|
||||
} else if (SDK_INT >= 23) {
|
||||
|
||||
@@ -9,6 +9,7 @@ import org.briarproject.briar.android.controller.handler.ResultExceptionHandler;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.UiThread;
|
||||
|
||||
@NotNullByDefault
|
||||
@@ -17,10 +18,7 @@ public interface BlogController extends BaseController {
|
||||
void setGroupId(GroupId g);
|
||||
|
||||
@UiThread
|
||||
void setBlogSharingListener(BlogSharingListener listener);
|
||||
|
||||
@UiThread
|
||||
void unsetBlogSharingListener(BlogSharingListener listener);
|
||||
void setBlogSharingListener(@Nullable BlogSharingListener listener);
|
||||
|
||||
void loadBlogPosts(
|
||||
ResultExceptionHandler<Collection<BlogPostItem>, DbException> handler);
|
||||
|
||||
@@ -96,15 +96,10 @@ class BlogControllerImpl extends BaseControllerImpl
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBlogSharingListener(BlogSharingListener listener) {
|
||||
public void setBlogSharingListener(@Nullable BlogSharingListener listener) {
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsetBlogSharingListener(BlogSharingListener listener) {
|
||||
if (this.listener == listener) this.listener = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (groupId == null || listener == null)
|
||||
|
||||
@@ -141,8 +141,7 @@ public class BlogFragment extends BaseFragment
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
super.onDestroy();
|
||||
blogController.unsetBlogSharingListener(this);
|
||||
sharingController.unsetSharingListener(this);
|
||||
blogController.setBlogSharingListener(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -7,6 +7,7 @@ import org.briarproject.briar.api.blog.Blog;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.annotation.UiThread;
|
||||
|
||||
@NotNullByDefault
|
||||
@@ -18,10 +19,7 @@ public interface FeedController extends BaseController {
|
||||
void loadPersonalBlog(ResultExceptionHandler<Blog, DbException> handler);
|
||||
|
||||
@UiThread
|
||||
void setFeedListener(FeedListener listener);
|
||||
|
||||
@UiThread
|
||||
void unsetFeedListener(FeedListener listener);
|
||||
void setFeedListener(@Nullable FeedListener listener);
|
||||
|
||||
@NotNullByDefault
|
||||
interface FeedListener extends BlogListener {
|
||||
|
||||
@@ -69,15 +69,10 @@ class FeedControllerImpl extends BaseControllerImpl implements FeedController {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFeedListener(FeedListener listener) {
|
||||
public void setFeedListener(@Nullable FeedListener listener) {
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsetFeedListener(FeedListener listener) {
|
||||
if (this.listener == listener) this.listener = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (listener == null) throw new IllegalStateException();
|
||||
|
||||
@@ -134,7 +134,7 @@ public class FeedFragment extends BaseFragment implements
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
super.onDestroy();
|
||||
feedController.unsetFeedListener(this);
|
||||
feedController.setFeedListener(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -61,7 +61,7 @@ import io.github.kobakei.materialfabspeeddial.FabSpeedDial.OnMenuItemClickListen
|
||||
import static android.os.Build.VERSION.SDK_INT;
|
||||
import static androidx.core.app.ActivityOptionsCompat.makeSceneTransitionAnimation;
|
||||
import static androidx.core.view.ViewCompat.getTransitionName;
|
||||
import static com.google.android.material.snackbar.BaseTransientBottomBar.LENGTH_INDEFINITE;
|
||||
import static com.google.android.material.snackbar.Snackbar.LENGTH_INDEFINITE;
|
||||
import static java.util.Objects.requireNonNull;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static org.briarproject.bramble.util.LogUtils.logDuration;
|
||||
@@ -87,12 +87,7 @@ public class ContactListFragment extends BaseFragment implements EventListener,
|
||||
|
||||
private ContactListAdapter adapter;
|
||||
private BriarRecyclerView list;
|
||||
/**
|
||||
* The Snackbar is non-null when shown and null otherwise.
|
||||
* Use {@link #showSnackBar()} and {@link #dismissSnackBar()} to interact.
|
||||
*/
|
||||
@Nullable
|
||||
private Snackbar snackbar = null;
|
||||
private Snackbar snackbar;
|
||||
|
||||
// Fields that are accessed from background threads must be volatile
|
||||
@Inject
|
||||
@@ -168,6 +163,13 @@ public class ContactListFragment extends BaseFragment implements EventListener,
|
||||
list.setEmptyText(getString(R.string.no_contacts));
|
||||
list.setEmptyAction(getString(R.string.no_contacts_action));
|
||||
|
||||
snackbar = new BriarSnackbarBuilder()
|
||||
.setAction(R.string.show, v ->
|
||||
startActivity(new Intent(getContext(),
|
||||
PendingContactListActivity.class)))
|
||||
.make(contentView, R.string.pending_contact_requests_snackbar,
|
||||
LENGTH_INDEFINITE);
|
||||
|
||||
return contentView;
|
||||
}
|
||||
|
||||
@@ -201,9 +203,9 @@ public class ContactListFragment extends BaseFragment implements EventListener,
|
||||
listener.runOnDbThread(() -> {
|
||||
try {
|
||||
if (contactManager.getPendingContacts().isEmpty()) {
|
||||
runOnUiThreadUnlessDestroyed(this::dismissSnackBar);
|
||||
runOnUiThreadUnlessDestroyed(() -> snackbar.dismiss());
|
||||
} else {
|
||||
runOnUiThreadUnlessDestroyed(this::showSnackBar);
|
||||
runOnUiThreadUnlessDestroyed(() -> snackbar.show());
|
||||
}
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
@@ -218,7 +220,6 @@ public class ContactListFragment extends BaseFragment implements EventListener,
|
||||
adapter.clear();
|
||||
list.showProgressBar();
|
||||
list.stopPeriodicUpdate();
|
||||
dismissSnackBar();
|
||||
}
|
||||
|
||||
private void loadContacts() {
|
||||
@@ -314,27 +315,4 @@ public class ContactListFragment extends BaseFragment implements EventListener,
|
||||
}
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void showSnackBar() {
|
||||
if (snackbar != null) return;
|
||||
View v = requireNonNull(getView());
|
||||
int stringRes = R.string.pending_contact_requests_snackbar;
|
||||
snackbar = new BriarSnackbarBuilder()
|
||||
.setAction(R.string.show, view -> showPendingContactList())
|
||||
.make(v, stringRes, LENGTH_INDEFINITE);
|
||||
snackbar.show();
|
||||
}
|
||||
|
||||
@UiThread
|
||||
private void dismissSnackBar() {
|
||||
if (snackbar == null) return;
|
||||
snackbar.dismiss();
|
||||
snackbar = null;
|
||||
}
|
||||
|
||||
private void showPendingContactList() {
|
||||
Intent i = new Intent(getContext(), PendingContactListActivity.class);
|
||||
startActivity(i);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ public class PendingContactListViewModel extends AndroidViewModel
|
||||
Collection<Pair<PendingContact, PendingContactState>> pairs =
|
||||
contactManager.getPendingContacts();
|
||||
List<PendingContactItem> items = new ArrayList<>(pairs.size());
|
||||
boolean online = pairs.isEmpty();
|
||||
boolean online = items.isEmpty();
|
||||
for (Pair<PendingContact, PendingContactState> pair : pairs) {
|
||||
PendingContact p = pair.getFirst();
|
||||
PendingContactState state = pair.getSecond();
|
||||
|
||||
@@ -54,6 +54,8 @@ class PendingContactViewHolder extends ViewHolder {
|
||||
status.setText(R.string.waiting_for_contact_to_come_online);
|
||||
break;
|
||||
case OFFLINE:
|
||||
color = ContextCompat
|
||||
.getColor(status.getContext(), R.color.briar_yellow);
|
||||
status.setText("");
|
||||
break;
|
||||
case CONNECTING:
|
||||
|
||||
@@ -16,12 +16,6 @@ public interface SharingController {
|
||||
@UiThread
|
||||
void setSharingListener(SharingListener listener);
|
||||
|
||||
/**
|
||||
* Unsets the listener.
|
||||
*/
|
||||
@UiThread
|
||||
void unsetSharingListener(SharingListener listener);
|
||||
|
||||
/**
|
||||
* Call this when your lifecycle starts,
|
||||
* so the listener will be called when information changes.
|
||||
|
||||
@@ -43,11 +43,6 @@ public class SharingControllerImpl implements SharingController, EventListener {
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsetSharingListener(SharingListener listener) {
|
||||
if (this.listener == listener) this.listener = null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
eventBus.addListener(this);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user