mirror of
https://code.briarproject.org/briar/briar.git
synced 2026-02-12 02:39:05 +01:00
Compare commits
234 Commits
beta-1.1.7
...
remote-con
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1502e6fab | ||
|
|
d145a082f5 | ||
|
|
4fd012c31a | ||
|
|
95d06770bf | ||
|
|
428247b7b2 | ||
|
|
a921361a56 | ||
|
|
fe7dfa721e | ||
|
|
92eb06a9e9 | ||
|
|
5beed1a748 | ||
|
|
774047d856 | ||
|
|
fc28e7aa88 | ||
|
|
78459499b2 | ||
|
|
c2973608d7 | ||
|
|
be1c33cb42 | ||
|
|
c955466bda | ||
|
|
593a0c4632 | ||
|
|
ed20b2d8d6 | ||
|
|
34583e6d2d | ||
|
|
ea5a862242 | ||
|
|
9ab9e02f8a | ||
|
|
3f70ae3c8c | ||
|
|
3f60098099 | ||
|
|
e965021e3d | ||
|
|
7d9380d3d6 | ||
|
|
3c8c0e579e | ||
|
|
bd2bbe9268 | ||
|
|
89d24b1753 | ||
|
|
861dbe20b1 | ||
|
|
197800de8b | ||
|
|
07e824ad68 | ||
|
|
d210215bd1 | ||
|
|
00705447ec | ||
|
|
9095ccef85 | ||
|
|
3196204094 | ||
|
|
2bae639105 | ||
|
|
f73d298752 | ||
|
|
bc3a443276 | ||
|
|
2a29d33303 | ||
|
|
30e0be9f43 | ||
|
|
3828d16971 | ||
|
|
a54eb64eb5 | ||
|
|
ad2d3e70d6 | ||
|
|
1f91842c52 | ||
|
|
c07a0a2fd7 | ||
|
|
4ee4905e06 | ||
|
|
67b7517f2b | ||
|
|
cd3174a643 | ||
|
|
9d9bc4ca84 | ||
|
|
7358091699 | ||
|
|
11eefaedcf | ||
|
|
bb5a6c0241 | ||
|
|
70d29af2ba | ||
|
|
baedb14e2b | ||
|
|
2796926709 | ||
|
|
fc6275b037 | ||
|
|
f76f9be4ed | ||
|
|
6167ba5c46 | ||
|
|
55f4600a69 | ||
|
|
c73801c7e8 | ||
|
|
249e1e28fe | ||
|
|
f0cea28aeb | ||
|
|
32e8ea9888 | ||
|
|
5a1caed89f | ||
|
|
22f5c42fc1 | ||
|
|
aab46040a5 | ||
|
|
18fd238aa1 | ||
|
|
3a837b3c5a | ||
|
|
ac2597865c | ||
|
|
4a67cf3ce7 | ||
|
|
a5041e651e | ||
|
|
b0e97d787f | ||
|
|
0d8af780a3 | ||
|
|
9c20e6b333 | ||
|
|
ab14976c96 | ||
|
|
ec3f821ba6 | ||
|
|
1d546da781 | ||
|
|
f2c951b70b | ||
|
|
1e259c100d | ||
|
|
3636aeba9a | ||
|
|
132e20a6ce | ||
|
|
c228e5c219 | ||
|
|
ae1d1fc5a7 | ||
|
|
37f02a40e9 | ||
|
|
3c8b8c39e1 | ||
|
|
8f839e2c30 | ||
|
|
da4b63f20f | ||
|
|
cd40e771d2 | ||
|
|
dd7accfa95 | ||
|
|
1cf993484d | ||
|
|
e810785fe2 | ||
|
|
7ec826ccb7 | ||
|
|
4a4abd7efa | ||
|
|
dc2e42e1f2 | ||
|
|
1c4d277771 | ||
|
|
fb10ba5855 | ||
|
|
f31b85acdb | ||
|
|
6519706599 | ||
|
|
76741bc2ba | ||
|
|
60eefbf3e0 | ||
|
|
a4a45efd43 | ||
|
|
208ae6a4b6 | ||
|
|
fe1df6dafa | ||
|
|
15d9ff1ebd | ||
|
|
dc741e988c | ||
|
|
6665235768 | ||
|
|
ba19716e0f | ||
|
|
41deff1bf3 | ||
|
|
1ec3fa3ade | ||
|
|
64ae99bbce | ||
|
|
ed1cefa144 | ||
|
|
23354d6568 | ||
|
|
1aa579a44f | ||
|
|
98191fb059 | ||
|
|
b9283ea654 | ||
|
|
71b1f99b56 | ||
|
|
2982a874d4 | ||
|
|
ea228164dc | ||
|
|
4b5ad9ace4 | ||
|
|
a94ffd413c | ||
|
|
1f921753fd | ||
|
|
157b64e643 | ||
|
|
6f285c5b0a | ||
|
|
bf39c30d24 | ||
|
|
7439e5579f | ||
|
|
4452dacc94 | ||
|
|
0579157010 | ||
|
|
3dbd0b80aa | ||
|
|
3863df3c1f | ||
|
|
08a5b8393f | ||
|
|
92dea21c67 | ||
|
|
82a52638cf | ||
|
|
a38113e862 | ||
|
|
7fd8ad65be | ||
|
|
ce9c7cb32a | ||
|
|
5d2252ebda | ||
|
|
3820d7413c | ||
|
|
ab90e1de04 | ||
|
|
a650d812fa | ||
|
|
c536782e01 | ||
|
|
9ffd1ec2c2 | ||
|
|
1c56068bf1 | ||
|
|
d2290e2037 | ||
|
|
0951508af7 | ||
|
|
34a5b69100 | ||
|
|
d939fe80bd | ||
|
|
4ea8a4732c | ||
|
|
da67cae4ce | ||
|
|
d3c7ecdef4 | ||
|
|
4d8e0baeb4 | ||
|
|
0b764a01dd | ||
|
|
f95bb9b28e | ||
|
|
8f21e07840 | ||
|
|
eed8d25120 | ||
|
|
265a43f5ff | ||
|
|
89cbdc824c | ||
|
|
4640651714 | ||
|
|
af8b7f1130 | ||
|
|
643270e247 | ||
|
|
24f1b7eeca | ||
|
|
60155f146a | ||
|
|
7c3f2c0bed | ||
|
|
85a1fd2caa | ||
|
|
f8d240a320 | ||
|
|
5860c723de | ||
|
|
33d35148d8 | ||
|
|
0e55b06c0a | ||
|
|
d964f06de1 | ||
|
|
100e17b242 | ||
|
|
7bf86d9c53 | ||
|
|
8fc5c21354 | ||
|
|
fe83a59d2a | ||
|
|
1b8692a216 | ||
|
|
57a70f411b | ||
|
|
b2d2b1765a | ||
|
|
430b530ca5 | ||
|
|
4a2936c685 | ||
|
|
d3c7c54797 | ||
|
|
83dc52572d | ||
|
|
810d45d6b9 | ||
|
|
9b4f60088f | ||
|
|
b222107044 | ||
|
|
d0495b7c00 | ||
|
|
ee874947d0 | ||
|
|
d38176faea | ||
|
|
2a00f94e23 | ||
|
|
8bd4278ae5 | ||
|
|
829a6df567 | ||
|
|
aa0c3118a0 | ||
|
|
015f5005d0 | ||
|
|
91c5ec6f18 | ||
|
|
cd9cc375ff | ||
|
|
819deca93c | ||
|
|
79632908d4 | ||
|
|
f979d44c96 | ||
|
|
44d2526997 | ||
|
|
14e604e21e | ||
|
|
677728b9ae | ||
|
|
84060a57da | ||
|
|
4a92625a7b | ||
|
|
bea526d64d | ||
|
|
717b2d176e | ||
|
|
cff5e53d09 | ||
|
|
221687c9d7 | ||
|
|
953fccba16 | ||
|
|
eca82e2888 | ||
|
|
ad93100e99 | ||
|
|
d80c77f466 | ||
|
|
a6376af7c2 | ||
|
|
f1e5c2dd66 | ||
|
|
5be0e928c4 | ||
|
|
bcc899eebf | ||
|
|
9ea91cbb3e | ||
|
|
da54712ae1 | ||
|
|
f459115b19 | ||
|
|
cc49648e37 | ||
|
|
9ce71088e2 | ||
|
|
0f3e6d9736 | ||
|
|
de97cce119 | ||
|
|
a82d20564a | ||
|
|
967f068637 | ||
|
|
90c33133c3 | ||
|
|
01ef367864 | ||
|
|
da5d442c91 | ||
|
|
ead7570ec5 | ||
|
|
43b2f9da1c | ||
|
|
668433dd62 | ||
|
|
a0772852de | ||
|
|
f0bd18c4d6 | ||
|
|
99000d8eab | ||
|
|
0b48afb692 | ||
|
|
299ad07222 | ||
|
|
19ec98b607 | ||
|
|
ec7fdb3f72 | ||
|
|
be8aba347d |
@@ -1,6 +1,11 @@
|
||||
image: briar/ci-image-android:latest
|
||||
|
||||
stages:
|
||||
- test
|
||||
- check_reproducibility
|
||||
|
||||
test:
|
||||
stage: test
|
||||
before_script:
|
||||
- set -e
|
||||
- export GRADLE_USER_HOME=$PWD/.gradle
|
||||
@@ -21,6 +26,7 @@ test:
|
||||
|
||||
|
||||
test_reproducible:
|
||||
stage: check_reproducibility
|
||||
script:
|
||||
- "curl -X POST -F token=${RELEASE_CHECK_TOKEN} -F ref=master -F variables[RELEASE_TAG]=${CI_COMMIT_REF_NAME} https://code.briarproject.org/api/v4/projects/61/trigger/pipeline"
|
||||
only:
|
||||
|
||||
20
.idea/runConfigurations/All_in_briar_headless.xml
generated
20
.idea/runConfigurations/All_in_briar_headless.xml
generated
@@ -1,20 +0,0 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="All in briar-headless" type="AndroidJUnit" factoryName="Android JUnit" nameIsGenerated="true">
|
||||
<module name="briar-headless" />
|
||||
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
|
||||
<option name="ALTERNATIVE_JRE_PATH" />
|
||||
<option name="PACKAGE_NAME" value="org.briarproject.briar.headless" />
|
||||
<option name="MAIN_CLASS_NAME" value="" />
|
||||
<option name="METHOD_NAME" value="" />
|
||||
<option name="TEST_OBJECT" value="package" />
|
||||
<option name="VM_PARAMETERS" value="" />
|
||||
<option name="PARAMETERS" value="" />
|
||||
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$/briar-headless" />
|
||||
<option name="PASS_PARENT_ENVS" value="true" />
|
||||
<option name="TEST_SEARCH_SCOPE">
|
||||
<value defaultName="singleModule" />
|
||||
</option>
|
||||
<patterns />
|
||||
<method />
|
||||
</configuration>
|
||||
</component>
|
||||
18
.idea/runConfigurations/All_tests.xml
generated
18
.idea/runConfigurations/All_tests.xml
generated
@@ -1,30 +1,20 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="All tests" type="AndroidJUnit" factoryName="Android JUnit">
|
||||
<extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea" />
|
||||
<module name="briar-android" />
|
||||
<option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
|
||||
<option name="ALTERNATIVE_JRE_PATH" />
|
||||
<option name="PACKAGE_NAME" value="" />
|
||||
<option name="MAIN_CLASS_NAME" value="" />
|
||||
<option name="METHOD_NAME" value="" />
|
||||
<option name="TEST_OBJECT" value="package" />
|
||||
<option name="VM_PARAMETERS" value="-ea" />
|
||||
<option name="PARAMETERS" value="" />
|
||||
<option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$/briar-android" />
|
||||
<option name="ENV_VARIABLES" />
|
||||
<option name="PASS_PARENT_ENVS" value="true" />
|
||||
<option name="TEST_SEARCH_SCOPE">
|
||||
<value defaultName="singleModule" />
|
||||
</option>
|
||||
<envs />
|
||||
<patterns />
|
||||
<method>
|
||||
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/briar-android" />
|
||||
<method v="2">
|
||||
<option name="Android.Gradle.BeforeRunTask" enabled="true" />
|
||||
<option name="RunConfigurationTask" enabled="true" run_configuration_name="All tests in bramble-api" run_configuration_type="AndroidJUnit" />
|
||||
<option name="RunConfigurationTask" enabled="true" run_configuration_name="All tests in bramble-core" run_configuration_type="AndroidJUnit" />
|
||||
<option name="RunConfigurationTask" enabled="true" run_configuration_name="All tests in bramble-android" run_configuration_type="AndroidJUnit" />
|
||||
<option name="RunConfigurationTask" enabled="true" run_configuration_name="All tests in bramble-java" run_configuration_type="AndroidJUnit" />
|
||||
<option name="RunConfigurationTask" enabled="true" run_configuration_name="All tests in briar-core" run_configuration_type="AndroidJUnit" />
|
||||
<option name="RunConfigurationTask" enabled="true" run_configuration_name="All in briar-headless" run_configuration_type="AndroidJUnit" />
|
||||
<option name="RunConfigurationTask" enabled="true" run_configuration_name="All tests in briar-headless" run_configuration_type="AndroidJUnit" />
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
||||
15
.idea/runConfigurations/All_tests_in_briar_headless.xml
generated
Normal file
15
.idea/runConfigurations/All_tests_in_briar_headless.xml
generated
Normal file
@@ -0,0 +1,15 @@
|
||||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="All tests in briar-headless" type="AndroidJUnit" factoryName="Android JUnit">
|
||||
<module name="briar-headless" />
|
||||
<option name="PACKAGE_NAME" value="org.briarproject.briar.headless" />
|
||||
<option name="MAIN_CLASS_NAME" value="" />
|
||||
<option name="METHOD_NAME" value="" />
|
||||
<option name="TEST_OBJECT" value="package" />
|
||||
<option name="VM_PARAMETERS" />
|
||||
<option name="PARAMETERS" value="" />
|
||||
<option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/briar-headless" />
|
||||
<method v="2">
|
||||
<option name="Android.Gradle.BeforeRunTask" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
||||
@@ -2,10 +2,13 @@ package org.briarproject.bramble;
|
||||
|
||||
import org.briarproject.bramble.battery.AndroidBatteryModule;
|
||||
import org.briarproject.bramble.network.AndroidNetworkModule;
|
||||
import org.briarproject.bramble.reporting.ReportingModule;
|
||||
|
||||
public interface BrambleAndroidEagerSingletons {
|
||||
|
||||
void inject(AndroidBatteryModule.EagerSingletons init);
|
||||
|
||||
void inject(AndroidNetworkModule.EagerSingletons init);
|
||||
|
||||
void inject(ReportingModule.EagerSingletons init);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package org.briarproject.bramble;
|
||||
import org.briarproject.bramble.battery.AndroidBatteryModule;
|
||||
import org.briarproject.bramble.network.AndroidNetworkModule;
|
||||
import org.briarproject.bramble.plugin.tor.CircumventionModule;
|
||||
import org.briarproject.bramble.reporting.ReportingModule;
|
||||
import org.briarproject.bramble.socks.SocksModule;
|
||||
import org.briarproject.bramble.system.AndroidSystemModule;
|
||||
|
||||
import dagger.Module;
|
||||
@@ -11,12 +13,15 @@ import dagger.Module;
|
||||
AndroidBatteryModule.class,
|
||||
AndroidNetworkModule.class,
|
||||
AndroidSystemModule.class,
|
||||
CircumventionModule.class
|
||||
CircumventionModule.class,
|
||||
ReportingModule.class,
|
||||
SocksModule.class
|
||||
})
|
||||
public class BrambleAndroidModule {
|
||||
|
||||
public static void initEagerSingletons(BrambleAndroidEagerSingletons c) {
|
||||
c.inject(new AndroidBatteryModule.EagerSingletons());
|
||||
c.inject(new AndroidNetworkModule.EagerSingletons());
|
||||
c.inject(new ReportingModule.EagerSingletons());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ import android.content.IntentFilter;
|
||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Backoff;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.PluginException;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.system.AndroidExecutor;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
@@ -51,6 +51,7 @@ import static android.bluetooth.BluetoothDevice.EXTRA_DEVICE;
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
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.PrivacyUtils.scrubMacAddress;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@@ -58,7 +59,7 @@ import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress;
|
||||
class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
||||
|
||||
private static final Logger LOG =
|
||||
Logger.getLogger(AndroidBluetoothPlugin.class.getName());
|
||||
getLogger(AndroidBluetoothPlugin.class.getName());
|
||||
|
||||
private static final int MAX_DISCOVERY_MS = 10_000;
|
||||
|
||||
@@ -75,7 +76,7 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
|
||||
AndroidBluetoothPlugin(BluetoothConnectionLimiter connectionLimiter,
|
||||
Executor ioExecutor, AndroidExecutor androidExecutor,
|
||||
Context appContext, SecureRandom secureRandom, Clock clock,
|
||||
Backoff backoff, DuplexPluginCallback callback, int maxLatency) {
|
||||
Backoff backoff, PluginCallback callback, int maxLatency) {
|
||||
super(connectionLimiter, ioExecutor, secureRandom, backoff, callback,
|
||||
maxLatency);
|
||||
this.androidExecutor = androidExecutor;
|
||||
|
||||
@@ -6,9 +6,9 @@ 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;
|
||||
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.DuplexPluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||
import org.briarproject.bramble.api.system.AndroidExecutor;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
@@ -61,7 +61,7 @@ public class AndroidBluetoothPluginFactory implements DuplexPluginFactory {
|
||||
}
|
||||
|
||||
@Override
|
||||
public DuplexPlugin createPlugin(DuplexPluginCallback callback) {
|
||||
public DuplexPlugin createPlugin(PluginCallback callback) {
|
||||
BluetoothConnectionLimiter connectionLimiter =
|
||||
new BluetoothConnectionLimiterImpl();
|
||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||
|
||||
@@ -13,7 +13,7 @@ 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.duplex.DuplexPluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
@@ -32,17 +32,18 @@ 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.Logger.getLogger;
|
||||
|
||||
@NotNullByDefault
|
||||
class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
|
||||
|
||||
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;
|
||||
|
||||
private static final Logger LOG =
|
||||
Logger.getLogger(AndroidLanTcpPlugin.class.getName());
|
||||
|
||||
static {
|
||||
try {
|
||||
WIFI_AP_ADDRESS = InetAddress.getByAddress(WIFI_AP_ADDRESS_BYTES);
|
||||
@@ -60,7 +61,7 @@ class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
|
||||
private volatile SocketFactory socketFactory;
|
||||
|
||||
AndroidLanTcpPlugin(Executor ioExecutor, Context appContext,
|
||||
Backoff backoff, DuplexPluginCallback callback, int maxLatency,
|
||||
Backoff backoff, PluginCallback callback, int maxLatency,
|
||||
int maxIdleTime) {
|
||||
super(ioExecutor, backoff, callback, maxLatency, maxIdleTime);
|
||||
// Don't execute more than one connection status check at a time
|
||||
|
||||
@@ -6,9 +6,9 @@ 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;
|
||||
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.DuplexPluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
@@ -51,7 +51,7 @@ public class AndroidLanTcpPluginFactory implements DuplexPluginFactory {
|
||||
}
|
||||
|
||||
@Override
|
||||
public DuplexPlugin createPlugin(DuplexPluginCallback callback) {
|
||||
public DuplexPlugin createPlugin(PluginCallback callback) {
|
||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||
AndroidLanTcpPlugin plugin = new AndroidLanTcpPlugin(ioExecutor,
|
||||
|
||||
@@ -11,7 +11,7 @@ import org.briarproject.bramble.api.network.NetworkManager;
|
||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Backoff;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.api.system.LocationUtils;
|
||||
import org.briarproject.bramble.api.system.ResourceProvider;
|
||||
@@ -41,11 +41,12 @@ class AndroidTorPlugin extends TorPlugin {
|
||||
Clock clock, ResourceProvider resourceProvider,
|
||||
CircumventionProvider circumventionProvider,
|
||||
BatteryManager batteryManager, Backoff backoff,
|
||||
DuplexPluginCallback callback, String architecture, int maxLatency,
|
||||
TorRendezvousCrypto torRendezvousCrypto,
|
||||
PluginCallback callback, String architecture, int maxLatency,
|
||||
int maxIdleTime) {
|
||||
super(ioExecutor, networkManager, locationUtils, torSocketFactory,
|
||||
clock, resourceProvider, circumventionProvider, batteryManager,
|
||||
backoff, callback, architecture, maxLatency, maxIdleTime,
|
||||
backoff, torRendezvousCrypto, callback, architecture, maxLatency, maxIdleTime,
|
||||
appContext.getDir("tor", MODE_PRIVATE));
|
||||
this.appContext = appContext;
|
||||
PowerManager pm = (PowerManager)
|
||||
|
||||
@@ -9,10 +9,10 @@ import org.briarproject.bramble.api.network.NetworkManager;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.Backoff;
|
||||
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.TorConstants;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.api.system.LocationUtils;
|
||||
@@ -84,7 +84,7 @@ public class AndroidTorPluginFactory implements DuplexPluginFactory {
|
||||
}
|
||||
|
||||
@Override
|
||||
public DuplexPlugin createPlugin(DuplexPluginCallback callback) {
|
||||
public DuplexPlugin createPlugin(PluginCallback callback) {
|
||||
|
||||
// Check that we have a Tor binary for this architecture
|
||||
String architecture = null;
|
||||
@@ -106,10 +106,12 @@ public class AndroidTorPluginFactory implements DuplexPluginFactory {
|
||||
|
||||
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
|
||||
MAX_POLLING_INTERVAL, BACKOFF_BASE);
|
||||
TorRendezvousCrypto torRendezvousCrypto = new TorRendezvousCryptoImpl();
|
||||
AndroidTorPlugin plugin = new AndroidTorPlugin(ioExecutor, scheduler,
|
||||
appContext, networkManager, locationUtils, torSocketFactory,
|
||||
clock, resourceProvider, circumventionProvider, batteryManager,
|
||||
backoff, callback, architecture, MAX_LATENCY, MAX_IDLE_TIME);
|
||||
backoff, torRendezvousCrypto, callback, architecture,
|
||||
MAX_LATENCY, MAX_IDLE_TIME);
|
||||
eventBus.addListener(plugin);
|
||||
return plugin;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.util.StringUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
@@ -16,8 +15,6 @@ import javax.annotation.concurrent.ThreadSafe;
|
||||
@NotNullByDefault
|
||||
public class Bytes implements Comparable<Bytes> {
|
||||
|
||||
public static final BytesComparator COMPARATOR = new BytesComparator();
|
||||
|
||||
private final byte[] bytes;
|
||||
|
||||
private int hashCode = -1;
|
||||
@@ -45,14 +42,7 @@ public class Bytes implements Comparable<Bytes> {
|
||||
|
||||
@Override
|
||||
public int compareTo(Bytes other) {
|
||||
byte[] aBytes = bytes, bBytes = other.bytes;
|
||||
int length = Math.min(aBytes.length, bBytes.length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
int aUnsigned = aBytes[i] & 0xFF, bUnsigned = bBytes[i] & 0xFF;
|
||||
if (aUnsigned < bUnsigned) return -1;
|
||||
if (aUnsigned > bUnsigned) return 1;
|
||||
}
|
||||
return aBytes.length - bBytes.length;
|
||||
return compare(bytes, other.bytes);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -61,11 +51,13 @@ public class Bytes implements Comparable<Bytes> {
|
||||
"(" + StringUtils.toHexString(getBytes()) + ")";
|
||||
}
|
||||
|
||||
public static class BytesComparator implements Comparator<Bytes> {
|
||||
|
||||
@Override
|
||||
public int compare(Bytes a, Bytes b) {
|
||||
return a.compareTo(b);
|
||||
public static int compare(byte[] a, byte[] b) {
|
||||
int length = Math.min(a.length, b.length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
int aUnsigned = a[i] & 0xFF, bUnsigned = b[i] & 0xFF;
|
||||
if (aUnsigned < bUnsigned) return -1;
|
||||
if (aUnsigned > bUnsigned) return 1;
|
||||
}
|
||||
return a.length - b.length;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.briarproject.bramble.api;
|
||||
|
||||
/**
|
||||
* Interface for specifying which features are enabled in a build.
|
||||
*/
|
||||
public interface FeatureFlags {
|
||||
|
||||
boolean shouldEnableImageAttachments();
|
||||
|
||||
boolean shouldEnableRemoteContacts();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package org.briarproject.bramble.api;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
@NotNullByDefault
|
||||
public interface Predicate<T> {
|
||||
|
||||
boolean test(T t);
|
||||
}
|
||||
@@ -25,7 +25,10 @@ public interface ClientHelper {
|
||||
throws DbException, FormatException;
|
||||
|
||||
void addLocalMessage(Transaction txn, Message m, BdfDictionary metadata,
|
||||
boolean shared) throws DbException, FormatException;
|
||||
boolean shared, boolean temporary)
|
||||
throws DbException, FormatException;
|
||||
|
||||
Message createMessage(GroupId g, long timestamp, byte[] body);
|
||||
|
||||
Message createMessage(GroupId g, long timestamp, BdfList body)
|
||||
throws FormatException;
|
||||
@@ -108,7 +111,7 @@ public interface ClientHelper {
|
||||
Author parseAndValidateAuthor(BdfList author) throws FormatException;
|
||||
|
||||
PublicKey parseAndValidateAgreementPublicKey(byte[] publicKeyBytes)
|
||||
throws FormatException;
|
||||
throws FormatException;
|
||||
|
||||
TransportProperties parseAndValidateTransportProperties(
|
||||
BdfDictionary properties) throws FormatException;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package org.briarproject.bramble.api.contact;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.ContactExistsException;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@NotNullByDefault
|
||||
public interface ContactExchangeManager {
|
||||
|
||||
/**
|
||||
* Exchanges contact information with a remote peer and adds the peer
|
||||
* as a contact.
|
||||
*
|
||||
* @param alice Whether the local peer takes the role of Alice
|
||||
* @return The newly added contact
|
||||
* @throws ContactExistsException If the contact already exists
|
||||
*/
|
||||
Contact exchangeContacts(DuplexTransportConnection conn,
|
||||
SecretKey masterKey, boolean alice, boolean verified)
|
||||
throws IOException, DbException;
|
||||
|
||||
/**
|
||||
* Exchanges contact information with a remote peer and adds the peer
|
||||
* as a contact, replacing the given pending contact.
|
||||
*
|
||||
* @param alice Whether the local peer takes the role of Alice
|
||||
* @return The newly added contact
|
||||
* @throws ContactExistsException If the contact already exists
|
||||
*/
|
||||
Contact exchangeContacts(PendingContactId p, DuplexTransportConnection conn,
|
||||
SecretKey masterKey, boolean alice, boolean verified)
|
||||
throws IOException, DbException;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.briarproject.bramble.api.contact;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.Pair;
|
||||
import org.briarproject.bramble.api.UnsupportedVersionException;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
@@ -12,6 +13,7 @@ import org.briarproject.bramble.api.identity.AuthorInfo;
|
||||
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
@@ -28,28 +30,71 @@ public interface ContactManager {
|
||||
|
||||
/**
|
||||
* Stores a contact associated with the given local and remote pseudonyms,
|
||||
* derives and stores transport keys for each transport, and returns an ID
|
||||
* for the contact.
|
||||
* derives and stores rotation mode transport keys for each transport, and
|
||||
* returns an ID for the contact.
|
||||
*
|
||||
* @param alice true if the local party is Alice
|
||||
* @param rootKey The root key for a set of rotation mode transport keys
|
||||
* @param timestamp The timestamp for deriving rotation mode transport
|
||||
* keys from the root key
|
||||
* @param alice True if the local party is Alice
|
||||
* @param verified True if the contact's identity has been verified, which
|
||||
* is true if the contact was added in person or false if the contact was
|
||||
* introduced or added remotely
|
||||
* @param active True if the rotation mode transport keys can be used for
|
||||
* outgoing streams
|
||||
*/
|
||||
ContactId addContact(Transaction txn, Author remote, AuthorId local,
|
||||
SecretKey rootKey, long timestamp, boolean alice, boolean verified,
|
||||
boolean active) throws DbException;
|
||||
|
||||
/**
|
||||
* Stores a contact associated with the given local and remote pseudonyms,
|
||||
* replacing the given pending contact, derives and stores handshake mode
|
||||
* and rotation mode transport keys for each transport, and returns an ID
|
||||
* for the contact.
|
||||
*
|
||||
* @param rootKey The root key for a set of rotation mode transport keys
|
||||
* @param timestamp The timestamp for deriving rotation mode transport
|
||||
* keys from the root key
|
||||
* @param alice True if the local party is Alice
|
||||
* @param verified True if the contact's identity has been verified, which
|
||||
* is true if the contact was added in person or false if the contact was
|
||||
* introduced or added remotely
|
||||
* @param active True if the rotation mode transport keys can be used for
|
||||
* outgoing streams
|
||||
* @throws GeneralSecurityException If the pending contact's handshake
|
||||
* public key is invalid
|
||||
*/
|
||||
ContactId addContact(Transaction txn, PendingContactId p, Author remote,
|
||||
AuthorId local, SecretKey rootKey, long timestamp, boolean alice,
|
||||
boolean verified, boolean active)
|
||||
throws DbException, GeneralSecurityException;
|
||||
|
||||
/**
|
||||
* Stores a contact associated with the given local and remote pseudonyms
|
||||
* and returns an ID for the contact.
|
||||
*
|
||||
* @param verified True if the contact's identity has been verified, which
|
||||
* is true if the contact was added in person or false if the contact was
|
||||
* introduced or added remotely
|
||||
*/
|
||||
ContactId addContact(Transaction txn, Author remote, AuthorId local,
|
||||
boolean verified) throws DbException;
|
||||
|
||||
/**
|
||||
* Stores a contact associated with the given local and remote pseudonyms,
|
||||
* derives and stores transport keys for each transport, and returns an ID
|
||||
* for the contact.
|
||||
* derives and stores rotation mode transport keys for each transport, and
|
||||
* returns an ID for the contact.
|
||||
*
|
||||
* @param alice true if the local party is Alice
|
||||
* @param rootKey The root key for a set of rotation mode transport keys
|
||||
* @param timestamp The timestamp for deriving rotation mode transport
|
||||
* keys from the root key
|
||||
* @param alice True if the local party is Alice
|
||||
* @param verified True if the contact's identity has been verified, which
|
||||
* is true if the contact was added in person or false if the contact was
|
||||
* introduced or added remotely
|
||||
* @param active True if the rotation mode transport keys can be used for
|
||||
* outgoing streams
|
||||
*/
|
||||
ContactId addContact(Author remote, AuthorId local, SecretKey rootKey,
|
||||
long timestamp, boolean alice, boolean verified, boolean active)
|
||||
@@ -65,20 +110,29 @@ public interface ContactManager {
|
||||
* Creates a {@link PendingContact} from the given handshake link and
|
||||
* alias, adds it to the database and returns it.
|
||||
*
|
||||
* @param link The handshake link received from the contact we want to add
|
||||
* @param alias The alias the user has given this contact
|
||||
* @return A PendingContact representing the contact to be added
|
||||
* @param link The handshake link received from the pending contact
|
||||
* @param alias The alias the user has given this pending contact
|
||||
* @throws UnsupportedVersionException If the link uses a format version
|
||||
* that is not supported
|
||||
* @throws FormatException If the link is invalid
|
||||
* @throws GeneralSecurityException If the pending contact's handshake
|
||||
* public key is invalid
|
||||
*/
|
||||
PendingContact addPendingContact(String link, String alias)
|
||||
throws DbException, FormatException;
|
||||
throws DbException, FormatException, GeneralSecurityException;
|
||||
|
||||
/**
|
||||
* Returns a list of {@link PendingContact}s.
|
||||
* Returns the pending contact with the given ID.
|
||||
*/
|
||||
Collection<PendingContact> getPendingContacts() throws DbException;
|
||||
PendingContact getPendingContact(Transaction txn, PendingContactId p)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Returns a list of {@link PendingContact PendingContacts} and their
|
||||
* {@link PendingContactState states}.
|
||||
*/
|
||||
Collection<Pair<PendingContact, PendingContactState>> getPendingContacts()
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Removes a {@link PendingContact}.
|
||||
@@ -91,8 +145,13 @@ public interface ContactManager {
|
||||
Contact getContact(ContactId c) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the contact with the given remoteAuthorId
|
||||
* that was added by the LocalAuthor with the given localAuthorId
|
||||
* Returns the contact with the given ID.
|
||||
*/
|
||||
Contact getContact(Transaction txn, ContactId c) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the contact with the given {@code remoteAuthorId}
|
||||
* that belongs to the local pseudonym with the given {@code localAuthorId}.
|
||||
*
|
||||
* @throws NoSuchContactException If the contact is not in the database
|
||||
*/
|
||||
@@ -100,8 +159,8 @@ public interface ContactManager {
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the contact with the given remoteAuthorId
|
||||
* that was added by the LocalAuthor with the given localAuthorId
|
||||
* Returns the contact with the given {@code remoteAuthorId}
|
||||
* that belongs to the local pseudonym with the given {@code localAuthorId}.
|
||||
*
|
||||
* @throws NoSuchContactException If the contact is not in the database
|
||||
*/
|
||||
@@ -109,7 +168,7 @@ public interface ContactManager {
|
||||
AuthorId localAuthorId) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns all active contacts.
|
||||
* Returns all contacts.
|
||||
*/
|
||||
Collection<Contact> getContacts() throws DbException;
|
||||
|
||||
@@ -124,25 +183,27 @@ public interface ContactManager {
|
||||
void removeContact(Transaction txn, ContactId c) throws DbException;
|
||||
|
||||
/**
|
||||
* Sets an alias name for the contact or unsets it if alias is null.
|
||||
* Sets an alias for the contact or unsets it if {@code alias} is null.
|
||||
*/
|
||||
void setContactAlias(Transaction txn, ContactId c, @Nullable String alias)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Sets an alias name for the contact or unsets it if alias is null.
|
||||
* Sets an alias for the contact or unsets it if {@code alias} is null.
|
||||
*/
|
||||
void setContactAlias(ContactId c, @Nullable String alias)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Return true if a contact with this name and public key already exists
|
||||
* Returns true if a contact with this {@code remoteAuthorId} belongs to
|
||||
* the local pseudonym with this {@code localAuthorId}.
|
||||
*/
|
||||
boolean contactExists(Transaction txn, AuthorId remoteAuthorId,
|
||||
AuthorId localAuthorId) throws DbException;
|
||||
|
||||
/**
|
||||
* Return true if a contact with this name and public key already exists
|
||||
* Returns true if a contact with this {@code remoteAuthorId} belongs to
|
||||
* the local pseudonym with this {@code localAuthorId}.
|
||||
*/
|
||||
boolean contactExists(AuthorId remoteAuthorId, AuthorId localAuthorId)
|
||||
throws DbException;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package org.briarproject.bramble.api.contact;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.transport.StreamWriter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
@NotNullByDefault
|
||||
public interface HandshakeManager {
|
||||
|
||||
/**
|
||||
* Handshakes with the given pending contact. Returns an ephemeral master
|
||||
* key authenticated with both parties' handshake key pairs and a flag
|
||||
* indicating whether the local peer is Alice or Bob.
|
||||
*
|
||||
* @param in An incoming stream for the handshake, which must be secured in
|
||||
* handshake mode
|
||||
* @param out An outgoing stream for the handshake, which must be secured
|
||||
* in handshake mode
|
||||
*/
|
||||
HandshakeResult handshake(PendingContactId p, InputStream in,
|
||||
StreamWriter out) throws DbException, IOException;
|
||||
|
||||
class HandshakeResult {
|
||||
|
||||
private final SecretKey masterKey;
|
||||
private final boolean alice;
|
||||
|
||||
public HandshakeResult(SecretKey masterKey, boolean alice) {
|
||||
this.masterKey = masterKey;
|
||||
this.alice = alice;
|
||||
}
|
||||
|
||||
public SecretKey getMasterKey() {
|
||||
return masterKey;
|
||||
}
|
||||
|
||||
public boolean isAlice() {
|
||||
return alice;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,15 +12,13 @@ public class PendingContact {
|
||||
private final PendingContactId id;
|
||||
private final PublicKey publicKey;
|
||||
private final String alias;
|
||||
private final PendingContactState state;
|
||||
private final long timestamp;
|
||||
|
||||
public PendingContact(PendingContactId id, PublicKey publicKey,
|
||||
String alias, PendingContactState state, long timestamp) {
|
||||
String alias, long timestamp) {
|
||||
this.id = id;
|
||||
this.publicKey = publicKey;
|
||||
this.alias = alias;
|
||||
this.state = state;
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
@@ -36,10 +34,6 @@ public class PendingContact {
|
||||
return alias;
|
||||
}
|
||||
|
||||
public PendingContactState getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
@@ -1,30 +1,10 @@
|
||||
package org.briarproject.bramble.api.contact;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public enum PendingContactState {
|
||||
|
||||
WAITING_FOR_CONNECTION(0),
|
||||
CONNECTED(1),
|
||||
ADDING_CONTACT(2),
|
||||
FAILED(3);
|
||||
|
||||
private final int value;
|
||||
|
||||
PendingContactState(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public static PendingContactState fromValue(int value) {
|
||||
for (PendingContactState s : values()) if (s.value == value) return s;
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
WAITING_FOR_CONNECTION,
|
||||
OFFLINE,
|
||||
CONNECTING,
|
||||
ADDING_CONTACT,
|
||||
FAILED
|
||||
}
|
||||
|
||||
@@ -14,12 +14,18 @@ import javax.annotation.concurrent.Immutable;
|
||||
public class ContactAddedEvent extends Event {
|
||||
|
||||
private final ContactId contactId;
|
||||
private final boolean verified;
|
||||
|
||||
public ContactAddedEvent(ContactId contactId) {
|
||||
public ContactAddedEvent(ContactId contactId, boolean verified) {
|
||||
this.contactId = contactId;
|
||||
this.verified = verified;
|
||||
}
|
||||
|
||||
public ContactId getContactId() {
|
||||
return contactId;
|
||||
}
|
||||
|
||||
public boolean isVerified() {
|
||||
return verified;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
package org.briarproject.bramble.api.contact.event;
|
||||
|
||||
import org.briarproject.bramble.api.contact.Contact;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class ContactAddedRemotelyEvent extends Event {
|
||||
|
||||
private final Contact contact;
|
||||
|
||||
public ContactAddedRemotelyEvent(Contact contact) {
|
||||
this.contact = contact;
|
||||
}
|
||||
|
||||
public Contact getContact() {
|
||||
return contact;
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package org.briarproject.bramble.api.contact.event;
|
||||
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
@NotNullByDefault
|
||||
public class ContactExchangeFailedEvent extends Event {
|
||||
|
||||
@Nullable
|
||||
private final Author duplicateRemoteAuthor;
|
||||
|
||||
public ContactExchangeFailedEvent(@Nullable Author duplicateRemoteAuthor) {
|
||||
this.duplicateRemoteAuthor = duplicateRemoteAuthor;
|
||||
}
|
||||
|
||||
public ContactExchangeFailedEvent() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Author getDuplicateRemoteAuthor() {
|
||||
return duplicateRemoteAuthor;
|
||||
}
|
||||
|
||||
public boolean wasDuplicateContact() {
|
||||
return duplicateRemoteAuthor != null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package org.briarproject.bramble.api.contact.event;
|
||||
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
@NotNullByDefault
|
||||
public class ContactExchangeSucceededEvent extends Event {
|
||||
|
||||
private final Author remoteAuthor;
|
||||
|
||||
public ContactExchangeSucceededEvent(Author remoteAuthor) {
|
||||
this.remoteAuthor = remoteAuthor;
|
||||
}
|
||||
|
||||
public Author getRemoteAuthor() {
|
||||
return remoteAuthor;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.briarproject.bramble.api.contact.event;
|
||||
|
||||
import org.briarproject.bramble.api.contact.PendingContact;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* An event that is broadcast when a pending contact is added.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class PendingContactAddedEvent extends Event {
|
||||
|
||||
private final PendingContact pendingContact;
|
||||
|
||||
public PendingContactAddedEvent(PendingContact pendingContact) {
|
||||
this.pendingContact = pendingContact;
|
||||
}
|
||||
|
||||
public PendingContact getPendingContact() {
|
||||
return pendingContact;
|
||||
}
|
||||
}
|
||||
@@ -27,31 +27,55 @@ public interface CryptoComponent {
|
||||
/**
|
||||
* Derives another secret key from the given secret key.
|
||||
*
|
||||
* @param label a namespaced label indicating the purpose of the derived
|
||||
* @param label A namespaced label indicating the purpose of the derived
|
||||
* key, to prevent it from being repurposed or colliding with a key derived
|
||||
* for another purpose
|
||||
* @param inputs Additional inputs that will be included in the derivation
|
||||
* of the key
|
||||
*/
|
||||
SecretKey deriveKey(String label, SecretKey k, byte[]... inputs);
|
||||
|
||||
/**
|
||||
* Derives a common shared secret from two public keys and one of the
|
||||
* corresponding private keys.
|
||||
* Derives a shared secret from two key pairs.
|
||||
*
|
||||
* @param label a namespaced label indicating the purpose of this shared
|
||||
* @param label A namespaced label indicating the purpose of this shared
|
||||
* secret, to prevent it from being repurposed or colliding with a shared
|
||||
* secret derived for another purpose
|
||||
* @param theirPublicKey the public key of the remote party
|
||||
* @param ourKeyPair the key pair of the local party
|
||||
* @return the shared secret
|
||||
* @param theirPublicKey The public key of the remote party
|
||||
* @param ourKeyPair The key pair of the local party
|
||||
* @param inputs Additional inputs that will be included in the derivation
|
||||
* of the shared secret
|
||||
* @return The shared secret
|
||||
*/
|
||||
SecretKey deriveSharedSecret(String label, PublicKey theirPublicKey,
|
||||
KeyPair ourKeyPair, byte[]... inputs)
|
||||
throws GeneralSecurityException;
|
||||
|
||||
/**
|
||||
* Derives a shared secret from two static and two ephemeral key pairs.
|
||||
*
|
||||
* @param label A namespaced label indicating the purpose of this shared
|
||||
* secret, to prevent it from being repurposed or colliding with a shared
|
||||
* secret derived for another purpose
|
||||
* @param theirStaticPublicKey The static public key of the remote party
|
||||
* @param theirEphemeralPublicKey The ephemeral public key of the remote
|
||||
* party
|
||||
* @param ourStaticKeyPair The static key pair of the local party
|
||||
* @param ourEphemeralKeyPair The ephemeral key pair of the local party
|
||||
* @param alice True if the local party is Alice
|
||||
* @param inputs Additional inputs that will be included in the
|
||||
* derivation of the shared secret
|
||||
* @return The shared secret
|
||||
*/
|
||||
SecretKey deriveSharedSecret(String label, PublicKey theirStaticPublicKey,
|
||||
PublicKey theirEphemeralPublicKey, KeyPair ourStaticKeyPair,
|
||||
KeyPair ourEphemeralKeyPair, boolean alice, byte[]... inputs)
|
||||
throws GeneralSecurityException;
|
||||
|
||||
/**
|
||||
* Signs the given byte[] with the given private key.
|
||||
*
|
||||
* @param label a namespaced label indicating the purpose of this
|
||||
* @param label A namespaced label indicating the purpose of this
|
||||
* signature, to prevent it from being repurposed or colliding with a
|
||||
* signature created for another purpose
|
||||
*/
|
||||
@@ -62,10 +86,10 @@ public interface CryptoComponent {
|
||||
* Verifies that the given signature is valid for the signed data
|
||||
* and the given public key.
|
||||
*
|
||||
* @param label a namespaced label indicating the purpose of this
|
||||
* @param label A namespaced label indicating the purpose of this
|
||||
* signature, to prevent it from being repurposed or colliding with a
|
||||
* signature created for another purpose
|
||||
* @return true if the signature was valid, false otherwise.
|
||||
* @return True if the signature was valid, false otherwise.
|
||||
*/
|
||||
boolean verifySignature(byte[] signature, String label, byte[] signed,
|
||||
PublicKey publicKey) throws GeneralSecurityException;
|
||||
@@ -74,7 +98,7 @@ public interface CryptoComponent {
|
||||
* Returns the hash of the given inputs. The inputs are unambiguously
|
||||
* combined by prefixing each input with its length.
|
||||
*
|
||||
* @param label a namespaced label indicating the purpose of this hash, to
|
||||
* @param label A namespaced label indicating the purpose of this hash, to
|
||||
* prevent it from being repurposed or colliding with a hash created for
|
||||
* another purpose
|
||||
*/
|
||||
@@ -85,7 +109,7 @@ public interface CryptoComponent {
|
||||
* given inputs. The inputs are unambiguously combined by prefixing each
|
||||
* input with its length.
|
||||
*
|
||||
* @param label a namespaced label indicating the purpose of this MAC, to
|
||||
* @param label A namespaced label indicating the purpose of this MAC, to
|
||||
* prevent it from being repurposed or colliding with a MAC created for
|
||||
* another purpose
|
||||
*/
|
||||
@@ -95,10 +119,10 @@ public interface CryptoComponent {
|
||||
* Verifies that the given message authentication code is valid for the
|
||||
* given secret key and inputs.
|
||||
*
|
||||
* @param label a namespaced label indicating the purpose of this MAC, to
|
||||
* @param label A namespaced label indicating the purpose of this MAC, to
|
||||
* prevent it from being repurposed or colliding with a MAC created for
|
||||
* another purpose
|
||||
* @return true if the MAC was valid, false otherwise.
|
||||
* @return True if the MAC was valid, false otherwise.
|
||||
*/
|
||||
boolean verifyMac(byte[] mac, String label, SecretKey macKey,
|
||||
byte[]... inputs);
|
||||
|
||||
@@ -3,12 +3,37 @@ package org.briarproject.bramble.api.crypto;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.transport.TransportKeys;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
/**
|
||||
* Crypto operations for the transport security protocol - see
|
||||
* https://code.briarproject.org/briar/briar-spec/blob/master/protocols/BTP.md
|
||||
*/
|
||||
public interface TransportCrypto {
|
||||
|
||||
/**
|
||||
* Returns true if the local peer is Alice.
|
||||
*/
|
||||
boolean isAlice(PublicKey theirHandshakePublicKey,
|
||||
KeyPair ourHandshakeKeyPair);
|
||||
|
||||
/**
|
||||
* Derives the static master key shared with a contact or pending contact.
|
||||
*/
|
||||
SecretKey deriveStaticMasterKey(PublicKey theirHandshakePublicKey,
|
||||
KeyPair ourHandshakeKeyPair) throws GeneralSecurityException;
|
||||
|
||||
/**
|
||||
* Derives the handshake mode root key from the static master key. To
|
||||
* prevent tag reuse, separate root keys are derived for contacts and
|
||||
* pending contacts.
|
||||
*
|
||||
* @param pendingContact Whether the static master key is shared with a
|
||||
* pending contact or a contact
|
||||
*/
|
||||
SecretKey deriveHandshakeRootKey(SecretKey staticMasterKey,
|
||||
boolean pendingContact);
|
||||
|
||||
/**
|
||||
* Derives initial rotation mode transport keys for the given transport in
|
||||
* the given time period from the given root key.
|
||||
|
||||
@@ -1,8 +1,27 @@
|
||||
package org.briarproject.bramble.api.db;
|
||||
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
import org.briarproject.bramble.api.identity.AuthorId;
|
||||
|
||||
/**
|
||||
* Thrown when a duplicate contact is added to the database. This exception may
|
||||
* occur due to concurrent updates and does not indicate a database error.
|
||||
*/
|
||||
public class ContactExistsException extends DbException {
|
||||
|
||||
private final AuthorId local;
|
||||
private final Author remote;
|
||||
|
||||
public ContactExistsException(AuthorId local, Author remote) {
|
||||
this.local = local;
|
||||
this.remote = remote;
|
||||
}
|
||||
|
||||
public AuthorId getLocalAuthorId() {
|
||||
return local;
|
||||
}
|
||||
|
||||
public Author getRemoteAuthor() {
|
||||
return remote;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ import org.briarproject.bramble.api.transport.TransportKeySet;
|
||||
import org.briarproject.bramble.api.transport.TransportKeys;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
@@ -38,7 +39,7 @@ import javax.annotation.Nullable;
|
||||
* to other components.
|
||||
*/
|
||||
@NotNullByDefault
|
||||
public interface DatabaseComponent {
|
||||
public interface DatabaseComponent extends TransactionManager {
|
||||
|
||||
/**
|
||||
* Opens the database and returns true if the database already existed.
|
||||
@@ -56,56 +57,12 @@ public interface DatabaseComponent {
|
||||
*/
|
||||
void close() throws DbException;
|
||||
|
||||
/**
|
||||
* Starts a new transaction and returns an object representing it.
|
||||
* <p/>
|
||||
* This method acquires locks, so it must not be called while holding a
|
||||
* lock.
|
||||
*
|
||||
* @param readOnly true if the transaction will only be used for reading.
|
||||
*/
|
||||
Transaction startTransaction(boolean readOnly) throws DbException;
|
||||
|
||||
/**
|
||||
* Commits a transaction to the database.
|
||||
*/
|
||||
void commitTransaction(Transaction txn) throws DbException;
|
||||
|
||||
/**
|
||||
* Ends a transaction. If the transaction has not been committed,
|
||||
* it will be aborted. If the transaction has been committed,
|
||||
* any events attached to the transaction are broadcast.
|
||||
* The database lock will be released in either case.
|
||||
*/
|
||||
void endTransaction(Transaction txn);
|
||||
|
||||
/**
|
||||
* Runs the given task within a transaction.
|
||||
*/
|
||||
<E extends Exception> void transaction(boolean readOnly,
|
||||
DbRunnable<E> task) throws DbException, E;
|
||||
|
||||
/**
|
||||
* Runs the given task within a transaction and returns the result of the
|
||||
* task.
|
||||
*/
|
||||
<R, E extends Exception> R transactionWithResult(boolean readOnly,
|
||||
DbCallable<R, E> task) throws DbException, E;
|
||||
|
||||
/**
|
||||
* Runs the given task within a transaction and returns the result of the
|
||||
* task, which may be null.
|
||||
*/
|
||||
@Nullable
|
||||
<R, E extends Exception> R transactionWithNullableResult(boolean readOnly,
|
||||
NullableDbCallable<R, E> task) throws DbException, E;
|
||||
|
||||
/**
|
||||
* Stores a contact associated with the given local and remote pseudonyms,
|
||||
* and returns an ID for the contact.
|
||||
*/
|
||||
ContactId addContact(Transaction txn, Author remote, AuthorId local,
|
||||
boolean verified) throws DbException;
|
||||
@Nullable PublicKey handshake, boolean verified) throws DbException;
|
||||
|
||||
/**
|
||||
* Stores a group.
|
||||
@@ -121,7 +78,7 @@ public interface DatabaseComponent {
|
||||
* Stores a local message.
|
||||
*/
|
||||
void addLocalMessage(Transaction txn, Message m, Metadata meta,
|
||||
boolean shared) throws DbException;
|
||||
boolean shared, boolean temporary) throws DbException;
|
||||
|
||||
/**
|
||||
* Stores a pending contact.
|
||||
@@ -448,6 +405,14 @@ public interface DatabaseComponent {
|
||||
*/
|
||||
long getNextSendTime(Transaction txn, ContactId c) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the pending contact with the given ID.
|
||||
* <p/>
|
||||
* Read-only.
|
||||
*/
|
||||
PendingContact getPendingContact(Transaction txn, PendingContactId p)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Returns all pending contacts.
|
||||
* <p/>
|
||||
@@ -463,6 +428,13 @@ public interface DatabaseComponent {
|
||||
*/
|
||||
Settings getSettings(Transaction txn, String namespace) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the versions of the sync protocol supported by the given contact.
|
||||
* <p/>
|
||||
* Read-only.
|
||||
*/
|
||||
List<Byte> getSyncVersions(Transaction txn, ContactId c) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns all transport keys for the given transport.
|
||||
* <p/>
|
||||
@@ -546,6 +518,12 @@ public interface DatabaseComponent {
|
||||
void removePendingContact(Transaction txn, PendingContactId p)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Removes all temporary messages (and all associated state) from the
|
||||
* database.
|
||||
*/
|
||||
void removeTemporaryMessages(Transaction txn) throws DbException;
|
||||
|
||||
/**
|
||||
* Removes a transport (and all associated state) from the database.
|
||||
*/
|
||||
@@ -574,6 +552,11 @@ public interface DatabaseComponent {
|
||||
void setGroupVisibility(Transaction txn, ContactId c, GroupId g,
|
||||
Visibility v) throws DbException;
|
||||
|
||||
/**
|
||||
* Marks the given message as permanent, i.e. not temporary.
|
||||
*/
|
||||
void setMessagePermanent(Transaction txn, MessageId m) throws DbException;
|
||||
|
||||
/**
|
||||
* Marks the given message as shared.
|
||||
*/
|
||||
@@ -604,6 +587,12 @@ public interface DatabaseComponent {
|
||||
void setReorderingWindow(Transaction txn, KeySetId k, TransportId t,
|
||||
long timePeriod, long base, byte[] bitmap) throws DbException;
|
||||
|
||||
/**
|
||||
* Sets the versions of the sync protocol supported by the given contact.
|
||||
*/
|
||||
void setSyncVersions(Transaction txn, ContactId c, List<Byte> supported)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Marks the given transport keys as usable for outgoing streams.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package org.briarproject.bramble.api.db;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
@NotNullByDefault
|
||||
public interface TransactionManager {
|
||||
|
||||
/**
|
||||
* Starts a new transaction and returns an object representing it.
|
||||
* <p/>
|
||||
* This method acquires locks, so it must not be called while holding a
|
||||
* lock.
|
||||
*
|
||||
* @param readOnly true if the transaction will only be used for reading.
|
||||
*/
|
||||
Transaction startTransaction(boolean readOnly) throws DbException;
|
||||
|
||||
/**
|
||||
* Commits a transaction to the database.
|
||||
*/
|
||||
void commitTransaction(Transaction txn) throws DbException;
|
||||
|
||||
/**
|
||||
* Ends a transaction. If the transaction has not been committed,
|
||||
* it will be aborted. If the transaction has been committed,
|
||||
* any events attached to the transaction are broadcast.
|
||||
* The database lock will be released in either case.
|
||||
*/
|
||||
void endTransaction(Transaction txn);
|
||||
|
||||
/**
|
||||
* Runs the given task within a transaction.
|
||||
*/
|
||||
<E extends Exception> void transaction(boolean readOnly,
|
||||
DbRunnable<E> task) throws DbException, E;
|
||||
|
||||
/**
|
||||
* Runs the given task within a transaction and returns the result of the
|
||||
* task.
|
||||
*/
|
||||
<R, E extends Exception> R transactionWithResult(boolean readOnly,
|
||||
DbCallable<R, E> task) throws DbException, E;
|
||||
|
||||
/**
|
||||
* Runs the given task within a transaction and returns the result of the
|
||||
* task, which may be null.
|
||||
*/
|
||||
@Nullable
|
||||
<R, E extends Exception> R transactionWithNullableResult(boolean readOnly,
|
||||
NullableDbCallable<R, E> task) throws DbException, E;
|
||||
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import org.briarproject.bramble.api.data.BdfList;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* An class for managing a particular key agreement listener.
|
||||
* Accepts key agreement connections over a given transport.
|
||||
*/
|
||||
public abstract class KeyAgreementListener {
|
||||
|
||||
|
||||
@@ -22,4 +22,11 @@ public class NullSafety {
|
||||
@Nullable Object b) {
|
||||
if ((a == null) == (b == null)) throw new AssertionError();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the argument is null.
|
||||
*/
|
||||
public static void requireNull(@Nullable Object o) {
|
||||
if (o != null) throw new AssertionError();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.briarproject.bramble.api.plugin;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
import org.briarproject.bramble.api.plugin.simplex.SimplexPlugin;
|
||||
|
||||
/**
|
||||
* An interface for handling connections created by transport plugins.
|
||||
*/
|
||||
@NotNullByDefault
|
||||
public interface ConnectionHandler {
|
||||
|
||||
/**
|
||||
* Handles a connection created by a {@link DuplexPlugin}.
|
||||
*/
|
||||
void handleConnection(DuplexTransportConnection c);
|
||||
|
||||
/**
|
||||
* Handles a reader created by a {@link SimplexPlugin}.
|
||||
*/
|
||||
void handleReader(TransportConnectionReader r);
|
||||
|
||||
/**
|
||||
* Handles a writer created by a {@link SimplexPlugin}.
|
||||
*/
|
||||
void handleWriter(TransportConnectionWriter w);
|
||||
}
|
||||
@@ -1,17 +1,46 @@
|
||||
package org.briarproject.bramble.api.plugin;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
|
||||
@NotNullByDefault
|
||||
public interface ConnectionManager {
|
||||
|
||||
/**
|
||||
* Manages an incoming connection from a contact over a simplex transport.
|
||||
*/
|
||||
void manageIncomingConnection(TransportId t, TransportConnectionReader r);
|
||||
|
||||
/**
|
||||
* Manages an incoming connection from a contact over a duplex transport.
|
||||
*/
|
||||
void manageIncomingConnection(TransportId t, DuplexTransportConnection d);
|
||||
|
||||
/**
|
||||
* Manages an incoming handshake connection from a pending contact over a
|
||||
* duplex transport.
|
||||
*/
|
||||
void manageIncomingConnection(PendingContactId p, TransportId t,
|
||||
DuplexTransportConnection d);
|
||||
|
||||
/**
|
||||
* Manages an outgoing connection to a contact over a simplex transport.
|
||||
*/
|
||||
void manageOutgoingConnection(ContactId c, TransportId t,
|
||||
TransportConnectionWriter w);
|
||||
|
||||
/**
|
||||
* Manages an outgoing connection to a contact over a duplex transport.
|
||||
*/
|
||||
void manageOutgoingConnection(ContactId c, TransportId t,
|
||||
DuplexTransportConnection d);
|
||||
|
||||
/**
|
||||
* Manages an outgoing handshake connection to a pending contact over a
|
||||
* duplex transport.
|
||||
*/
|
||||
void manageOutgoingConnection(PendingContactId p, TransportId t,
|
||||
DuplexTransportConnection d);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
package org.briarproject.bramble.api.plugin;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.event.ConnectionClosedEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.ConnectionOpenedEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.ContactConnectedEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.ContactDisconnectedEvent;
|
||||
import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionClosedEvent;
|
||||
import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionOpenedEvent;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
@@ -11,13 +18,50 @@ import java.util.Collection;
|
||||
@NotNullByDefault
|
||||
public interface ConnectionRegistry {
|
||||
|
||||
/**
|
||||
* Registers a connection with the given contact over the given transport.
|
||||
* Broadcasts {@link ConnectionOpenedEvent}. Also broadcasts
|
||||
* {@link ContactConnectedEvent} if this is the only connection with the
|
||||
* contact.
|
||||
*/
|
||||
void registerConnection(ContactId c, TransportId t, boolean incoming);
|
||||
|
||||
/**
|
||||
* Unregisters a connection with the given contact over the given transport.
|
||||
* Broadcasts {@link ConnectionClosedEvent}. Also broadcasts
|
||||
* {@link ContactDisconnectedEvent} if this is the only connection with
|
||||
* the contact.
|
||||
*/
|
||||
void unregisterConnection(ContactId c, TransportId t, boolean incoming);
|
||||
|
||||
/**
|
||||
* Returns any contacts that are connected via the given transport.
|
||||
*/
|
||||
Collection<ContactId> getConnectedContacts(TransportId t);
|
||||
|
||||
/**
|
||||
* Returns true if the given contact is connected via the given transport.
|
||||
*/
|
||||
boolean isConnected(ContactId c, TransportId t);
|
||||
|
||||
/**
|
||||
* Returns true if the given contact is connected via any transport.
|
||||
*/
|
||||
boolean isConnected(ContactId c);
|
||||
|
||||
/**
|
||||
* Registers a connection with the given pending contact. Broadcasts
|
||||
* {@link RendezvousConnectionOpenedEvent} if this is the only connection
|
||||
* with the pending contact.
|
||||
*
|
||||
* @return True if this is the only connection with the pending contact,
|
||||
* false if it is redundant and should be closed
|
||||
*/
|
||||
boolean registerConnection(PendingContactId p);
|
||||
|
||||
/**
|
||||
* Unregisters a connection with the given pending contact. Broadcasts
|
||||
* {@link RendezvousConnectionClosedEvent}.
|
||||
*/
|
||||
void unregisterConnection(PendingContactId p, boolean success);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package org.briarproject.bramble.api.plugin;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.Pair;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Collection;
|
||||
|
||||
@NotNullByDefault
|
||||
public interface Plugin {
|
||||
@@ -51,8 +51,9 @@ public interface Plugin {
|
||||
int getPollingInterval();
|
||||
|
||||
/**
|
||||
* Attempts to establish connections to the given contacts, passing any
|
||||
* created connections to the callback.
|
||||
* Attempts to create connections using the given transport properties,
|
||||
* passing any created connections to the corresponding handlers.
|
||||
*/
|
||||
void poll(Map<ContactId, TransportProperties> contacts);
|
||||
void poll(Collection<Pair<TransportProperties, ConnectionHandler>>
|
||||
properties);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import org.briarproject.bramble.api.settings.Settings;
|
||||
* the application.
|
||||
*/
|
||||
@NotNullByDefault
|
||||
public interface PluginCallback {
|
||||
public interface PluginCallback extends ConnectionHandler {
|
||||
|
||||
/**
|
||||
* Returns the plugin's settings
|
||||
|
||||
@@ -36,4 +36,9 @@ public interface PluginManager {
|
||||
* Returns any duplex plugins that support key agreement.
|
||||
*/
|
||||
Collection<DuplexPlugin> getKeyAgreementPlugins();
|
||||
|
||||
/**
|
||||
* Returns any duplex plugins that support rendezvous.
|
||||
*/
|
||||
Collection<DuplexPlugin> getRendezvousPlugins();
|
||||
}
|
||||
|
||||
@@ -3,8 +3,11 @@ package org.briarproject.bramble.api.plugin.duplex;
|
||||
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.ConnectionHandler;
|
||||
import org.briarproject.bramble.api.plugin.Plugin;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.rendezvous.KeyMaterialSource;
|
||||
import org.briarproject.bramble.api.rendezvous.RendezvousEndpoint;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
@@ -40,4 +43,19 @@ public interface DuplexPlugin extends Plugin {
|
||||
@Nullable
|
||||
DuplexTransportConnection createKeyAgreementConnection(
|
||||
byte[] remoteCommitment, BdfList descriptor);
|
||||
|
||||
/**
|
||||
* Returns true if the plugin supports rendezvous connections.
|
||||
*/
|
||||
boolean supportsRendezvous();
|
||||
|
||||
/**
|
||||
* Creates and returns an endpoint that uses the given key material to
|
||||
* rendezvous with a pending contact, and the given connection handler to
|
||||
* handle incoming connections. Returns null if an endpoint cannot be
|
||||
* created.
|
||||
*/
|
||||
@Nullable
|
||||
RendezvousEndpoint createRendezvousEndpoint(KeyMaterialSource k,
|
||||
boolean alice, ConnectionHandler incoming);
|
||||
}
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
package org.briarproject.bramble.api.plugin.duplex;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
|
||||
/**
|
||||
* An interface through which a duplex plugin interacts with the rest of the
|
||||
* application.
|
||||
*/
|
||||
@NotNullByDefault
|
||||
public interface DuplexPluginCallback extends PluginCallback {
|
||||
|
||||
void incomingConnectionCreated(DuplexTransportConnection d);
|
||||
|
||||
void outgoingConnectionCreated(ContactId c, DuplexTransportConnection d);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.briarproject.bramble.api.plugin.duplex;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
@@ -25,5 +26,5 @@ public interface DuplexPluginFactory {
|
||||
* Creates and returns a plugin, or null if no plugin can be created.
|
||||
*/
|
||||
@Nullable
|
||||
DuplexPlugin createPlugin(DuplexPluginCallback callback);
|
||||
DuplexPlugin createPlugin(PluginCallback callback);
|
||||
}
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
package org.briarproject.bramble.api.plugin.simplex;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
|
||||
|
||||
/**
|
||||
* An interface through which a simplex plugin interacts with the rest of the
|
||||
* application.
|
||||
*/
|
||||
@NotNullByDefault
|
||||
public interface SimplexPluginCallback extends PluginCallback {
|
||||
|
||||
void readerCreated(TransportConnectionReader r);
|
||||
|
||||
void writerCreated(ContactId c, TransportConnectionWriter w);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.briarproject.bramble.api.plugin.simplex;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
@@ -25,5 +26,5 @@ public interface SimplexPluginFactory {
|
||||
* Creates and returns a plugin, or null if no plugin can be created.
|
||||
*/
|
||||
@Nullable
|
||||
SimplexPlugin createPlugin(SimplexPluginCallback callback);
|
||||
SimplexPlugin createPlugin(PluginCallback callback);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package org.briarproject.bramble.api.record;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.Predicate;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
@NotNullByDefault
|
||||
public interface RecordReader {
|
||||
|
||||
@@ -16,5 +20,20 @@ public interface RecordReader {
|
||||
*/
|
||||
Record readRecord() throws IOException;
|
||||
|
||||
/**
|
||||
* Reads and returns the next record matching the 'accept' predicate,
|
||||
* skipping any records that match the 'ignore' predicate. Returns null if
|
||||
* no record matching the 'accept' predicate is found before the end of the
|
||||
* stream.
|
||||
*
|
||||
* @throws EOFException If the end of the stream is reached without
|
||||
* reading a complete record
|
||||
* @throws FormatException If a record is read that does not match the
|
||||
* 'accept' or 'ignore' predicates
|
||||
*/
|
||||
@Nullable
|
||||
Record readRecord(Predicate<Record> accept, Predicate<Record> ignore)
|
||||
throws IOException;
|
||||
|
||||
void close() throws IOException;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.briarproject.bramble.api.rendezvous;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
/**
|
||||
* A source of key material for use in making rendezvous connections.
|
||||
*/
|
||||
@NotNullByDefault
|
||||
public interface KeyMaterialSource {
|
||||
|
||||
/**
|
||||
* Returns the requested amount of key material.
|
||||
*/
|
||||
byte[] getKeyMaterial(int length);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.briarproject.bramble.api.rendezvous;
|
||||
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* An interface for making and accepting rendezvous connections with a pending
|
||||
* contact over a given transport.
|
||||
*/
|
||||
public interface RendezvousEndpoint extends Closeable {
|
||||
|
||||
/**
|
||||
* Returns a set of transport properties for connecting to the pending
|
||||
* contact.
|
||||
*/
|
||||
TransportProperties getRemoteTransportProperties();
|
||||
|
||||
/**
|
||||
* Closes the handler and releases any resources held by it, such as
|
||||
* network sockets.
|
||||
*/
|
||||
@Override
|
||||
void close() throws IOException;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package org.briarproject.bramble.api.rendezvous;
|
||||
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
|
||||
/**
|
||||
* Interface for the poller that makes rendezvous connections to pending
|
||||
* contacts.
|
||||
*/
|
||||
public interface RendezvousPoller {
|
||||
|
||||
long getLastPollTime(PendingContactId p);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package org.briarproject.bramble.api.rendezvous.event;
|
||||
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* An event that is broadcast when a rendezvous connection is closed.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class RendezvousConnectionClosedEvent extends Event {
|
||||
|
||||
private final PendingContactId pendingContactId;
|
||||
private final boolean success;
|
||||
|
||||
public RendezvousConnectionClosedEvent(PendingContactId pendingContactId,
|
||||
boolean success) {
|
||||
this.pendingContactId = pendingContactId;
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
public PendingContactId getPendingContactId() {
|
||||
return pendingContactId;
|
||||
}
|
||||
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.briarproject.bramble.api.rendezvous.event;
|
||||
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* An event that is broadcast when a rendezvous connection is opened.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class RendezvousConnectionOpenedEvent extends Event {
|
||||
|
||||
private final PendingContactId pendingContactId;
|
||||
|
||||
public RendezvousConnectionOpenedEvent(PendingContactId pendingContactId) {
|
||||
this.pendingContactId = pendingContactId;
|
||||
}
|
||||
|
||||
public PendingContactId getPendingContactId() {
|
||||
return pendingContactId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package org.briarproject.bramble.api.rendezvous.event;
|
||||
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* An event that is broadcast when a transport plugin is polled for connections
|
||||
* to one or more pending contacts.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class RendezvousPollEvent extends Event {
|
||||
|
||||
private final TransportId transportId;
|
||||
private final Collection<PendingContactId> pendingContacts;
|
||||
|
||||
public RendezvousPollEvent(TransportId transportId,
|
||||
Collection<PendingContactId> pendingContacts) {
|
||||
this.transportId = transportId;
|
||||
this.pendingContacts = pendingContacts;
|
||||
}
|
||||
|
||||
public TransportId getTransportId() {
|
||||
return transportId;
|
||||
}
|
||||
|
||||
public Collection<PendingContactId> getPendingContacts() {
|
||||
return pendingContacts;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
package org.briarproject.bramble.api.sync;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* A record acknowledging receipt of one or more {@link Message Messages}.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class Ack {
|
||||
|
||||
private final Collection<MessageId> acked;
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
package org.briarproject.bramble.api.sync;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_BODY_LENGTH;
|
||||
import static org.briarproject.bramble.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH;
|
||||
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class Message {
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
package org.briarproject.bramble.api.sync;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* A record offering the recipient one or more {@link Message Messages}.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class Offer {
|
||||
|
||||
private final Collection<MessageId> offered;
|
||||
|
||||
@@ -9,5 +9,5 @@ public interface RecordTypes {
|
||||
byte MESSAGE = 1;
|
||||
byte OFFER = 2;
|
||||
byte REQUEST = 3;
|
||||
|
||||
byte VERSIONS = 4;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
package org.briarproject.bramble.api.sync;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* A record requesting one or more {@link Message Messages} from the recipient.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class Request {
|
||||
|
||||
private final Collection<MessageId> requested;
|
||||
|
||||
@@ -2,6 +2,9 @@ package org.briarproject.bramble.api.sync;
|
||||
|
||||
import org.briarproject.bramble.api.UniqueId;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static java.util.Collections.singletonList;
|
||||
import static org.briarproject.bramble.api.record.Record.MAX_RECORD_PAYLOAD_BYTES;
|
||||
|
||||
public interface SyncConstants {
|
||||
@@ -11,6 +14,11 @@ public interface SyncConstants {
|
||||
*/
|
||||
byte PROTOCOL_VERSION = 0;
|
||||
|
||||
/**
|
||||
* The versions of the sync protocol this peer supports.
|
||||
*/
|
||||
List<Byte> SUPPORTED_VERSIONS = singletonList(PROTOCOL_VERSION);
|
||||
|
||||
/**
|
||||
* The maximum length of a group descriptor in bytes.
|
||||
*/
|
||||
@@ -35,4 +43,10 @@ public interface SyncConstants {
|
||||
* The maximum number of message IDs in an ack, offer or request record.
|
||||
*/
|
||||
int MAX_MESSAGE_IDS = MAX_RECORD_PAYLOAD_BYTES / UniqueId.LENGTH;
|
||||
|
||||
/**
|
||||
* The maximum number of versions of the sync protocol a peer may support
|
||||
* simultaneously.
|
||||
*/
|
||||
int MAX_SUPPORTED_VERSIONS = 10;
|
||||
}
|
||||
|
||||
@@ -25,4 +25,7 @@ public interface SyncRecordReader {
|
||||
|
||||
Request readRequest() throws IOException;
|
||||
|
||||
boolean hasVersions() throws IOException;
|
||||
|
||||
Versions readVersions() throws IOException;
|
||||
}
|
||||
|
||||
@@ -15,5 +15,7 @@ public interface SyncRecordWriter {
|
||||
|
||||
void writeRequest(Request r) throws IOException;
|
||||
|
||||
void writeVersions(Versions v) throws IOException;
|
||||
|
||||
void flush() throws IOException;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.briarproject.bramble.api.sync;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* A record telling the recipient which versions of the sync protocol the
|
||||
* sender supports.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class Versions {
|
||||
|
||||
private final List<Byte> supported;
|
||||
|
||||
public Versions(List<Byte> supported) {
|
||||
this.supported = supported;
|
||||
}
|
||||
|
||||
public List<Byte> getSupportedVersions() {
|
||||
return supported;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package org.briarproject.bramble.api.sync.event;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
|
||||
/**
|
||||
* An event that is broadcast when the versions of the sync protocol supported
|
||||
* by a contact are updated.
|
||||
*/
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
public class SyncVersionsUpdatedEvent extends Event {
|
||||
|
||||
private final ContactId contactId;
|
||||
private final List<Byte> supported;
|
||||
|
||||
public SyncVersionsUpdatedEvent(ContactId contactId, List<Byte> supported) {
|
||||
this.contactId = contactId;
|
||||
this.supported = supported;
|
||||
}
|
||||
|
||||
public ContactId getContactId() {
|
||||
return contactId;
|
||||
}
|
||||
|
||||
public List<Byte> getSupportedVersions() {
|
||||
return supported;
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,14 @@ package org.briarproject.bramble.api.transport;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.crypto.KeyPair;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.db.Transaction;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
@@ -18,9 +21,9 @@ import javax.annotation.Nullable;
|
||||
public interface KeyManager {
|
||||
|
||||
/**
|
||||
* Informs the key manager that a new contact has been added. Derives and
|
||||
* stores a set of rotation mode transport keys for communicating with the
|
||||
* contact over each transport and returns the key set IDs.
|
||||
* Derives and stores a set of rotation mode transport keys for
|
||||
* communicating with the given contact over each transport and returns the
|
||||
* key set IDs.
|
||||
* <p/>
|
||||
* {@link StreamContext StreamContexts} for the contact can be created
|
||||
* after this method has returned.
|
||||
@@ -28,7 +31,7 @@ public interface KeyManager {
|
||||
* @param alice True if the local party is Alice
|
||||
* @param active Whether the derived keys can be used for outgoing streams
|
||||
*/
|
||||
Map<TransportId, KeySetId> addContactWithRotationKeys(Transaction txn,
|
||||
Map<TransportId, KeySetId> addRotationKeys(Transaction txn,
|
||||
ContactId c, SecretKey rootKey, long timestamp, boolean alice,
|
||||
boolean active) throws DbException;
|
||||
|
||||
@@ -39,11 +42,10 @@ public interface KeyManager {
|
||||
* <p/>
|
||||
* {@link StreamContext StreamContexts} for the contact can be created
|
||||
* after this method has returned.
|
||||
*
|
||||
* @param alice True if the local party is Alice
|
||||
*/
|
||||
Map<TransportId, KeySetId> addContactWithHandshakeKeys(Transaction txn,
|
||||
ContactId c, SecretKey rootKey, boolean alice) throws DbException;
|
||||
Map<TransportId, KeySetId> addContact(Transaction txn, ContactId c,
|
||||
PublicKey theirPublicKey, KeyPair ourKeyPair)
|
||||
throws DbException, GeneralSecurityException;
|
||||
|
||||
/**
|
||||
* Informs the key manager that a new pending contact has been added.
|
||||
@@ -53,12 +55,10 @@ public interface KeyManager {
|
||||
* <p/>
|
||||
* {@link StreamContext StreamContexts} for the pending contact can be
|
||||
* created after this method has returned.
|
||||
*
|
||||
* @param alice True if the local party is Alice
|
||||
*/
|
||||
Map<TransportId, KeySetId> addPendingContact(Transaction txn,
|
||||
PendingContactId p, SecretKey rootKey, boolean alice)
|
||||
throws DbException;
|
||||
PendingContactId p, PublicKey theirPublicKey, KeyPair ourKeyPair)
|
||||
throws DbException, GeneralSecurityException;
|
||||
|
||||
/**
|
||||
* Marks the given transport keys as usable for outgoing streams.
|
||||
|
||||
@@ -63,14 +63,6 @@ public interface TransportConstants {
|
||||
int MAX_PAYLOAD_LENGTH = MAX_FRAME_LENGTH - FRAME_HEADER_LENGTH
|
||||
- MAC_LENGTH;
|
||||
|
||||
/**
|
||||
* The minimum stream length in bytes that all transport plugins must
|
||||
* support. Streams may be shorter than this length, but all transport
|
||||
* plugins must support streams of at least this length.
|
||||
*/
|
||||
int MIN_STREAM_LENGTH = STREAM_HEADER_LENGTH + FRAME_HEADER_LENGTH
|
||||
+ MAC_LENGTH;
|
||||
|
||||
/**
|
||||
* The maximum difference in milliseconds between two peers' clocks.
|
||||
*/
|
||||
@@ -81,6 +73,26 @@ public interface TransportConstants {
|
||||
*/
|
||||
int REORDERING_WINDOW_SIZE = 32;
|
||||
|
||||
/**
|
||||
* Label for deriving the static master key from handshake key pairs.
|
||||
*/
|
||||
String STATIC_MASTER_KEY_LABEL =
|
||||
"org.briarproject.bramble.transport/STATIC_MASTER_KEY";
|
||||
|
||||
/**
|
||||
* Label for deriving the handshake mode root key for a pending contact
|
||||
* from the static master key.
|
||||
*/
|
||||
String PENDING_CONTACT_ROOT_KEY_LABEL =
|
||||
"org.briarproject.bramble.transport/PENDING_CONTACT_ROOT_KEY";
|
||||
|
||||
/**
|
||||
* Label for deriving the handshake mode root key for a contact from the
|
||||
* static master key.
|
||||
*/
|
||||
String CONTACT_ROOT_KEY_LABEL =
|
||||
"org.briarproject.bramble.transport/CONTACT_ROOT_KEY";
|
||||
|
||||
/**
|
||||
* Label for deriving Alice's initial tag key from the root key in
|
||||
* rotation mode.
|
||||
|
||||
@@ -5,7 +5,6 @@ import org.briarproject.bramble.api.contact.Contact;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.contact.PendingContact;
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.contact.PendingContactState;
|
||||
import org.briarproject.bramble.api.crypto.AgreementPrivateKey;
|
||||
import org.briarproject.bramble.api.crypto.AgreementPublicKey;
|
||||
import org.briarproject.bramble.api.crypto.PrivateKey;
|
||||
@@ -181,10 +180,7 @@ public class TestUtils {
|
||||
PendingContactId id = new PendingContactId(getRandomId());
|
||||
PublicKey publicKey = getAgreementPublicKey();
|
||||
String alias = getRandomString(nameLength);
|
||||
int stateIndex =
|
||||
random.nextInt(PendingContactState.values().length - 1);
|
||||
PendingContactState state = PendingContactState.values()[stateIndex];
|
||||
return new PendingContact(id, publicKey, alias, state, timestamp);
|
||||
return new PendingContact(id, publicKey, alias, timestamp);
|
||||
}
|
||||
|
||||
public static ContactId getContactId() {
|
||||
|
||||
@@ -7,7 +7,7 @@ import org.briarproject.bramble.identity.IdentityModule;
|
||||
import org.briarproject.bramble.lifecycle.LifecycleModule;
|
||||
import org.briarproject.bramble.plugin.PluginModule;
|
||||
import org.briarproject.bramble.properties.PropertiesModule;
|
||||
import org.briarproject.bramble.reporting.ReportingModule;
|
||||
import org.briarproject.bramble.rendezvous.RendezvousModule;
|
||||
import org.briarproject.bramble.sync.validation.ValidationModule;
|
||||
import org.briarproject.bramble.system.SystemModule;
|
||||
import org.briarproject.bramble.transport.TransportModule;
|
||||
@@ -29,7 +29,7 @@ public interface BrambleCoreEagerSingletons {
|
||||
|
||||
void inject(PropertiesModule.EagerSingletons init);
|
||||
|
||||
void inject(ReportingModule.EagerSingletons init);
|
||||
void inject(RendezvousModule.EagerSingletons init);
|
||||
|
||||
void inject(SystemModule.EagerSingletons init);
|
||||
|
||||
@@ -38,4 +38,19 @@ public interface BrambleCoreEagerSingletons {
|
||||
void inject(ValidationModule.EagerSingletons init);
|
||||
|
||||
void inject(VersioningModule.EagerSingletons init);
|
||||
|
||||
default void injectBrambleCoreEagerSingletons() {
|
||||
inject(new ContactModule.EagerSingletons());
|
||||
inject(new CryptoExecutorModule.EagerSingletons());
|
||||
inject(new DatabaseExecutorModule.EagerSingletons());
|
||||
inject(new IdentityModule.EagerSingletons());
|
||||
inject(new LifecycleModule.EagerSingletons());
|
||||
inject(new RendezvousModule.EagerSingletons());
|
||||
inject(new PluginModule.EagerSingletons());
|
||||
inject(new PropertiesModule.EagerSingletons());
|
||||
inject(new SystemModule.EagerSingletons());
|
||||
inject(new TransportModule.EagerSingletons());
|
||||
inject(new ValidationModule.EagerSingletons());
|
||||
inject(new VersioningModule.EagerSingletons());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,9 +15,8 @@ import org.briarproject.bramble.plugin.PluginModule;
|
||||
import org.briarproject.bramble.properties.PropertiesModule;
|
||||
import org.briarproject.bramble.record.RecordModule;
|
||||
import org.briarproject.bramble.reliability.ReliabilityModule;
|
||||
import org.briarproject.bramble.reporting.ReportingModule;
|
||||
import org.briarproject.bramble.rendezvous.RendezvousModule;
|
||||
import org.briarproject.bramble.settings.SettingsModule;
|
||||
import org.briarproject.bramble.socks.SocksModule;
|
||||
import org.briarproject.bramble.sync.SyncModule;
|
||||
import org.briarproject.bramble.sync.validation.ValidationModule;
|
||||
import org.briarproject.bramble.system.SystemModule;
|
||||
@@ -42,9 +41,8 @@ import dagger.Module;
|
||||
PropertiesModule.class,
|
||||
RecordModule.class,
|
||||
ReliabilityModule.class,
|
||||
ReportingModule.class,
|
||||
RendezvousModule.class,
|
||||
SettingsModule.class,
|
||||
SocksModule.class,
|
||||
SyncModule.class,
|
||||
SystemModule.class,
|
||||
TransportModule.class,
|
||||
@@ -54,17 +52,6 @@ import dagger.Module;
|
||||
public class BrambleCoreModule {
|
||||
|
||||
public static void initEagerSingletons(BrambleCoreEagerSingletons c) {
|
||||
c.inject(new ContactModule.EagerSingletons());
|
||||
c.inject(new CryptoExecutorModule.EagerSingletons());
|
||||
c.inject(new DatabaseExecutorModule.EagerSingletons());
|
||||
c.inject(new IdentityModule.EagerSingletons());
|
||||
c.inject(new LifecycleModule.EagerSingletons());
|
||||
c.inject(new PluginModule.EagerSingletons());
|
||||
c.inject(new PropertiesModule.EagerSingletons());
|
||||
c.inject(new ReportingModule.EagerSingletons());
|
||||
c.inject(new SystemModule.EagerSingletons());
|
||||
c.inject(new TransportModule.EagerSingletons());
|
||||
c.inject(new ValidationModule.EagerSingletons());
|
||||
c.inject(new VersioningModule.EagerSingletons());
|
||||
c.injectBrambleCoreEagerSingletons();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,14 +85,21 @@ class ClientHelperImpl implements ClientHelper {
|
||||
@Override
|
||||
public void addLocalMessage(Message m, BdfDictionary metadata,
|
||||
boolean shared) throws DbException, FormatException {
|
||||
db.transaction(false, txn -> addLocalMessage(txn, m, metadata, shared));
|
||||
db.transaction(false, txn -> addLocalMessage(txn, m, metadata, shared,
|
||||
false));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addLocalMessage(Transaction txn, Message m,
|
||||
BdfDictionary metadata, boolean shared)
|
||||
BdfDictionary metadata, boolean shared, boolean temporary)
|
||||
throws DbException, FormatException {
|
||||
db.addLocalMessage(txn, m, metadataEncoder.encode(metadata), shared);
|
||||
db.addLocalMessage(txn, m, metadataEncoder.encode(metadata), shared,
|
||||
temporary);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Message createMessage(GroupId g, long timestamp, byte[] body) {
|
||||
return messageFactory.createMessage(g, timestamp, body);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.briarproject.bramble.client;
|
||||
|
||||
import org.briarproject.bramble.api.Bytes;
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.client.ClientHelper;
|
||||
import org.briarproject.bramble.api.client.ContactGroupFactory;
|
||||
@@ -55,7 +54,7 @@ class ContactGroupFactoryImpl implements ContactGroupFactory {
|
||||
|
||||
private byte[] createGroupDescriptor(AuthorId local, AuthorId remote) {
|
||||
try {
|
||||
if (Bytes.COMPARATOR.compare(local, remote) < 0)
|
||||
if (local.compareTo(remote) < 0)
|
||||
return clientHelper.toByteArray(BdfList.of(local, remote));
|
||||
else return clientHelper.toByteArray(BdfList.of(remote, local));
|
||||
} catch (FormatException e) {
|
||||
|
||||
@@ -1,16 +1,6 @@
|
||||
package org.briarproject.bramble.api.contact;
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.identity.LocalAuthor;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
|
||||
|
||||
/**
|
||||
* A task for conducting a contact information exchange with a remote peer.
|
||||
*/
|
||||
@NotNullByDefault
|
||||
public interface ContactExchangeTask {
|
||||
interface ContactExchangeConstants {
|
||||
|
||||
/**
|
||||
* The current version of the contact exchange protocol.
|
||||
@@ -39,9 +29,7 @@ public interface ContactExchangeTask {
|
||||
String BOB_NONCE_LABEL = "org.briarproject.bramble.contact/BOB_NONCE";
|
||||
|
||||
/**
|
||||
* Exchanges contact information with a remote peer.
|
||||
* Label for signing key binding nonces.
|
||||
*/
|
||||
void startExchange(LocalAuthor localAuthor, SecretKey masterKey,
|
||||
DuplexTransportConnection conn, TransportId transportId,
|
||||
boolean alice);
|
||||
String SIGNING_LABEL = "org.briarproject.briar.contact/EXCHANGE";
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.PrivateKey;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
@NotNullByDefault
|
||||
interface ContactExchangeCrypto {
|
||||
|
||||
/**
|
||||
* Derives the header key for a contact exchange stream from the master key.
|
||||
*
|
||||
* @param alice Whether the header key is for the stream sent by Alice
|
||||
*/
|
||||
SecretKey deriveHeaderKey(SecretKey masterKey, boolean alice);
|
||||
|
||||
/**
|
||||
* Creates and returns a signature that proves ownership of a pseudonym.
|
||||
*
|
||||
* @param privateKey The pseudonym's signature private key
|
||||
* @param alice Whether the pseudonym belongs to Alice
|
||||
*/
|
||||
byte[] sign(PrivateKey privateKey, SecretKey masterKey, boolean alice);
|
||||
|
||||
/**
|
||||
* Verifies a signature that proves ownership of a pseudonym.
|
||||
*
|
||||
* @param publicKey The pseudonym's signature public key
|
||||
* @param alice Whether the pseudonym belongs to Alice
|
||||
* @return True if the signature is valid
|
||||
*/
|
||||
boolean verify(PublicKey publicKey, SecretKey masterKey, boolean alice,
|
||||
byte[] signature);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.CryptoComponent;
|
||||
import org.briarproject.bramble.api.crypto.PrivateKey;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static org.briarproject.bramble.contact.ContactExchangeConstants.ALICE_KEY_LABEL;
|
||||
import static org.briarproject.bramble.contact.ContactExchangeConstants.ALICE_NONCE_LABEL;
|
||||
import static org.briarproject.bramble.contact.ContactExchangeConstants.BOB_KEY_LABEL;
|
||||
import static org.briarproject.bramble.contact.ContactExchangeConstants.BOB_NONCE_LABEL;
|
||||
import static org.briarproject.bramble.contact.ContactExchangeConstants.PROTOCOL_VERSION;
|
||||
import static org.briarproject.bramble.contact.ContactExchangeConstants.SIGNING_LABEL;
|
||||
|
||||
@NotNullByDefault
|
||||
class ContactExchangeCryptoImpl implements ContactExchangeCrypto {
|
||||
|
||||
private static final byte[] PROTOCOL_VERSION_BYTES =
|
||||
new byte[] {PROTOCOL_VERSION};
|
||||
|
||||
private final CryptoComponent crypto;
|
||||
|
||||
@Inject
|
||||
ContactExchangeCryptoImpl(CryptoComponent crypto) {
|
||||
this.crypto = crypto;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SecretKey deriveHeaderKey(SecretKey masterKey, boolean alice) {
|
||||
String label = alice ? ALICE_KEY_LABEL : BOB_KEY_LABEL;
|
||||
return crypto.deriveKey(label, masterKey, PROTOCOL_VERSION_BYTES);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] sign(PrivateKey privateKey, SecretKey masterKey,
|
||||
boolean alice) {
|
||||
byte[] nonce = deriveNonce(masterKey, alice);
|
||||
try {
|
||||
return crypto.sign(SIGNING_LABEL, nonce, privateKey);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new AssertionError();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(PublicKey publicKey,
|
||||
SecretKey masterKey, boolean alice, byte[] signature) {
|
||||
byte[] nonce = deriveNonce(masterKey, alice);
|
||||
try {
|
||||
return crypto.verifySignature(signature, SIGNING_LABEL, nonce,
|
||||
publicKey);
|
||||
} catch (GeneralSecurityException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] deriveNonce(SecretKey masterKey, boolean alice) {
|
||||
String label = alice ? ALICE_NONCE_LABEL : BOB_NONCE_LABEL;
|
||||
return crypto.mac(label, masterKey, PROTOCOL_VERSION_BYTES);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.Predicate;
|
||||
import org.briarproject.bramble.api.client.ClientHelper;
|
||||
import org.briarproject.bramble.api.contact.Contact;
|
||||
import org.briarproject.bramble.api.contact.ContactExchangeManager;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.contact.ContactManager;
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.data.BdfDictionary;
|
||||
import org.briarproject.bramble.api.data.BdfList;
|
||||
import org.briarproject.bramble.api.db.DatabaseComponent;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.db.Transaction;
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
import org.briarproject.bramble.api.identity.IdentityManager;
|
||||
import org.briarproject.bramble.api.identity.LocalAuthor;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
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.record.Record;
|
||||
import org.briarproject.bramble.api.record.RecordReader;
|
||||
import org.briarproject.bramble.api.record.RecordReaderFactory;
|
||||
import org.briarproject.bramble.api.record.RecordWriter;
|
||||
import org.briarproject.bramble.api.record.RecordWriterFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.api.transport.StreamReaderFactory;
|
||||
import org.briarproject.bramble.api.transport.StreamWriter;
|
||||
import org.briarproject.bramble.api.transport.StreamWriterFactory;
|
||||
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_SIGNATURE_LENGTH;
|
||||
import static org.briarproject.bramble.contact.ContactExchangeConstants.PROTOCOL_VERSION;
|
||||
import static org.briarproject.bramble.contact.ContactExchangeRecordTypes.CONTACT_INFO;
|
||||
import static org.briarproject.bramble.util.ValidationUtils.checkLength;
|
||||
import static org.briarproject.bramble.util.ValidationUtils.checkSize;
|
||||
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
class ContactExchangeManagerImpl implements ContactExchangeManager {
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(ContactExchangeManagerImpl.class.getName());
|
||||
|
||||
// Accept records with current protocol version, known record type
|
||||
private static final Predicate<Record> ACCEPT = r ->
|
||||
r.getProtocolVersion() == PROTOCOL_VERSION &&
|
||||
isKnownRecordType(r.getRecordType());
|
||||
|
||||
// Ignore records with current protocol version, unknown record type
|
||||
private static final Predicate<Record> IGNORE = r ->
|
||||
r.getProtocolVersion() == PROTOCOL_VERSION &&
|
||||
!isKnownRecordType(r.getRecordType());
|
||||
|
||||
private static boolean isKnownRecordType(byte type) {
|
||||
return type == CONTACT_INFO;
|
||||
}
|
||||
|
||||
private final DatabaseComponent db;
|
||||
private final ClientHelper clientHelper;
|
||||
private final RecordReaderFactory recordReaderFactory;
|
||||
private final RecordWriterFactory recordWriterFactory;
|
||||
private final Clock clock;
|
||||
private final ContactManager contactManager;
|
||||
private final IdentityManager identityManager;
|
||||
private final TransportPropertyManager transportPropertyManager;
|
||||
private final ContactExchangeCrypto contactExchangeCrypto;
|
||||
private final StreamReaderFactory streamReaderFactory;
|
||||
private final StreamWriterFactory streamWriterFactory;
|
||||
|
||||
@Inject
|
||||
ContactExchangeManagerImpl(DatabaseComponent db, ClientHelper clientHelper,
|
||||
RecordReaderFactory recordReaderFactory,
|
||||
RecordWriterFactory recordWriterFactory, Clock clock,
|
||||
ContactManager contactManager, IdentityManager identityManager,
|
||||
TransportPropertyManager transportPropertyManager,
|
||||
ContactExchangeCrypto contactExchangeCrypto,
|
||||
StreamReaderFactory streamReaderFactory,
|
||||
StreamWriterFactory streamWriterFactory) {
|
||||
this.db = db;
|
||||
this.clientHelper = clientHelper;
|
||||
this.recordReaderFactory = recordReaderFactory;
|
||||
this.recordWriterFactory = recordWriterFactory;
|
||||
this.clock = clock;
|
||||
this.contactManager = contactManager;
|
||||
this.identityManager = identityManager;
|
||||
this.transportPropertyManager = transportPropertyManager;
|
||||
this.contactExchangeCrypto = contactExchangeCrypto;
|
||||
this.streamReaderFactory = streamReaderFactory;
|
||||
this.streamWriterFactory = streamWriterFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Contact exchangeContacts(DuplexTransportConnection conn,
|
||||
SecretKey masterKey, boolean alice,
|
||||
boolean verified) throws IOException, DbException {
|
||||
return exchange(null, conn, masterKey, alice, verified);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Contact exchangeContacts(PendingContactId p,
|
||||
DuplexTransportConnection conn, SecretKey masterKey, boolean alice,
|
||||
boolean verified) throws IOException, DbException {
|
||||
return exchange(p, conn, masterKey, alice, verified);
|
||||
}
|
||||
|
||||
private Contact exchange(@Nullable PendingContactId p,
|
||||
DuplexTransportConnection conn, SecretKey masterKey, boolean alice,
|
||||
boolean verified) throws IOException, DbException {
|
||||
// Get the transport connection's input and output streams
|
||||
InputStream in = conn.getReader().getInputStream();
|
||||
OutputStream out = conn.getWriter().getOutputStream();
|
||||
|
||||
// Get the local author and transport properties
|
||||
LocalAuthor localAuthor = identityManager.getLocalAuthor();
|
||||
Map<TransportId, TransportProperties> localProperties =
|
||||
transportPropertyManager.getLocalProperties();
|
||||
|
||||
// Derive the header keys for the transport streams
|
||||
SecretKey localHeaderKey =
|
||||
contactExchangeCrypto.deriveHeaderKey(masterKey, alice);
|
||||
SecretKey remoteHeaderKey =
|
||||
contactExchangeCrypto.deriveHeaderKey(masterKey, !alice);
|
||||
|
||||
// Create the readers
|
||||
InputStream streamReader = streamReaderFactory
|
||||
.createContactExchangeStreamReader(in, remoteHeaderKey);
|
||||
RecordReader recordReader =
|
||||
recordReaderFactory.createRecordReader(streamReader);
|
||||
|
||||
// Create the writers
|
||||
StreamWriter streamWriter = streamWriterFactory
|
||||
.createContactExchangeStreamWriter(out, localHeaderKey);
|
||||
RecordWriter recordWriter = recordWriterFactory
|
||||
.createRecordWriter(streamWriter.getOutputStream());
|
||||
|
||||
// Create our signature
|
||||
byte[] localSignature = contactExchangeCrypto
|
||||
.sign(localAuthor.getPrivateKey(), masterKey, alice);
|
||||
|
||||
// Exchange contact info
|
||||
long localTimestamp = clock.currentTimeMillis();
|
||||
ContactInfo remoteInfo;
|
||||
if (alice) {
|
||||
sendContactInfo(recordWriter, localAuthor, localProperties,
|
||||
localSignature, localTimestamp);
|
||||
remoteInfo = receiveContactInfo(recordReader);
|
||||
} else {
|
||||
remoteInfo = receiveContactInfo(recordReader);
|
||||
sendContactInfo(recordWriter, localAuthor, localProperties,
|
||||
localSignature, localTimestamp);
|
||||
}
|
||||
|
||||
// Send EOF on the outgoing stream
|
||||
streamWriter.sendEndOfStream();
|
||||
|
||||
// Skip any remaining records from the incoming stream
|
||||
recordReader.readRecord(r -> false, IGNORE);
|
||||
|
||||
// Verify the contact's signature
|
||||
PublicKey remotePublicKey = remoteInfo.author.getPublicKey();
|
||||
if (!contactExchangeCrypto.verify(remotePublicKey,
|
||||
masterKey, !alice, remoteInfo.signature)) {
|
||||
LOG.warning("Invalid signature");
|
||||
throw new FormatException();
|
||||
}
|
||||
|
||||
// The agreed timestamp is the minimum of the peers' timestamps
|
||||
long timestamp = Math.min(localTimestamp, remoteInfo.timestamp);
|
||||
|
||||
// Add the contact
|
||||
Contact contact = addContact(p, remoteInfo.author, localAuthor,
|
||||
masterKey, timestamp, alice, verified, remoteInfo.properties);
|
||||
|
||||
// Contact exchange succeeded
|
||||
LOG.info("Contact exchange succeeded");
|
||||
return contact;
|
||||
}
|
||||
|
||||
private void sendContactInfo(RecordWriter recordWriter, Author author,
|
||||
Map<TransportId, TransportProperties> properties, byte[] signature,
|
||||
long timestamp) throws IOException {
|
||||
BdfList authorList = clientHelper.toList(author);
|
||||
BdfDictionary props = clientHelper.toDictionary(properties);
|
||||
BdfList payload = BdfList.of(authorList, props, signature, timestamp);
|
||||
recordWriter.writeRecord(new Record(PROTOCOL_VERSION, CONTACT_INFO,
|
||||
clientHelper.toByteArray(payload)));
|
||||
recordWriter.flush();
|
||||
LOG.info("Sent contact info");
|
||||
}
|
||||
|
||||
private ContactInfo receiveContactInfo(RecordReader recordReader)
|
||||
throws IOException {
|
||||
Record record = recordReader.readRecord(ACCEPT, IGNORE);
|
||||
if (record == null) throw new EOFException();
|
||||
LOG.info("Received contact info");
|
||||
BdfList payload = clientHelper.toList(record.getPayload());
|
||||
checkSize(payload, 4);
|
||||
Author author = clientHelper.parseAndValidateAuthor(payload.getList(0));
|
||||
BdfDictionary props = payload.getDictionary(1);
|
||||
Map<TransportId, TransportProperties> properties =
|
||||
clientHelper.parseAndValidateTransportPropertiesMap(props);
|
||||
byte[] signature = payload.getRaw(2);
|
||||
checkLength(signature, 1, MAX_SIGNATURE_LENGTH);
|
||||
long timestamp = payload.getLong(3);
|
||||
if (timestamp < 0) throw new FormatException();
|
||||
return new ContactInfo(author, properties, signature, timestamp);
|
||||
}
|
||||
|
||||
private Contact addContact(@Nullable PendingContactId pendingContactId,
|
||||
Author remoteAuthor, LocalAuthor localAuthor, SecretKey masterKey,
|
||||
long timestamp, boolean alice, boolean verified,
|
||||
Map<TransportId, TransportProperties> remoteProperties)
|
||||
throws DbException, FormatException {
|
||||
Transaction txn = db.startTransaction(false);
|
||||
try {
|
||||
ContactId contactId;
|
||||
if (pendingContactId == null) {
|
||||
contactId = contactManager.addContact(txn, remoteAuthor,
|
||||
localAuthor.getId(), masterKey, timestamp, alice,
|
||||
verified, true);
|
||||
} else {
|
||||
contactId = contactManager.addContact(txn, pendingContactId,
|
||||
remoteAuthor, localAuthor.getId(), masterKey,
|
||||
timestamp, alice, verified, true);
|
||||
}
|
||||
transportPropertyManager.addRemoteProperties(txn, contactId,
|
||||
remoteProperties);
|
||||
Contact contact = contactManager.getContact(txn, contactId);
|
||||
db.commitTransaction(txn);
|
||||
return contact;
|
||||
} catch (GeneralSecurityException e) {
|
||||
// Pending contact's public key is invalid
|
||||
throw new FormatException();
|
||||
} finally {
|
||||
db.endTransaction(txn);
|
||||
}
|
||||
}
|
||||
|
||||
private static class ContactInfo {
|
||||
|
||||
private final Author author;
|
||||
private final Map<TransportId, TransportProperties> properties;
|
||||
private final byte[] signature;
|
||||
private final long timestamp;
|
||||
|
||||
private ContactInfo(Author author,
|
||||
Map<TransportId, TransportProperties> properties,
|
||||
byte[] signature, long timestamp) {
|
||||
this.author = author;
|
||||
this.properties = properties;
|
||||
this.signature = signature;
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
package org.briarproject.bramble.api.contact;
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
/**
|
||||
* Record types for the contact exchange protocol.
|
||||
*/
|
||||
public interface RecordTypes {
|
||||
interface ContactExchangeRecordTypes {
|
||||
|
||||
byte CONTACT_INFO = 0;
|
||||
}
|
||||
@@ -1,330 +0,0 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.client.ClientHelper;
|
||||
import org.briarproject.bramble.api.contact.ContactExchangeTask;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.contact.ContactManager;
|
||||
import org.briarproject.bramble.api.contact.event.ContactExchangeFailedEvent;
|
||||
import org.briarproject.bramble.api.contact.event.ContactExchangeSucceededEvent;
|
||||
import org.briarproject.bramble.api.crypto.CryptoComponent;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.data.BdfDictionary;
|
||||
import org.briarproject.bramble.api.data.BdfList;
|
||||
import org.briarproject.bramble.api.db.ContactExistsException;
|
||||
import org.briarproject.bramble.api.db.DatabaseComponent;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
import org.briarproject.bramble.api.identity.LocalAuthor;
|
||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.ConnectionManager;
|
||||
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.record.Record;
|
||||
import org.briarproject.bramble.api.record.RecordReader;
|
||||
import org.briarproject.bramble.api.record.RecordReaderFactory;
|
||||
import org.briarproject.bramble.api.record.RecordWriter;
|
||||
import org.briarproject.bramble.api.record.RecordWriterFactory;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.api.transport.StreamReaderFactory;
|
||||
import org.briarproject.bramble.api.transport.StreamWriter;
|
||||
import org.briarproject.bramble.api.transport.StreamWriterFactory;
|
||||
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static org.briarproject.bramble.api.contact.RecordTypes.CONTACT_INFO;
|
||||
import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_SIGNATURE_LENGTH;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
import static org.briarproject.bramble.util.ValidationUtils.checkLength;
|
||||
import static org.briarproject.bramble.util.ValidationUtils.checkSize;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
class ContactExchangeTaskImpl extends Thread implements ContactExchangeTask {
|
||||
|
||||
private static final Logger LOG =
|
||||
Logger.getLogger(ContactExchangeTaskImpl.class.getName());
|
||||
|
||||
private static final String SIGNING_LABEL_EXCHANGE =
|
||||
"org.briarproject.briar.contact/EXCHANGE";
|
||||
|
||||
private final DatabaseComponent db;
|
||||
private final ClientHelper clientHelper;
|
||||
private final RecordReaderFactory recordReaderFactory;
|
||||
private final RecordWriterFactory recordWriterFactory;
|
||||
private final EventBus eventBus;
|
||||
private final Clock clock;
|
||||
private final ConnectionManager connectionManager;
|
||||
private final ContactManager contactManager;
|
||||
private final TransportPropertyManager transportPropertyManager;
|
||||
private final CryptoComponent crypto;
|
||||
private final StreamReaderFactory streamReaderFactory;
|
||||
private final StreamWriterFactory streamWriterFactory;
|
||||
|
||||
private volatile LocalAuthor localAuthor;
|
||||
private volatile DuplexTransportConnection conn;
|
||||
private volatile TransportId transportId;
|
||||
private volatile SecretKey masterKey;
|
||||
private volatile boolean alice;
|
||||
|
||||
@Inject
|
||||
ContactExchangeTaskImpl(DatabaseComponent db, ClientHelper clientHelper,
|
||||
RecordReaderFactory recordReaderFactory,
|
||||
RecordWriterFactory recordWriterFactory, EventBus eventBus,
|
||||
Clock clock, ConnectionManager connectionManager,
|
||||
ContactManager contactManager,
|
||||
TransportPropertyManager transportPropertyManager,
|
||||
CryptoComponent crypto, StreamReaderFactory streamReaderFactory,
|
||||
StreamWriterFactory streamWriterFactory) {
|
||||
this.db = db;
|
||||
this.clientHelper = clientHelper;
|
||||
this.recordReaderFactory = recordReaderFactory;
|
||||
this.recordWriterFactory = recordWriterFactory;
|
||||
this.eventBus = eventBus;
|
||||
this.clock = clock;
|
||||
this.connectionManager = connectionManager;
|
||||
this.contactManager = contactManager;
|
||||
this.transportPropertyManager = transportPropertyManager;
|
||||
this.crypto = crypto;
|
||||
this.streamReaderFactory = streamReaderFactory;
|
||||
this.streamWriterFactory = streamWriterFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startExchange(LocalAuthor localAuthor, SecretKey masterKey,
|
||||
DuplexTransportConnection conn, TransportId transportId,
|
||||
boolean alice) {
|
||||
this.localAuthor = localAuthor;
|
||||
this.conn = conn;
|
||||
this.transportId = transportId;
|
||||
this.masterKey = masterKey;
|
||||
this.alice = alice;
|
||||
start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// Get the transport connection's input and output streams
|
||||
InputStream in;
|
||||
OutputStream out;
|
||||
try {
|
||||
in = conn.getReader().getInputStream();
|
||||
out = conn.getWriter().getOutputStream();
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
tryToClose(conn);
|
||||
eventBus.broadcast(new ContactExchangeFailedEvent());
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the local transport properties
|
||||
Map<TransportId, TransportProperties> localProperties;
|
||||
try {
|
||||
localProperties = transportPropertyManager.getLocalProperties();
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
eventBus.broadcast(new ContactExchangeFailedEvent());
|
||||
tryToClose(conn);
|
||||
return;
|
||||
}
|
||||
|
||||
// Derive the header keys for the transport streams
|
||||
SecretKey aliceHeaderKey = crypto.deriveKey(ALICE_KEY_LABEL, masterKey,
|
||||
new byte[] {PROTOCOL_VERSION});
|
||||
SecretKey bobHeaderKey = crypto.deriveKey(BOB_KEY_LABEL, masterKey,
|
||||
new byte[] {PROTOCOL_VERSION});
|
||||
|
||||
// Create the readers
|
||||
InputStream streamReader =
|
||||
streamReaderFactory.createContactExchangeStreamReader(in,
|
||||
alice ? bobHeaderKey : aliceHeaderKey);
|
||||
RecordReader recordReader =
|
||||
recordReaderFactory.createRecordReader(streamReader);
|
||||
|
||||
// Create the writers
|
||||
StreamWriter streamWriter =
|
||||
streamWriterFactory.createContactExchangeStreamWriter(out,
|
||||
alice ? aliceHeaderKey : bobHeaderKey);
|
||||
RecordWriter recordWriter =
|
||||
recordWriterFactory
|
||||
.createRecordWriter(streamWriter.getOutputStream());
|
||||
|
||||
// Derive the nonces to be signed
|
||||
byte[] aliceNonce = crypto.mac(ALICE_NONCE_LABEL, masterKey,
|
||||
new byte[] {PROTOCOL_VERSION});
|
||||
byte[] bobNonce = crypto.mac(BOB_NONCE_LABEL, masterKey,
|
||||
new byte[] {PROTOCOL_VERSION});
|
||||
byte[] localNonce = alice ? aliceNonce : bobNonce;
|
||||
byte[] remoteNonce = alice ? bobNonce : aliceNonce;
|
||||
|
||||
// Sign the nonce
|
||||
byte[] localSignature = sign(localAuthor, localNonce);
|
||||
|
||||
// Exchange contact info
|
||||
long localTimestamp = clock.currentTimeMillis();
|
||||
ContactInfo remoteInfo;
|
||||
try {
|
||||
if (alice) {
|
||||
sendContactInfo(recordWriter, localAuthor, localProperties,
|
||||
localSignature, localTimestamp);
|
||||
recordWriter.flush();
|
||||
remoteInfo = receiveContactInfo(recordReader);
|
||||
} else {
|
||||
remoteInfo = receiveContactInfo(recordReader);
|
||||
sendContactInfo(recordWriter, localAuthor, localProperties,
|
||||
localSignature, localTimestamp);
|
||||
recordWriter.flush();
|
||||
}
|
||||
// Send EOF on the outgoing stream
|
||||
streamWriter.sendEndOfStream();
|
||||
// Skip any remaining records from the incoming stream
|
||||
try {
|
||||
while (true) recordReader.readRecord();
|
||||
} catch (EOFException expected) {
|
||||
LOG.info("End of stream");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
eventBus.broadcast(new ContactExchangeFailedEvent());
|
||||
tryToClose(conn);
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify the contact's signature
|
||||
if (!verify(remoteInfo.author, remoteNonce, remoteInfo.signature)) {
|
||||
LOG.warning("Invalid signature");
|
||||
eventBus.broadcast(new ContactExchangeFailedEvent());
|
||||
tryToClose(conn);
|
||||
return;
|
||||
}
|
||||
|
||||
// The agreed timestamp is the minimum of the peers' timestamps
|
||||
long timestamp = Math.min(localTimestamp, remoteInfo.timestamp);
|
||||
|
||||
try {
|
||||
// Add the contact
|
||||
ContactId contactId = addContact(remoteInfo.author, timestamp,
|
||||
remoteInfo.properties);
|
||||
// Reuse the connection as a transport connection
|
||||
connectionManager.manageOutgoingConnection(contactId, transportId,
|
||||
conn);
|
||||
// Pseudonym exchange succeeded
|
||||
LOG.info("Pseudonym exchange succeeded");
|
||||
eventBus.broadcast(
|
||||
new ContactExchangeSucceededEvent(remoteInfo.author));
|
||||
} catch (ContactExistsException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
tryToClose(conn);
|
||||
eventBus.broadcast(
|
||||
new ContactExchangeFailedEvent(remoteInfo.author));
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
tryToClose(conn);
|
||||
eventBus.broadcast(new ContactExchangeFailedEvent());
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] sign(LocalAuthor author, byte[] nonce) {
|
||||
try {
|
||||
return crypto.sign(SIGNING_LABEL_EXCHANGE, nonce,
|
||||
author.getPrivateKey());
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new AssertionError();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean verify(Author author, byte[] nonce, byte[] signature) {
|
||||
try {
|
||||
return crypto.verifySignature(signature, SIGNING_LABEL_EXCHANGE,
|
||||
nonce, author.getPublicKey());
|
||||
} catch (GeneralSecurityException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void sendContactInfo(RecordWriter recordWriter, Author author,
|
||||
Map<TransportId, TransportProperties> properties, byte[] signature,
|
||||
long timestamp) throws IOException {
|
||||
BdfList authorList = clientHelper.toList(author);
|
||||
BdfDictionary props = clientHelper.toDictionary(properties);
|
||||
BdfList payload = BdfList.of(authorList, props, signature, timestamp);
|
||||
recordWriter.writeRecord(new Record(PROTOCOL_VERSION, CONTACT_INFO,
|
||||
clientHelper.toByteArray(payload)));
|
||||
LOG.info("Sent contact info");
|
||||
}
|
||||
|
||||
private ContactInfo receiveContactInfo(RecordReader recordReader)
|
||||
throws IOException {
|
||||
Record record;
|
||||
do {
|
||||
record = recordReader.readRecord();
|
||||
if (record.getProtocolVersion() != PROTOCOL_VERSION)
|
||||
throw new FormatException();
|
||||
} while (record.getRecordType() != CONTACT_INFO);
|
||||
LOG.info("Received contact info");
|
||||
BdfList payload = clientHelper.toList(record.getPayload());
|
||||
checkSize(payload, 4);
|
||||
Author author = clientHelper.parseAndValidateAuthor(payload.getList(0));
|
||||
BdfDictionary props = payload.getDictionary(1);
|
||||
Map<TransportId, TransportProperties> properties =
|
||||
clientHelper.parseAndValidateTransportPropertiesMap(props);
|
||||
byte[] signature = payload.getRaw(2);
|
||||
checkLength(signature, 1, MAX_SIGNATURE_LENGTH);
|
||||
long timestamp = payload.getLong(3);
|
||||
if (timestamp < 0) throw new FormatException();
|
||||
return new ContactInfo(author, properties, signature, timestamp);
|
||||
}
|
||||
|
||||
private ContactId addContact(Author remoteAuthor, long timestamp,
|
||||
Map<TransportId, TransportProperties> remoteProperties)
|
||||
throws DbException {
|
||||
return db.transactionWithResult(false, txn -> {
|
||||
ContactId contactId = contactManager.addContact(txn, remoteAuthor,
|
||||
localAuthor.getId(), masterKey, timestamp, alice,
|
||||
true, true);
|
||||
transportPropertyManager.addRemoteProperties(txn, contactId,
|
||||
remoteProperties);
|
||||
return contactId;
|
||||
});
|
||||
}
|
||||
|
||||
private void tryToClose(DuplexTransportConnection conn) {
|
||||
try {
|
||||
LOG.info("Closing connection");
|
||||
conn.getReader().dispose(true, true);
|
||||
conn.getWriter().dispose(true);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static class ContactInfo {
|
||||
|
||||
private final Author author;
|
||||
private final Map<TransportId, TransportProperties> properties;
|
||||
private final byte[] signature;
|
||||
private final long timestamp;
|
||||
|
||||
private ContactInfo(Author author,
|
||||
Map<TransportId, TransportProperties> properties,
|
||||
byte[] signature, long timestamp) {
|
||||
this.author = author;
|
||||
this.properties = properties;
|
||||
this.signature = signature;
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,23 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.Pair;
|
||||
import org.briarproject.bramble.api.contact.Contact;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.contact.ContactManager;
|
||||
import org.briarproject.bramble.api.contact.PendingContact;
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.contact.PendingContactState;
|
||||
import org.briarproject.bramble.api.contact.event.PendingContactStateChangedEvent;
|
||||
import org.briarproject.bramble.api.crypto.KeyPair;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.DatabaseComponent;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.db.NoSuchContactException;
|
||||
import org.briarproject.bramble.api.db.Transaction;
|
||||
import org.briarproject.bramble.api.event.Event;
|
||||
import org.briarproject.bramble.api.event.EventListener;
|
||||
import org.briarproject.bramble.api.identity.Author;
|
||||
import org.briarproject.bramble.api.identity.AuthorId;
|
||||
import org.briarproject.bramble.api.identity.AuthorInfo;
|
||||
@@ -19,45 +26,48 @@ import org.briarproject.bramble.api.identity.LocalAuthor;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.transport.KeyManager;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static org.briarproject.bramble.api.contact.HandshakeLinkConstants.BASE32_LINK_BYTES;
|
||||
import static org.briarproject.bramble.api.contact.PendingContactState.WAITING_FOR_CONNECTION;
|
||||
import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_AUTHOR_NAME_LENGTH;
|
||||
import static org.briarproject.bramble.api.identity.AuthorInfo.Status.OURSELVES;
|
||||
import static org.briarproject.bramble.api.identity.AuthorInfo.Status.UNKNOWN;
|
||||
import static org.briarproject.bramble.api.identity.AuthorInfo.Status.UNVERIFIED;
|
||||
import static org.briarproject.bramble.api.identity.AuthorInfo.Status.VERIFIED;
|
||||
import static org.briarproject.bramble.util.StringUtils.getRandomBase32String;
|
||||
import static org.briarproject.bramble.util.StringUtils.toUtf8;
|
||||
|
||||
@ThreadSafe
|
||||
@NotNullByDefault
|
||||
class ContactManagerImpl implements ContactManager {
|
||||
|
||||
private static final String REMOTE_CONTACT_LINK =
|
||||
"briar://" + getRandomBase32String(BASE32_LINK_BYTES);
|
||||
class ContactManagerImpl implements ContactManager, EventListener {
|
||||
|
||||
private final DatabaseComponent db;
|
||||
private final KeyManager keyManager;
|
||||
private final IdentityManager identityManager;
|
||||
private final PendingContactFactory pendingContactFactory;
|
||||
private final List<ContactHook> hooks;
|
||||
|
||||
private final List<ContactHook> hooks = new CopyOnWriteArrayList<>();
|
||||
private final Map<PendingContactId, PendingContactState> states =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
ContactManagerImpl(DatabaseComponent db, KeyManager keyManager,
|
||||
ContactManagerImpl(DatabaseComponent db,
|
||||
KeyManager keyManager,
|
||||
IdentityManager identityManager,
|
||||
PendingContactFactory pendingContactFactory) {
|
||||
this.db = db;
|
||||
this.keyManager = keyManager;
|
||||
this.identityManager = identityManager;
|
||||
this.pendingContactFactory = pendingContactFactory;
|
||||
hooks = new CopyOnWriteArrayList<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -69,9 +79,29 @@ class ContactManagerImpl implements ContactManager {
|
||||
public ContactId addContact(Transaction txn, Author remote, AuthorId local,
|
||||
SecretKey rootKey, long timestamp, boolean alice, boolean verified,
|
||||
boolean active) throws DbException {
|
||||
ContactId c = db.addContact(txn, remote, local, verified);
|
||||
keyManager.addContactWithRotationKeys(txn, c, rootKey, timestamp,
|
||||
alice, active);
|
||||
ContactId c = db.addContact(txn, remote, local, null, verified);
|
||||
keyManager.addRotationKeys(txn, c, rootKey, timestamp, alice, active);
|
||||
Contact contact = db.getContact(txn, c);
|
||||
for (ContactHook hook : hooks) hook.addingContact(txn, contact);
|
||||
return c;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ContactId addContact(Transaction txn, PendingContactId p,
|
||||
Author remote, AuthorId local, SecretKey rootKey, long timestamp,
|
||||
boolean alice, boolean verified, boolean active)
|
||||
throws DbException, GeneralSecurityException {
|
||||
PendingContact pendingContact = db.getPendingContact(txn, p);
|
||||
db.removePendingContact(txn, p);
|
||||
states.remove(p);
|
||||
PublicKey theirPublicKey = pendingContact.getPublicKey();
|
||||
ContactId c =
|
||||
db.addContact(txn, remote, local, theirPublicKey, verified);
|
||||
String alias = pendingContact.getAlias();
|
||||
if (!alias.equals(remote.getName())) db.setContactAlias(txn, c, alias);
|
||||
KeyPair ourKeyPair = identityManager.getHandshakeKeys(txn);
|
||||
keyManager.addContact(txn, c, theirPublicKey, ourKeyPair);
|
||||
keyManager.addRotationKeys(txn, c, rootKey, timestamp, alice, active);
|
||||
Contact contact = db.getContact(txn, c);
|
||||
for (ContactHook hook : hooks) hook.addingContact(txn, contact);
|
||||
return c;
|
||||
@@ -80,7 +110,7 @@ class ContactManagerImpl implements ContactManager {
|
||||
@Override
|
||||
public ContactId addContact(Transaction txn, Author remote, AuthorId local,
|
||||
boolean verified) throws DbException {
|
||||
ContactId c = db.addContact(txn, remote, local, verified);
|
||||
ContactId c = db.addContact(txn, remote, local, null, verified);
|
||||
Contact contact = db.getContact(txn, c);
|
||||
for (ContactHook hook : hooks) hook.addingContact(txn, contact);
|
||||
return c;
|
||||
@@ -96,28 +126,55 @@ class ContactManagerImpl implements ContactManager {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHandshakeLink() {
|
||||
// TODO replace with real implementation
|
||||
return REMOTE_CONTACT_LINK;
|
||||
public String getHandshakeLink() throws DbException {
|
||||
KeyPair keyPair = db.transactionWithResult(true,
|
||||
identityManager::getHandshakeKeys);
|
||||
return pendingContactFactory.createHandshakeLink(keyPair.getPublic());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PendingContact addPendingContact(String link, String alias)
|
||||
throws DbException, FormatException {
|
||||
throws DbException, FormatException, GeneralSecurityException {
|
||||
PendingContact p =
|
||||
pendingContactFactory.createPendingContact(link, alias);
|
||||
db.transaction(false, txn -> db.addPendingContact(txn, p));
|
||||
Transaction txn = db.startTransaction(false);
|
||||
try {
|
||||
db.addPendingContact(txn, p);
|
||||
KeyPair ourKeyPair = identityManager.getHandshakeKeys(txn);
|
||||
keyManager.addPendingContact(txn, p.getId(), p.getPublicKey(),
|
||||
ourKeyPair);
|
||||
db.commitTransaction(txn);
|
||||
} finally {
|
||||
db.endTransaction(txn);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<PendingContact> getPendingContacts() throws DbException {
|
||||
return db.transactionWithResult(true, db::getPendingContacts);
|
||||
public PendingContact getPendingContact(Transaction txn, PendingContactId p)
|
||||
throws DbException {
|
||||
return db.getPendingContact(txn, p);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Pair<PendingContact, PendingContactState>> getPendingContacts()
|
||||
throws DbException {
|
||||
Collection<PendingContact> pendingContacts =
|
||||
db.transactionWithResult(true, db::getPendingContacts);
|
||||
List<Pair<PendingContact, PendingContactState>> pairs =
|
||||
new ArrayList<>(pendingContacts.size());
|
||||
for (PendingContact p : pendingContacts) {
|
||||
PendingContactState state = states.get(p.getId());
|
||||
if (state == null) state = WAITING_FOR_CONNECTION;
|
||||
pairs.add(new Pair<>(p, state));
|
||||
}
|
||||
return pairs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removePendingContact(PendingContactId p) throws DbException {
|
||||
db.transaction(false, txn -> db.removePendingContact(txn, p));
|
||||
states.remove(p);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -125,6 +182,11 @@ class ContactManagerImpl implements ContactManager {
|
||||
return db.transactionWithResult(true, txn -> db.getContact(txn, c));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Contact getContact(Transaction txn, ContactId c) throws DbException {
|
||||
return db.getContact(txn, c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Contact getContact(AuthorId remoteAuthorId, AuthorId localAuthorId)
|
||||
throws DbException {
|
||||
@@ -212,4 +274,12 @@ class ContactManagerImpl implements ContactManager {
|
||||
else return new AuthorInfo(UNVERIFIED, c.getAlias());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eventOccurred(Event e) {
|
||||
if (e instanceof PendingContactStateChangedEvent) {
|
||||
PendingContactStateChangedEvent p =
|
||||
(PendingContactStateChangedEvent) e;
|
||||
states.put(p.getId(), p.getPendingContactState());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactExchangeTask;
|
||||
import org.briarproject.bramble.api.contact.ContactExchangeManager;
|
||||
import org.briarproject.bramble.api.contact.ContactManager;
|
||||
import org.briarproject.bramble.api.contact.HandshakeManager;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
@@ -19,14 +21,16 @@ public class ContactModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
ContactManager getContactManager(ContactManagerImpl contactManager) {
|
||||
ContactManager provideContactManager(EventBus eventBus,
|
||||
ContactManagerImpl contactManager) {
|
||||
eventBus.addListener(contactManager);
|
||||
return contactManager;
|
||||
}
|
||||
|
||||
@Provides
|
||||
ContactExchangeTask provideContactExchangeTask(
|
||||
ContactExchangeTaskImpl contactExchangeTask) {
|
||||
return contactExchangeTask;
|
||||
ContactExchangeManager provideContactExchangeManager(
|
||||
ContactExchangeManagerImpl contactExchangeManager) {
|
||||
return contactExchangeManager;
|
||||
}
|
||||
|
||||
@Provides
|
||||
@@ -34,4 +38,23 @@ public class ContactModule {
|
||||
PendingContactFactoryImpl pendingContactFactory) {
|
||||
return pendingContactFactory;
|
||||
}
|
||||
|
||||
@Provides
|
||||
ContactExchangeCrypto provideContactExchangeCrypto(
|
||||
ContactExchangeCryptoImpl contactExchangeCrypto) {
|
||||
return contactExchangeCrypto;
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
HandshakeManager provideHandshakeManager(
|
||||
HandshakeManagerImpl handshakeManager) {
|
||||
return handshakeManager;
|
||||
}
|
||||
|
||||
@Provides
|
||||
HandshakeCrypto provideHandshakeCrypto(
|
||||
HandshakeCryptoImpl handshakeCrypto) {
|
||||
return handshakeCrypto;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
import static org.briarproject.bramble.api.crypto.CryptoConstants.MAC_BYTES;
|
||||
|
||||
interface HandshakeConstants {
|
||||
|
||||
/**
|
||||
* The current version of the handshake protocol.
|
||||
*/
|
||||
byte PROTOCOL_VERSION = 0;
|
||||
|
||||
/**
|
||||
* Label for deriving the master key.
|
||||
*/
|
||||
String MASTER_KEY_LABEL = "org.briarproject.bramble.handshake/MASTER_KEY";
|
||||
|
||||
/**
|
||||
* Label for deriving Alice's proof of ownership from the master key.
|
||||
*/
|
||||
String ALICE_PROOF_LABEL = "org.briarproject.bramble.handshake/ALICE_PROOF";
|
||||
|
||||
/**
|
||||
* Label for deriving Bob's proof of ownership from the master key.
|
||||
*/
|
||||
String BOB_PROOF_LABEL = "org.briarproject.bramble.handshake/BOB_PROOF";
|
||||
|
||||
/**
|
||||
* The length of the proof of ownership in bytes.
|
||||
*/
|
||||
int PROOF_BYTES = MAC_BYTES;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.KeyPair;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
@NotNullByDefault
|
||||
interface HandshakeCrypto {
|
||||
|
||||
KeyPair generateEphemeralKeyPair();
|
||||
|
||||
/**
|
||||
* Derives the master key from the given static and ephemeral keys.
|
||||
*
|
||||
* @param alice Whether the local peer is Alice
|
||||
*/
|
||||
SecretKey deriveMasterKey(PublicKey theirStaticPublicKey,
|
||||
PublicKey theirEphemeralPublicKey, KeyPair ourStaticKeyPair,
|
||||
KeyPair ourEphemeralKeyPair, boolean alice)
|
||||
throws GeneralSecurityException;
|
||||
|
||||
/**
|
||||
* Returns proof that the local peer knows the master key and therefore
|
||||
* owns the static and ephemeral public keys sent by the local peer.
|
||||
*
|
||||
* @param alice Whether the proof is being created by Alice
|
||||
*/
|
||||
byte[] proveOwnership(SecretKey masterKey, boolean alice);
|
||||
|
||||
/**
|
||||
* Verifies the given proof that the remote peer knows the master key and
|
||||
* therefore owns the static and ephemeral keys sent by the remote peer.
|
||||
*
|
||||
* @param alice Whether the proof was created by Alice
|
||||
*/
|
||||
boolean verifyOwnership(SecretKey masterKey, boolean alice, byte[] proof);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.CryptoComponent;
|
||||
import org.briarproject.bramble.api.crypto.KeyPair;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static org.briarproject.bramble.contact.HandshakeConstants.ALICE_PROOF_LABEL;
|
||||
import static org.briarproject.bramble.contact.HandshakeConstants.BOB_PROOF_LABEL;
|
||||
import static org.briarproject.bramble.contact.HandshakeConstants.MASTER_KEY_LABEL;
|
||||
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
class HandshakeCryptoImpl implements HandshakeCrypto {
|
||||
|
||||
private final CryptoComponent crypto;
|
||||
|
||||
@Inject
|
||||
HandshakeCryptoImpl(CryptoComponent crypto) {
|
||||
this.crypto = crypto;
|
||||
}
|
||||
|
||||
@Override
|
||||
public KeyPair generateEphemeralKeyPair() {
|
||||
return crypto.generateAgreementKeyPair();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SecretKey deriveMasterKey(PublicKey theirStaticPublicKey,
|
||||
PublicKey theirEphemeralPublicKey, KeyPair ourStaticKeyPair,
|
||||
KeyPair ourEphemeralKeyPair, boolean alice) throws
|
||||
GeneralSecurityException {
|
||||
byte[] theirStatic = theirStaticPublicKey.getEncoded();
|
||||
byte[] theirEphemeral = theirEphemeralPublicKey.getEncoded();
|
||||
byte[] ourStatic = ourStaticKeyPair.getPublic().getEncoded();
|
||||
byte[] ourEphemeral = ourEphemeralKeyPair.getPublic().getEncoded();
|
||||
byte[][] inputs = {
|
||||
alice ? ourStatic : theirStatic,
|
||||
alice ? theirStatic : ourStatic,
|
||||
alice ? ourEphemeral : theirEphemeral,
|
||||
alice ? theirEphemeral : ourEphemeral
|
||||
};
|
||||
return crypto.deriveSharedSecret(MASTER_KEY_LABEL, theirStaticPublicKey,
|
||||
theirEphemeralPublicKey, ourStaticKeyPair, ourEphemeralKeyPair,
|
||||
alice, inputs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] proveOwnership(SecretKey masterKey, boolean alice) {
|
||||
String label = alice ? ALICE_PROOF_LABEL : BOB_PROOF_LABEL;
|
||||
return crypto.mac(label, masterKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verifyOwnership(SecretKey masterKey, boolean alice,
|
||||
byte[] proof) {
|
||||
String label = alice ? ALICE_PROOF_LABEL : BOB_PROOF_LABEL;
|
||||
return crypto.verifyMac(proof, label, masterKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.Pair;
|
||||
import org.briarproject.bramble.api.Predicate;
|
||||
import org.briarproject.bramble.api.contact.ContactManager;
|
||||
import org.briarproject.bramble.api.contact.HandshakeManager;
|
||||
import org.briarproject.bramble.api.contact.PendingContact;
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.crypto.AgreementPublicKey;
|
||||
import org.briarproject.bramble.api.crypto.KeyPair;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.crypto.TransportCrypto;
|
||||
import org.briarproject.bramble.api.db.DatabaseComponent;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.db.TransactionManager;
|
||||
import org.briarproject.bramble.api.identity.IdentityManager;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.record.Record;
|
||||
import org.briarproject.bramble.api.record.RecordReader;
|
||||
import org.briarproject.bramble.api.record.RecordReaderFactory;
|
||||
import org.briarproject.bramble.api.record.RecordWriter;
|
||||
import org.briarproject.bramble.api.record.RecordWriterFactory;
|
||||
import org.briarproject.bramble.api.transport.StreamWriter;
|
||||
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import javax.annotation.concurrent.Immutable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static org.briarproject.bramble.api.crypto.CryptoConstants.MAX_AGREEMENT_PUBLIC_KEY_BYTES;
|
||||
import static org.briarproject.bramble.contact.HandshakeConstants.PROOF_BYTES;
|
||||
import static org.briarproject.bramble.contact.HandshakeConstants.PROTOCOL_VERSION;
|
||||
import static org.briarproject.bramble.contact.HandshakeRecordTypes.EPHEMERAL_PUBLIC_KEY;
|
||||
import static org.briarproject.bramble.contact.HandshakeRecordTypes.PROOF_OF_OWNERSHIP;
|
||||
import static org.briarproject.bramble.util.ValidationUtils.checkLength;
|
||||
|
||||
@Immutable
|
||||
@NotNullByDefault
|
||||
class HandshakeManagerImpl implements HandshakeManager {
|
||||
|
||||
// Ignore records with current protocol version, unknown record type
|
||||
private static final Predicate<Record> IGNORE = r ->
|
||||
r.getProtocolVersion() == PROTOCOL_VERSION &&
|
||||
!isKnownRecordType(r.getRecordType());
|
||||
|
||||
private static boolean isKnownRecordType(byte type) {
|
||||
return type == EPHEMERAL_PUBLIC_KEY || type == PROOF_OF_OWNERSHIP;
|
||||
}
|
||||
|
||||
private final TransactionManager db;
|
||||
private final IdentityManager identityManager;
|
||||
private final ContactManager contactManager;
|
||||
private final TransportCrypto transportCrypto;
|
||||
private final HandshakeCrypto handshakeCrypto;
|
||||
private final RecordReaderFactory recordReaderFactory;
|
||||
private final RecordWriterFactory recordWriterFactory;
|
||||
|
||||
@Inject
|
||||
HandshakeManagerImpl(DatabaseComponent db,
|
||||
IdentityManager identityManager,
|
||||
ContactManager contactManager,
|
||||
TransportCrypto transportCrypto,
|
||||
HandshakeCrypto handshakeCrypto,
|
||||
RecordReaderFactory recordReaderFactory,
|
||||
RecordWriterFactory recordWriterFactory) {
|
||||
this.db = db;
|
||||
this.identityManager = identityManager;
|
||||
this.contactManager = contactManager;
|
||||
this.transportCrypto = transportCrypto;
|
||||
this.handshakeCrypto = handshakeCrypto;
|
||||
this.recordReaderFactory = recordReaderFactory;
|
||||
this.recordWriterFactory = recordWriterFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HandshakeResult handshake(PendingContactId p, InputStream in,
|
||||
StreamWriter out) throws DbException, IOException {
|
||||
Pair<PublicKey, KeyPair> keys = db.transactionWithResult(true, txn -> {
|
||||
PendingContact pendingContact =
|
||||
contactManager.getPendingContact(txn, p);
|
||||
KeyPair keyPair = identityManager.getHandshakeKeys(txn);
|
||||
return new Pair<>(pendingContact.getPublicKey(), keyPair);
|
||||
});
|
||||
PublicKey theirStaticPublicKey = keys.getFirst();
|
||||
KeyPair ourStaticKeyPair = keys.getSecond();
|
||||
boolean alice = transportCrypto.isAlice(theirStaticPublicKey,
|
||||
ourStaticKeyPair);
|
||||
RecordReader recordReader = recordReaderFactory.createRecordReader(in);
|
||||
RecordWriter recordWriter = recordWriterFactory
|
||||
.createRecordWriter(out.getOutputStream());
|
||||
KeyPair ourEphemeralKeyPair =
|
||||
handshakeCrypto.generateEphemeralKeyPair();
|
||||
PublicKey theirEphemeralPublicKey;
|
||||
if (alice) {
|
||||
sendPublicKey(recordWriter, ourEphemeralKeyPair.getPublic());
|
||||
theirEphemeralPublicKey = receivePublicKey(recordReader);
|
||||
} else {
|
||||
theirEphemeralPublicKey = receivePublicKey(recordReader);
|
||||
sendPublicKey(recordWriter, ourEphemeralKeyPair.getPublic());
|
||||
}
|
||||
SecretKey masterKey;
|
||||
try {
|
||||
masterKey = handshakeCrypto.deriveMasterKey(theirStaticPublicKey,
|
||||
theirEphemeralPublicKey, ourStaticKeyPair,
|
||||
ourEphemeralKeyPair, alice);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new FormatException();
|
||||
}
|
||||
byte[] ourProof = handshakeCrypto.proveOwnership(masterKey, alice);
|
||||
byte[] theirProof;
|
||||
if (alice) {
|
||||
sendProof(recordWriter, ourProof);
|
||||
theirProof = receiveProof(recordReader);
|
||||
} else {
|
||||
theirProof = receiveProof(recordReader);
|
||||
sendProof(recordWriter, ourProof);
|
||||
}
|
||||
out.sendEndOfStream();
|
||||
recordReader.readRecord(r -> false, IGNORE);
|
||||
if (!handshakeCrypto.verifyOwnership(masterKey, !alice, theirProof))
|
||||
throw new FormatException();
|
||||
return new HandshakeResult(masterKey, alice);
|
||||
}
|
||||
|
||||
private void sendPublicKey(RecordWriter w, PublicKey k) throws IOException {
|
||||
w.writeRecord(new Record(PROTOCOL_VERSION, EPHEMERAL_PUBLIC_KEY,
|
||||
k.getEncoded()));
|
||||
w.flush();
|
||||
}
|
||||
|
||||
private PublicKey receivePublicKey(RecordReader r) throws IOException {
|
||||
byte[] key = readRecord(r, EPHEMERAL_PUBLIC_KEY).getPayload();
|
||||
checkLength(key, 1, MAX_AGREEMENT_PUBLIC_KEY_BYTES);
|
||||
return new AgreementPublicKey(key);
|
||||
}
|
||||
|
||||
private void sendProof(RecordWriter w, byte[] proof) throws IOException {
|
||||
w.writeRecord(new Record(PROTOCOL_VERSION, PROOF_OF_OWNERSHIP, proof));
|
||||
w.flush();
|
||||
}
|
||||
|
||||
private byte[] receiveProof(RecordReader r) throws IOException {
|
||||
byte[] proof = readRecord(r, PROOF_OF_OWNERSHIP).getPayload();
|
||||
checkLength(proof, PROOF_BYTES, PROOF_BYTES);
|
||||
return proof;
|
||||
}
|
||||
|
||||
private Record readRecord(RecordReader r, byte expectedType)
|
||||
throws IOException {
|
||||
// Accept records with current protocol version, expected type only
|
||||
Predicate<Record> accept = rec ->
|
||||
rec.getProtocolVersion() == PROTOCOL_VERSION &&
|
||||
rec.getRecordType() == expectedType;
|
||||
Record rec = r.readRecord(accept, IGNORE);
|
||||
if (rec == null) throw new EOFException();
|
||||
return rec;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package org.briarproject.bramble.contact;
|
||||
|
||||
/**
|
||||
* Record types for the handshake protocol.
|
||||
*/
|
||||
interface HandshakeRecordTypes {
|
||||
|
||||
byte EPHEMERAL_PUBLIC_KEY = 0;
|
||||
|
||||
byte PROOF_OF_OWNERSHIP = 1;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package org.briarproject.bramble.contact;
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.UnsupportedVersionException;
|
||||
import org.briarproject.bramble.api.contact.PendingContact;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
|
||||
interface PendingContactFactory {
|
||||
|
||||
@@ -15,4 +16,9 @@ interface PendingContactFactory {
|
||||
*/
|
||||
PendingContact createPendingContact(String link, String alias)
|
||||
throws FormatException;
|
||||
|
||||
/**
|
||||
* Creates a handshake link from the given public key.
|
||||
*/
|
||||
String createHandshakeLink(PublicKey k);
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import static org.briarproject.bramble.api.contact.HandshakeLinkConstants.FORMAT
|
||||
import static org.briarproject.bramble.api.contact.HandshakeLinkConstants.ID_LABEL;
|
||||
import static org.briarproject.bramble.api.contact.HandshakeLinkConstants.LINK_REGEX;
|
||||
import static org.briarproject.bramble.api.contact.HandshakeLinkConstants.RAW_LINK_BYTES;
|
||||
import static org.briarproject.bramble.api.contact.PendingContactState.WAITING_FOR_CONNECTION;
|
||||
import static org.briarproject.bramble.api.crypto.CryptoConstants.KEY_TYPE_AGREEMENT;
|
||||
|
||||
class PendingContactFactoryImpl implements PendingContactFactory {
|
||||
|
||||
@@ -39,8 +39,20 @@ class PendingContactFactoryImpl implements PendingContactFactory {
|
||||
PublicKey publicKey = parseHandshakeLink(link);
|
||||
PendingContactId id = getPendingContactId(publicKey);
|
||||
long timestamp = clock.currentTimeMillis();
|
||||
return new PendingContact(id, publicKey, alias, WAITING_FOR_CONNECTION,
|
||||
timestamp);
|
||||
return new PendingContact(id, publicKey, alias, timestamp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String createHandshakeLink(PublicKey k) {
|
||||
if (!k.getKeyType().equals(KEY_TYPE_AGREEMENT))
|
||||
throw new IllegalArgumentException();
|
||||
byte[] encoded = k.getEncoded();
|
||||
if (encoded.length != RAW_LINK_BYTES - 1)
|
||||
throw new IllegalArgumentException();
|
||||
byte[] raw = new byte[RAW_LINK_BYTES];
|
||||
raw[0] = FORMAT_VERSION;
|
||||
arraycopy(encoded, 0, raw, 1, encoded.length);
|
||||
return "briar://" + Base32.encode(raw).toLowerCase();
|
||||
}
|
||||
|
||||
private PublicKey parseHandshakeLink(String link) throws FormatException {
|
||||
@@ -48,13 +60,13 @@ class PendingContactFactoryImpl implements PendingContactFactory {
|
||||
if (!matcher.find()) throw new FormatException();
|
||||
// Discard 'briar://' and anything before or after the link
|
||||
link = matcher.group(2);
|
||||
byte[] base32 = Base32.decode(link, false);
|
||||
if (base32.length != RAW_LINK_BYTES) throw new AssertionError();
|
||||
byte version = base32[0];
|
||||
byte[] raw = Base32.decode(link, false);
|
||||
if (raw.length != RAW_LINK_BYTES) throw new AssertionError();
|
||||
byte version = raw[0];
|
||||
if (version != FORMAT_VERSION)
|
||||
throw new UnsupportedVersionException(version < FORMAT_VERSION);
|
||||
byte[] publicKeyBytes = new byte[base32.length - 1];
|
||||
arraycopy(base32, 1, publicKeyBytes, 0, publicKeyBytes.length);
|
||||
byte[] publicKeyBytes = new byte[raw.length - 1];
|
||||
arraycopy(raw, 1, publicKeyBytes, 0, publicKeyBytes.length);
|
||||
try {
|
||||
KeyParser parser = crypto.getAgreementKeyParser();
|
||||
return parser.parsePublicKey(publicKeyBytes);
|
||||
|
||||
@@ -34,6 +34,7 @@ import java.util.logging.Logger;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
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;
|
||||
@@ -191,10 +192,39 @@ class CryptoComponentImpl implements CryptoComponent {
|
||||
public SecretKey deriveSharedSecret(String label, PublicKey theirPublicKey,
|
||||
KeyPair ourKeyPair, byte[]... inputs)
|
||||
throws GeneralSecurityException {
|
||||
PrivateKey ourPriv = ourKeyPair.getPrivate();
|
||||
PrivateKey ourPrivateKey = ourKeyPair.getPrivate();
|
||||
byte[][] hashInputs = new byte[inputs.length + 1][];
|
||||
hashInputs[0] = performRawKeyAgreement(ourPriv, theirPublicKey);
|
||||
System.arraycopy(inputs, 0, hashInputs, 1, inputs.length);
|
||||
hashInputs[0] = performRawKeyAgreement(ourPrivateKey, theirPublicKey);
|
||||
arraycopy(inputs, 0, hashInputs, 1, inputs.length);
|
||||
byte[] hash = hash(label, hashInputs);
|
||||
if (hash.length != SecretKey.LENGTH) throw new IllegalStateException();
|
||||
return new SecretKey(hash);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SecretKey deriveSharedSecret(String label,
|
||||
PublicKey theirStaticPublicKey, PublicKey theirEphemeralPublicKey,
|
||||
KeyPair ourStaticKeyPair, KeyPair ourEphemeralKeyPair,
|
||||
boolean alice, byte[]... inputs) throws GeneralSecurityException {
|
||||
PrivateKey ourStaticPrivateKey = ourStaticKeyPair.getPrivate();
|
||||
PrivateKey ourEphemeralPrivateKey = ourEphemeralKeyPair.getPrivate();
|
||||
byte[][] hashInputs = new byte[inputs.length + 3][];
|
||||
// Alice static/Bob static
|
||||
hashInputs[0] = performRawKeyAgreement(ourStaticPrivateKey,
|
||||
theirStaticPublicKey);
|
||||
// Alice static/Bob ephemeral, Bob static/Alice ephemeral
|
||||
if (alice) {
|
||||
hashInputs[1] = performRawKeyAgreement(ourStaticPrivateKey,
|
||||
theirEphemeralPublicKey);
|
||||
hashInputs[2] = performRawKeyAgreement(ourEphemeralPrivateKey,
|
||||
theirStaticPublicKey);
|
||||
} else {
|
||||
hashInputs[1] = performRawKeyAgreement(ourEphemeralPrivateKey,
|
||||
theirStaticPublicKey);
|
||||
hashInputs[2] = performRawKeyAgreement(ourStaticPrivateKey,
|
||||
theirEphemeralPublicKey);
|
||||
}
|
||||
arraycopy(inputs, 0, hashInputs, 3, inputs.length);
|
||||
byte[] hash = hash(label, hashInputs);
|
||||
if (hash.length != SecretKey.LENGTH) throw new IllegalStateException();
|
||||
return new SecretKey(hash);
|
||||
@@ -304,13 +334,13 @@ class CryptoComponentImpl implements CryptoComponent {
|
||||
output[outputOff] = PBKDF_FORMAT_SCRYPT;
|
||||
outputOff++;
|
||||
// Salt
|
||||
System.arraycopy(salt, 0, output, outputOff, salt.length);
|
||||
arraycopy(salt, 0, output, outputOff, salt.length);
|
||||
outputOff += salt.length;
|
||||
// Cost parameter
|
||||
ByteUtils.writeUint32(cost, output, outputOff);
|
||||
outputOff += INT_32_BYTES;
|
||||
// IV
|
||||
System.arraycopy(iv, 0, output, outputOff, iv.length);
|
||||
arraycopy(iv, 0, output, outputOff, iv.length);
|
||||
outputOff += iv.length;
|
||||
// Initialise the cipher and encrypt the plaintext
|
||||
try {
|
||||
@@ -340,7 +370,7 @@ class CryptoComponentImpl implements CryptoComponent {
|
||||
return null; // Unknown format
|
||||
// Salt
|
||||
byte[] salt = new byte[PBKDF_SALT_BYTES];
|
||||
System.arraycopy(input, inputOff, salt, 0, salt.length);
|
||||
arraycopy(input, inputOff, salt, 0, salt.length);
|
||||
inputOff += salt.length;
|
||||
// Cost parameter
|
||||
long cost = ByteUtils.readUint32(input, inputOff);
|
||||
@@ -349,7 +379,7 @@ class CryptoComponentImpl implements CryptoComponent {
|
||||
return null; // Invalid cost parameter
|
||||
// IV
|
||||
byte[] iv = new byte[STORAGE_IV_BYTES];
|
||||
System.arraycopy(input, inputOff, iv, 0, iv.length);
|
||||
arraycopy(input, inputOff, iv, 0, iv.length);
|
||||
inputOff += iv.length;
|
||||
// Derive the key from the password
|
||||
SecretKey key = passwordBasedKdf.deriveKey(password, salt, (int) cost);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package org.briarproject.bramble.crypto;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.CryptoComponent;
|
||||
import org.briarproject.bramble.api.crypto.KeyPair;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.crypto.TransportCrypto;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
@@ -10,9 +12,12 @@ import org.briarproject.bramble.api.transport.TransportKeys;
|
||||
import org.spongycastle.crypto.Digest;
|
||||
import org.spongycastle.crypto.digests.Blake2bDigest;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static java.lang.System.arraycopy;
|
||||
import static org.briarproject.bramble.api.Bytes.compare;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.ALICE_HANDSHAKE_HEADER_LABEL;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.ALICE_HANDSHAKE_TAG_LABEL;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.ALICE_HEADER_LABEL;
|
||||
@@ -21,7 +26,10 @@ import static org.briarproject.bramble.api.transport.TransportConstants.BOB_HAND
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.BOB_HANDSHAKE_TAG_LABEL;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.BOB_HEADER_LABEL;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.BOB_TAG_LABEL;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.CONTACT_ROOT_KEY_LABEL;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.PENDING_CONTACT_ROOT_KEY_LABEL;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.ROTATE_LABEL;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.STATIC_MASTER_KEY_LABEL;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH;
|
||||
import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES;
|
||||
import static org.briarproject.bramble.util.ByteUtils.INT_64_BYTES;
|
||||
@@ -40,6 +48,36 @@ class TransportCryptoImpl implements TransportCrypto {
|
||||
this.crypto = crypto;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAlice(PublicKey theirHandshakePublicKey,
|
||||
KeyPair ourHandshakeKeyPair) {
|
||||
byte[] theirPublic = theirHandshakePublicKey.getEncoded();
|
||||
byte[] ourPublic = ourHandshakeKeyPair.getPublic().getEncoded();
|
||||
return compare(ourPublic, theirPublic) < 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SecretKey deriveStaticMasterKey(PublicKey theirHandshakePublicKey,
|
||||
KeyPair ourHandshakeKeyPair) throws GeneralSecurityException {
|
||||
byte[] theirPublic = theirHandshakePublicKey.getEncoded();
|
||||
byte[] ourPublic = ourHandshakeKeyPair.getPublic().getEncoded();
|
||||
boolean alice = compare(ourPublic, theirPublic) < 0;
|
||||
byte[][] inputs = {
|
||||
alice ? ourPublic : theirPublic,
|
||||
alice ? theirPublic : ourPublic
|
||||
};
|
||||
return crypto.deriveSharedSecret(STATIC_MASTER_KEY_LABEL,
|
||||
theirHandshakePublicKey, ourHandshakeKeyPair, inputs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SecretKey deriveHandshakeRootKey(SecretKey staticMasterKey,
|
||||
boolean pendingContact) {
|
||||
String label = pendingContact ?
|
||||
PENDING_CONTACT_ROOT_KEY_LABEL : CONTACT_ROOT_KEY_LABEL;
|
||||
return crypto.deriveKey(label, staticMasterKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TransportKeys deriveRotationKeys(TransportId t,
|
||||
SecretKey rootKey, long timePeriod, boolean weAreAlice,
|
||||
|
||||
@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.contact.Contact;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.contact.PendingContact;
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.contact.PendingContactState;
|
||||
import org.briarproject.bramble.api.crypto.PrivateKey;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
@@ -34,6 +33,7 @@ import org.briarproject.bramble.api.transport.TransportKeySet;
|
||||
import org.briarproject.bramble.api.transport.TransportKeys;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
@@ -89,8 +89,8 @@ interface Database<T> {
|
||||
* Stores a contact associated with the given local and remote pseudonyms,
|
||||
* and returns an ID for the contact.
|
||||
*/
|
||||
ContactId addContact(T txn, Author remote, AuthorId local, boolean verified)
|
||||
throws DbException;
|
||||
ContactId addContact(T txn, Author remote, AuthorId local,
|
||||
@Nullable PublicKey handshake, boolean verified) throws DbException;
|
||||
|
||||
/**
|
||||
* Stores a group.
|
||||
@@ -116,7 +116,7 @@ interface Database<T> {
|
||||
* if the message was created locally.
|
||||
*/
|
||||
void addMessage(T txn, Message m, MessageState state, boolean shared,
|
||||
@Nullable ContactId sender) throws DbException;
|
||||
boolean temporary, @Nullable ContactId sender) throws DbException;
|
||||
|
||||
/**
|
||||
* Adds a dependency between two messages, where the dependent message is
|
||||
@@ -497,6 +497,14 @@ interface Database<T> {
|
||||
*/
|
||||
long getNextSendTime(T txn, ContactId c) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the pending contact with the given ID.
|
||||
* <p/>
|
||||
* Read-only.
|
||||
*/
|
||||
PendingContact getPendingContact(T txn, PendingContactId p)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Returns all pending contacts.
|
||||
* <p/>
|
||||
@@ -521,6 +529,13 @@ interface Database<T> {
|
||||
*/
|
||||
Settings getSettings(T txn, String namespace) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns the versions of the sync protocol supported by the given contact.
|
||||
* <p/>
|
||||
* Read-only.
|
||||
*/
|
||||
List<Byte> getSyncVersions(T txn, ContactId c) throws DbException;
|
||||
|
||||
/**
|
||||
* Returns all transport keys for the given transport.
|
||||
* <p/>
|
||||
@@ -623,6 +638,12 @@ interface Database<T> {
|
||||
*/
|
||||
void removePendingContact(T txn, PendingContactId p) throws DbException;
|
||||
|
||||
/**
|
||||
* Removes all temporary messages (and all associated state) from the
|
||||
* database.
|
||||
*/
|
||||
void removeTemporaryMessages(T txn) throws DbException;
|
||||
|
||||
/**
|
||||
* Removes a transport (and all associated state) from the database.
|
||||
*/
|
||||
@@ -631,7 +652,8 @@ interface Database<T> {
|
||||
/**
|
||||
* Removes the given transport keys from the database.
|
||||
*/
|
||||
void removeTransportKeys(T txn, TransportId t, KeySetId k) throws DbException;
|
||||
void removeTransportKeys(T txn, TransportId t, KeySetId k)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Resets the transmission count and expiry time of the given message with
|
||||
@@ -663,6 +685,11 @@ interface Database<T> {
|
||||
void setHandshakeKeyPair(T txn, AuthorId local, PublicKey publicKey,
|
||||
PrivateKey privateKey) throws DbException;
|
||||
|
||||
/**
|
||||
* Marks the given message as permanent, i.e. not temporary.
|
||||
*/
|
||||
void setMessagePermanent(T txn, MessageId m) throws DbException;
|
||||
|
||||
/**
|
||||
* Marks the given message as shared.
|
||||
*/
|
||||
@@ -674,12 +701,6 @@ interface Database<T> {
|
||||
void setMessageState(T txn, MessageId m, MessageState state)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Sets the state of the given pending contact.
|
||||
*/
|
||||
void setPendingContactState(T txn, PendingContactId p,
|
||||
PendingContactState state) throws DbException;
|
||||
|
||||
/**
|
||||
* Sets the reordering window for the given transport keys in the given
|
||||
* time period.
|
||||
@@ -687,6 +708,12 @@ interface Database<T> {
|
||||
void setReorderingWindow(T txn, KeySetId k, TransportId t,
|
||||
long timePeriod, long base, byte[] bitmap) throws DbException;
|
||||
|
||||
/**
|
||||
* Sets the versions of the sync protocol supported by the given contact.
|
||||
*/
|
||||
void setSyncVersions(T txn, ContactId c, List<Byte> supported)
|
||||
throws DbException;
|
||||
|
||||
/**
|
||||
* Marks the given transport keys as usable for outgoing streams.
|
||||
*/
|
||||
|
||||
@@ -7,8 +7,8 @@ import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.contact.event.ContactAddedEvent;
|
||||
import org.briarproject.bramble.api.contact.event.ContactRemovedEvent;
|
||||
import org.briarproject.bramble.api.contact.event.ContactVerifiedEvent;
|
||||
import org.briarproject.bramble.api.contact.event.PendingContactAddedEvent;
|
||||
import org.briarproject.bramble.api.contact.event.PendingContactRemovedEvent;
|
||||
import org.briarproject.bramble.api.contact.event.PendingContactStateChangedEvent;
|
||||
import org.briarproject.bramble.api.crypto.PrivateKey;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
@@ -65,6 +65,7 @@ import org.briarproject.bramble.api.sync.event.MessageToAckEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessageToRequestEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesAckedEvent;
|
||||
import org.briarproject.bramble.api.sync.event.MessagesSentEvent;
|
||||
import org.briarproject.bramble.api.sync.event.SyncVersionsUpdatedEvent;
|
||||
import org.briarproject.bramble.api.sync.validation.MessageState;
|
||||
import org.briarproject.bramble.api.transport.KeySetId;
|
||||
import org.briarproject.bramble.api.transport.TransportKeySet;
|
||||
@@ -85,6 +86,7 @@ import javax.annotation.concurrent.ThreadSafe;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.api.sync.Group.Visibility.INVISIBLE;
|
||||
import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED;
|
||||
import static org.briarproject.bramble.api.sync.validation.MessageState.DELIVERED;
|
||||
@@ -99,7 +101,7 @@ import static org.briarproject.bramble.util.LogUtils.now;
|
||||
class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
|
||||
private static final Logger LOG =
|
||||
Logger.getLogger(DatabaseComponentImpl.class.getName());
|
||||
getLogger(DatabaseComponentImpl.class.getName());
|
||||
|
||||
private final Database<T> db;
|
||||
private final Class<T> txnClass;
|
||||
@@ -234,18 +236,18 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
|
||||
@Override
|
||||
public ContactId addContact(Transaction transaction, Author remote,
|
||||
AuthorId local, boolean verified)
|
||||
AuthorId local, @Nullable PublicKey handshake, boolean verified)
|
||||
throws DbException {
|
||||
if (transaction.isReadOnly()) throw new IllegalArgumentException();
|
||||
T txn = unbox(transaction);
|
||||
if (!db.containsIdentity(txn, local))
|
||||
throw new NoSuchIdentityException();
|
||||
if (db.containsIdentity(txn, remote.getId()))
|
||||
throw new ContactExistsException();
|
||||
throw new ContactExistsException(local, remote);
|
||||
if (db.containsContact(txn, remote.getId(), local))
|
||||
throw new ContactExistsException();
|
||||
ContactId c = db.addContact(txn, remote, local, verified);
|
||||
transaction.attach(new ContactAddedEvent(c));
|
||||
throw new ContactExistsException(local, remote);
|
||||
ContactId c = db.addContact(txn, remote, local, handshake, verified);
|
||||
transaction.attach(new ContactAddedEvent(c, verified));
|
||||
return c;
|
||||
}
|
||||
|
||||
@@ -272,13 +274,14 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
|
||||
@Override
|
||||
public void addLocalMessage(Transaction transaction, Message m,
|
||||
Metadata meta, boolean shared) throws DbException {
|
||||
Metadata meta, boolean shared, boolean temporary)
|
||||
throws DbException {
|
||||
if (transaction.isReadOnly()) throw new IllegalArgumentException();
|
||||
T txn = unbox(transaction);
|
||||
if (!db.containsGroup(txn, m.getGroupId()))
|
||||
throw new NoSuchGroupException();
|
||||
if (!db.containsMessage(txn, m.getId())) {
|
||||
db.addMessage(txn, m, DELIVERED, shared, null);
|
||||
db.addMessage(txn, m, DELIVERED, shared, temporary, null);
|
||||
transaction.attach(new MessageAddedEvent(m, null));
|
||||
transaction.attach(new MessageStateChangedEvent(m.getId(), true,
|
||||
DELIVERED));
|
||||
@@ -295,8 +298,7 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
if (db.containsPendingContact(txn, p.getId()))
|
||||
throw new PendingContactExistsException();
|
||||
db.addPendingContact(txn, p);
|
||||
transaction.attach(new PendingContactStateChangedEvent(p.getId(),
|
||||
p.getState()));
|
||||
transaction.attach(new PendingContactAddedEvent(p));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -692,6 +694,15 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
return db.getNextSendTime(txn, c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PendingContact getPendingContact(Transaction transaction,
|
||||
PendingContactId p) throws DbException {
|
||||
T txn = unbox(transaction);
|
||||
if (!db.containsPendingContact(txn, p))
|
||||
throw new NoSuchPendingContactException();
|
||||
return db.getPendingContact(txn, p);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<PendingContact> getPendingContacts(
|
||||
Transaction transaction) throws DbException {
|
||||
@@ -706,6 +717,15 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
return db.getSettings(txn, namespace);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Byte> getSyncVersions(Transaction transaction, ContactId c)
|
||||
throws DbException {
|
||||
T txn = unbox(transaction);
|
||||
if (!db.containsContact(txn, c))
|
||||
throw new NoSuchContactException();
|
||||
return db.getSyncVersions(txn, c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<TransportKeySet> getTransportKeys(Transaction transaction,
|
||||
TransportId t) throws DbException {
|
||||
@@ -791,7 +811,7 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
db.raiseSeenFlag(txn, c, m.getId());
|
||||
db.raiseAckFlag(txn, c, m.getId());
|
||||
} else {
|
||||
db.addMessage(txn, m, UNKNOWN, false, c);
|
||||
db.addMessage(txn, m, UNKNOWN, false, false, c);
|
||||
transaction.attach(new MessageAddedEvent(m, c));
|
||||
}
|
||||
transaction.attach(new MessageToAckEvent(c));
|
||||
@@ -899,6 +919,14 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
transaction.attach(new PendingContactRemovedEvent(p));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTemporaryMessages(Transaction transaction)
|
||||
throws DbException {
|
||||
if (transaction.isReadOnly()) throw new IllegalArgumentException();
|
||||
T txn = unbox(transaction);
|
||||
db.removeTemporaryMessages(txn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTransport(Transaction transaction, TransportId t)
|
||||
throws DbException {
|
||||
@@ -958,6 +986,16 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
transaction.attach(new GroupVisibilityUpdatedEvent(affected));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMessagePermanent(Transaction transaction, MessageId m)
|
||||
throws DbException {
|
||||
if (transaction.isReadOnly()) throw new IllegalArgumentException();
|
||||
T txn = unbox(transaction);
|
||||
if (!db.containsMessage(txn, m))
|
||||
throw new NoSuchMessageException();
|
||||
db.setMessagePermanent(txn, m);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMessageShared(Transaction transaction, MessageId m)
|
||||
throws DbException {
|
||||
@@ -966,8 +1004,7 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
if (!db.containsMessage(txn, m))
|
||||
throw new NoSuchMessageException();
|
||||
if (db.getMessageState(txn, m) != DELIVERED)
|
||||
throw new IllegalArgumentException(
|
||||
"Shared undelivered message");
|
||||
throw new IllegalArgumentException("Shared undelivered message");
|
||||
db.setMessageShared(txn, m);
|
||||
transaction.attach(new MessageSharedEvent(m));
|
||||
}
|
||||
@@ -1019,6 +1056,17 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
|
||||
db.setReorderingWindow(txn, k, t, timePeriod, base, bitmap);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSyncVersions(Transaction transaction, ContactId c,
|
||||
List<Byte> supported) throws DbException {
|
||||
if (transaction.isReadOnly()) throw new IllegalArgumentException();
|
||||
T txn = unbox(transaction);
|
||||
if (!db.containsContact(txn, c))
|
||||
throw new NoSuchContactException();
|
||||
db.setSyncVersions(txn, c, supported);
|
||||
transaction.attach(new SyncVersionsUpdatedEvent(c, supported));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTransportKeysActive(Transaction transaction, TransportId t,
|
||||
KeySetId k) throws DbException {
|
||||
|
||||
@@ -2,6 +2,7 @@ package org.briarproject.bramble.db;
|
||||
|
||||
import org.briarproject.bramble.api.db.DatabaseComponent;
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
import org.briarproject.bramble.api.db.TransactionManager;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.event.EventExecutor;
|
||||
import org.briarproject.bramble.api.lifecycle.ShutdownManager;
|
||||
@@ -34,4 +35,9 @@ public class DatabaseModule {
|
||||
return new DatabaseComponentImpl<>(db, Connection.class, eventBus,
|
||||
eventExecutor, shutdownManager);
|
||||
}
|
||||
|
||||
@Provides
|
||||
TransactionManager provideTransactionManager(DatabaseComponent db) {
|
||||
return db;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package org.briarproject.bramble.db;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
import org.briarproject.bramble.api.db.DbClosedException;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.db.MigrationListener;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
@@ -89,9 +90,9 @@ class H2Database extends JdbcDatabase {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Connection createConnection() throws SQLException {
|
||||
protected Connection createConnection() throws DbException, SQLException {
|
||||
SecretKey key = this.key;
|
||||
if (key == null) throw new IllegalStateException();
|
||||
if (key == null) throw new DbClosedException();
|
||||
Properties props = new Properties();
|
||||
props.setProperty("user", "user");
|
||||
// Separate the file password from the user password with a space
|
||||
|
||||
@@ -2,6 +2,7 @@ package org.briarproject.bramble.db;
|
||||
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.api.db.DatabaseConfig;
|
||||
import org.briarproject.bramble.api.db.DbClosedException;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.db.MigrationListener;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
@@ -87,9 +88,9 @@ class HyperSqlDatabase extends JdbcDatabase {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Connection createConnection() throws SQLException {
|
||||
protected Connection createConnection() throws DbException, SQLException {
|
||||
SecretKey key = this.key;
|
||||
if (key == null) throw new IllegalStateException();
|
||||
if (key == null) throw new DbClosedException();
|
||||
String hex = StringUtils.toHexString(key.getBytes());
|
||||
return DriverManager.getConnection(url + ";crypt_key=" + hex);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.contact.Contact;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.contact.PendingContact;
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.contact.PendingContactState;
|
||||
import org.briarproject.bramble.api.crypto.AgreementPrivateKey;
|
||||
import org.briarproject.bramble.api.crypto.AgreementPublicKey;
|
||||
import org.briarproject.bramble.api.crypto.PrivateKey;
|
||||
@@ -63,6 +62,7 @@ import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
|
||||
import static java.sql.Types.BINARY;
|
||||
import static java.sql.Types.BOOLEAN;
|
||||
@@ -98,7 +98,7 @@ import static org.briarproject.bramble.util.LogUtils.now;
|
||||
abstract class JdbcDatabase implements Database<Connection> {
|
||||
|
||||
// Package access for testing
|
||||
static final int CODE_SCHEMA_VERSION = 44;
|
||||
static final int CODE_SCHEMA_VERSION = 47;
|
||||
|
||||
// Time period offsets for incoming transport keys
|
||||
private static final int OFFSET_PREV = -1;
|
||||
@@ -135,6 +135,7 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
+ " handshakePublicKey _BINARY," // Null if key is unknown
|
||||
+ " localAuthorId _HASH NOT NULL,"
|
||||
+ " verified BOOLEAN NOT NULL,"
|
||||
+ " syncVersions _BINARY DEFAULT '00' NOT NULL,"
|
||||
+ " PRIMARY KEY (contactId),"
|
||||
+ " FOREIGN KEY (localAuthorId)"
|
||||
+ " REFERENCES localAuthors (authorId)"
|
||||
@@ -178,6 +179,7 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
+ " timestamp BIGINT NOT NULL,"
|
||||
+ " state INT NOT NULL,"
|
||||
+ " shared BOOLEAN NOT NULL,"
|
||||
+ " temporary BOOLEAN NOT NULL,"
|
||||
+ " length INT NOT NULL,"
|
||||
+ " raw BLOB," // Null if message has been deleted
|
||||
+ " PRIMARY KEY (messageId),"
|
||||
@@ -264,7 +266,6 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
+ " (pendingContactId _HASH NOT NULL,"
|
||||
+ " publicKey _BINARY NOT NULL,"
|
||||
+ " alias _STRING NOT NULL,"
|
||||
+ " state INT NOT NULL,"
|
||||
+ " timestamp BIGINT NOT NULL,"
|
||||
+ " PRIMARY KEY (pendingContactId))";
|
||||
|
||||
@@ -338,24 +339,26 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
private static final Logger LOG =
|
||||
getLogger(JdbcDatabase.class.getName());
|
||||
|
||||
// Different database libraries use different names for certain types
|
||||
private final MessageFactory messageFactory;
|
||||
private final Clock clock;
|
||||
private final DatabaseTypes dbTypes;
|
||||
|
||||
// Locking: connectionsLock
|
||||
private final LinkedList<Connection> connections = new LinkedList<>();
|
||||
|
||||
private int openConnections = 0; // Locking: connectionsLock
|
||||
private boolean closed = false; // Locking: connectionsLock
|
||||
|
||||
protected abstract Connection createConnection() throws SQLException;
|
||||
|
||||
protected abstract void compactAndClose() throws DbException;
|
||||
|
||||
private final Lock connectionsLock = new ReentrantLock();
|
||||
private final Condition connectionsChanged = connectionsLock.newCondition();
|
||||
|
||||
@GuardedBy("connectionsLock")
|
||||
private final LinkedList<Connection> connections = new LinkedList<>();
|
||||
|
||||
@GuardedBy("connectionsLock")
|
||||
private int openConnections = 0;
|
||||
@GuardedBy("connectionsLock")
|
||||
private boolean closed = false;
|
||||
|
||||
protected abstract Connection createConnection()
|
||||
throws DbException, SQLException;
|
||||
|
||||
protected abstract void compactAndClose() throws DbException;
|
||||
|
||||
JdbcDatabase(DatabaseTypes databaseTypes, MessageFactory messageFactory,
|
||||
Clock clock) {
|
||||
this.dbTypes = databaseTypes;
|
||||
@@ -457,7 +460,10 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
new Migration40_41(dbTypes),
|
||||
new Migration41_42(dbTypes),
|
||||
new Migration42_43(dbTypes),
|
||||
new Migration43_44(dbTypes)
|
||||
new Migration43_44(dbTypes),
|
||||
new Migration44_45(),
|
||||
new Migration45_46(),
|
||||
new Migration46_47(dbTypes)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -630,22 +636,25 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
|
||||
@Override
|
||||
public ContactId addContact(Connection txn, Author remote, AuthorId local,
|
||||
boolean verified) throws DbException {
|
||||
@Nullable PublicKey handshake, boolean verified)
|
||||
throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
// Create a contact row
|
||||
String sql = "INSERT INTO contacts"
|
||||
+ " (authorId, formatVersion, name, publicKey,"
|
||||
+ " localAuthorId, verified)"
|
||||
+ " VALUES (?, ?, ?, ?, ?, ?)";
|
||||
+ " localAuthorId, handshakePublicKey, verified)"
|
||||
+ " VALUES (?, ?, ?, ?, ?, ?, ?)";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, remote.getId().getBytes());
|
||||
ps.setInt(2, remote.getFormatVersion());
|
||||
ps.setString(3, remote.getName());
|
||||
ps.setBytes(4, remote.getPublicKey().getEncoded());
|
||||
ps.setBytes(5, local.getBytes());
|
||||
ps.setBoolean(6, verified);
|
||||
if (handshake == null) ps.setNull(6, BINARY);
|
||||
else ps.setBytes(6, handshake.getEncoded());
|
||||
ps.setBoolean(7, verified);
|
||||
int affected = ps.executeUpdate();
|
||||
if (affected != 1) throw new DbStateException();
|
||||
ps.close();
|
||||
@@ -774,22 +783,23 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
|
||||
@Override
|
||||
public void addMessage(Connection txn, Message m, MessageState state,
|
||||
boolean messageShared, @Nullable ContactId sender)
|
||||
boolean shared, boolean temporary, @Nullable ContactId sender)
|
||||
throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
try {
|
||||
String sql = "INSERT INTO messages (messageId, groupId, timestamp,"
|
||||
+ " state, shared, length, raw)"
|
||||
+ " VALUES (?, ?, ?, ?, ?, ?, ?)";
|
||||
+ " state, shared, temporary, length, raw)"
|
||||
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, m.getId().getBytes());
|
||||
ps.setBytes(2, m.getGroupId().getBytes());
|
||||
ps.setLong(3, m.getTimestamp());
|
||||
ps.setInt(4, state.getValue());
|
||||
ps.setBoolean(5, messageShared);
|
||||
ps.setBoolean(5, shared);
|
||||
ps.setBoolean(6, temporary);
|
||||
byte[] raw = messageFactory.getRawMessage(m);
|
||||
ps.setInt(6, raw.length);
|
||||
ps.setBytes(7, raw);
|
||||
ps.setInt(7, raw.length);
|
||||
ps.setBytes(8, raw);
|
||||
int affected = ps.executeUpdate();
|
||||
if (affected != 1) throw new DbStateException();
|
||||
ps.close();
|
||||
@@ -801,8 +811,7 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
boolean offered = removeOfferedMessage(txn, c, m.getId());
|
||||
boolean seen = offered || c.equals(sender);
|
||||
addStatus(txn, m.getId(), c, m.getGroupId(), m.getTimestamp(),
|
||||
raw.length, state, e.getValue(), messageShared,
|
||||
false, seen);
|
||||
raw.length, state, e.getValue(), shared, false, seen);
|
||||
}
|
||||
// Update denormalised column in messageDependencies if dependency
|
||||
// is in same group as dependent
|
||||
@@ -933,14 +942,13 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
PreparedStatement ps = null;
|
||||
try {
|
||||
String sql = "INSERT INTO pendingContacts (pendingContactId,"
|
||||
+ " publicKey, alias, state, timestamp)"
|
||||
+ " VALUES (?, ?, ?, ?, ?)";
|
||||
+ " publicKey, alias, timestamp)"
|
||||
+ " VALUES (?, ?, ?, ?)";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, p.getId().getBytes());
|
||||
ps.setBytes(2, p.getPublicKey().getEncoded());
|
||||
ps.setString(3, p.getAlias());
|
||||
ps.setInt(4, p.getState().getValue());
|
||||
ps.setLong(5, p.getTimestamp());
|
||||
ps.setLong(4, p.getTimestamp());
|
||||
int affected = ps.executeUpdate();
|
||||
if (affected != 1) throw new DbStateException();
|
||||
ps.close();
|
||||
@@ -2207,14 +2215,37 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public PendingContact getPendingContact(Connection txn, PendingContactId p)
|
||||
throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
String sql = "SELECT publicKey, alias, timestamp"
|
||||
+ " FROM pendingContacts"
|
||||
+ " WHERE pendingContactId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, p.getBytes());
|
||||
rs = ps.executeQuery();
|
||||
if (!rs.next()) throw new DbStateException();
|
||||
PublicKey publicKey = new AgreementPublicKey(rs.getBytes(1));
|
||||
String alias = rs.getString(2);
|
||||
long timestamp = rs.getLong(3);
|
||||
return new PendingContact(p, publicKey, alias, timestamp);
|
||||
} catch (SQLException e) {
|
||||
tryToClose(rs, LOG, WARNING);
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<PendingContact> getPendingContacts(Connection txn)
|
||||
throws DbException {
|
||||
Statement s = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
String sql = "SELECT pendingContactId, publicKey, alias, state,"
|
||||
+ " timestamp"
|
||||
String sql = "SELECT pendingContactId, publicKey, alias, timestamp"
|
||||
+ " FROM pendingContacts";
|
||||
s = txn.createStatement();
|
||||
rs = s.executeQuery(sql);
|
||||
@@ -2223,11 +2254,9 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
PendingContactId id = new PendingContactId(rs.getBytes(1));
|
||||
PublicKey publicKey = new AgreementPublicKey(rs.getBytes(2));
|
||||
String alias = rs.getString(3);
|
||||
PendingContactState state =
|
||||
PendingContactState.fromValue(rs.getInt(4));
|
||||
long timestamp = rs.getLong(5);
|
||||
long timestamp = rs.getLong(4);
|
||||
pendingContacts.add(new PendingContact(id, publicKey, alias,
|
||||
state, timestamp));
|
||||
timestamp));
|
||||
}
|
||||
rs.close();
|
||||
s.close();
|
||||
@@ -2301,6 +2330,32 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Byte> getSyncVersions(Connection txn, ContactId c)
|
||||
throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
String sql = "SELECT syncVersions FROM contacts"
|
||||
+ " WHERE contactId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setInt(1, c.getInt());
|
||||
rs = ps.executeQuery();
|
||||
if (!rs.next()) throw new DbStateException();
|
||||
byte[] bytes = rs.getBytes(1);
|
||||
List<Byte> supported = new ArrayList<>(bytes.length);
|
||||
for (byte b : bytes) supported.add(b);
|
||||
if (rs.next()) throw new DbStateException();
|
||||
rs.close();
|
||||
ps.close();
|
||||
return supported;
|
||||
} catch (SQLException e) {
|
||||
tryToClose(rs, LOG, WARNING);
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<TransportKeySet> getTransportKeys(Connection txn,
|
||||
TransportId t) throws DbException {
|
||||
@@ -2853,6 +2908,21 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTemporaryMessages(Connection txn) throws DbException {
|
||||
Statement s = null;
|
||||
try {
|
||||
String sql = "DELETE FROM messages WHERE temporary = TRUE";
|
||||
s = txn.createStatement();
|
||||
int affected = s.executeUpdate(sql);
|
||||
if (affected < 0) throw new DbStateException();
|
||||
s.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTransport(Connection txn, TransportId t)
|
||||
throws DbException {
|
||||
@@ -2998,6 +3068,24 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMessagePermanent(Connection txn, MessageId m)
|
||||
throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
try {
|
||||
String sql = "UPDATE messages SET temporary = FALSE"
|
||||
+ " WHERE messageId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setBytes(1, m.getBytes());
|
||||
int affected = ps.executeUpdate();
|
||||
if (affected < 0 || affected > 1) throw new DbStateException();
|
||||
ps.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMessageShared(Connection txn, MessageId m)
|
||||
throws DbException {
|
||||
@@ -3077,25 +3165,6 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPendingContactState(Connection txn, PendingContactId p,
|
||||
PendingContactState state) throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
try {
|
||||
String sql = "UPDATE pendingContacts SET state = ?"
|
||||
+ " WHERE pendingContactId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
ps.setInt(1, state.getValue());
|
||||
ps.setBytes(2, p.getBytes());
|
||||
int affected = ps.executeUpdate();
|
||||
if (affected < 0 || affected > 1) throw new DbStateException();
|
||||
ps.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setReorderingWindow(Connection txn, KeySetId k,
|
||||
TransportId t, long timePeriod, long base, byte[] bitmap)
|
||||
@@ -3120,6 +3189,29 @@ abstract class JdbcDatabase implements Database<Connection> {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSyncVersions(Connection txn, ContactId c,
|
||||
List<Byte> supported) throws DbException {
|
||||
PreparedStatement ps = null;
|
||||
try {
|
||||
String sql = "UPDATE contacts SET syncVersions = ?"
|
||||
+ " WHERE contactId = ?";
|
||||
ps = txn.prepareStatement(sql);
|
||||
byte[] bytes = new byte[supported.size()];
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
bytes[i] = supported.get(i);
|
||||
}
|
||||
ps.setBytes(1, bytes);
|
||||
ps.setInt(2, c.getInt());
|
||||
int affected = ps.executeUpdate();
|
||||
if (affected < 0 || affected > 1) throw new DbStateException();
|
||||
ps.close();
|
||||
} catch (SQLException e) {
|
||||
tryToClose(ps, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTransportKeysActive(Connection txn, TransportId t,
|
||||
KeySetId k) throws DbException {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package org.briarproject.bramble.db;
|
||||
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.db.JdbcUtils.tryToClose;
|
||||
|
||||
class Migration44_45 implements Migration<Connection> {
|
||||
|
||||
private static final Logger LOG = getLogger(Migration44_45.class.getName());
|
||||
|
||||
@Override
|
||||
public int getStartVersion() {
|
||||
return 44;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEndVersion() {
|
||||
return 45;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void migrate(Connection txn) throws DbException {
|
||||
Statement s = null;
|
||||
try {
|
||||
s = txn.createStatement();
|
||||
s.execute("ALTER TABLE pendingContacts DROP COLUMN state");
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package org.briarproject.bramble.db;
|
||||
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.db.JdbcUtils.tryToClose;
|
||||
|
||||
class Migration45_46 implements Migration<Connection> {
|
||||
|
||||
private static final Logger LOG = getLogger(Migration45_46.class.getName());
|
||||
|
||||
@Override
|
||||
public int getStartVersion() {
|
||||
return 45;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEndVersion() {
|
||||
return 46;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void migrate(Connection txn) throws DbException {
|
||||
Statement s = null;
|
||||
try {
|
||||
s = txn.createStatement();
|
||||
s.execute("ALTER TABLE messages"
|
||||
+ " ADD COLUMN temporary BOOLEAN DEFAULT FALSE NOT NULL");
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package org.briarproject.bramble.db;
|
||||
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.db.JdbcUtils.tryToClose;
|
||||
|
||||
class Migration46_47 implements Migration<Connection> {
|
||||
|
||||
private static final Logger LOG = getLogger(Migration46_47.class.getName());
|
||||
|
||||
private final DatabaseTypes dbTypes;
|
||||
|
||||
Migration46_47(DatabaseTypes dbTypes) {
|
||||
this.dbTypes = dbTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getStartVersion() {
|
||||
return 46;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getEndVersion() {
|
||||
return 47;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void migrate(Connection txn) throws DbException {
|
||||
Statement s = null;
|
||||
try {
|
||||
s = txn.createStatement();
|
||||
s.execute(dbTypes.replaceTypes("ALTER TABLE contacts"
|
||||
+ " ADD COLUMN syncVersions"
|
||||
+ " _BINARY DEFAULT '00' NOT NULL"));
|
||||
} catch (SQLException e) {
|
||||
tryToClose(s, LOG, WARNING);
|
||||
throw new DbException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.briarproject.bramble.keyagreement;
|
||||
|
||||
import org.briarproject.bramble.api.Predicate;
|
||||
import org.briarproject.bramble.api.keyagreement.KeyAgreementConnection;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.TransportId;
|
||||
@@ -10,6 +11,7 @@ import org.briarproject.bramble.api.record.RecordReaderFactory;
|
||||
import org.briarproject.bramble.api.record.RecordWriter;
|
||||
import org.briarproject.bramble.api.record.RecordWriterFactory;
|
||||
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
@@ -31,6 +33,20 @@ class KeyAgreementTransport {
|
||||
private static final Logger LOG =
|
||||
Logger.getLogger(KeyAgreementTransport.class.getName());
|
||||
|
||||
// Accept records with current protocol version, known record type
|
||||
private static Predicate<Record> ACCEPT = r ->
|
||||
r.getProtocolVersion() == PROTOCOL_VERSION &&
|
||||
isKnownRecordType(r.getRecordType());
|
||||
|
||||
// Ignore records with current protocol version, unknown record type
|
||||
private static Predicate<Record> IGNORE = r ->
|
||||
r.getProtocolVersion() == PROTOCOL_VERSION &&
|
||||
!isKnownRecordType(r.getRecordType());
|
||||
|
||||
private static boolean isKnownRecordType(byte type) {
|
||||
return type == KEY || type == CONFIRM || type == ABORT;
|
||||
}
|
||||
|
||||
private final KeyAgreementConnection kac;
|
||||
private final RecordReader reader;
|
||||
private final RecordWriter writer;
|
||||
@@ -94,22 +110,15 @@ class KeyAgreementTransport {
|
||||
}
|
||||
|
||||
private byte[] readRecord(byte expectedType) throws AbortException {
|
||||
while (true) {
|
||||
try {
|
||||
Record record = reader.readRecord();
|
||||
// Reject unrecognised protocol version
|
||||
if (record.getProtocolVersion() != PROTOCOL_VERSION)
|
||||
throw new AbortException(false);
|
||||
byte type = record.getRecordType();
|
||||
if (type == ABORT) throw new AbortException(true);
|
||||
if (type == expectedType) return record.getPayload();
|
||||
// Reject recognised but unexpected record type
|
||||
if (type == KEY || type == CONFIRM)
|
||||
throw new AbortException(false);
|
||||
// Skip unrecognised record type
|
||||
} catch (IOException e) {
|
||||
throw new AbortException(e);
|
||||
}
|
||||
try {
|
||||
Record record = reader.readRecord(ACCEPT, IGNORE);
|
||||
if (record == null) throw new AbortException(new EOFException());
|
||||
byte type = record.getRecordType();
|
||||
if (type == ABORT) throw new AbortException(true);
|
||||
if (type != expectedType) throw new AbortException(false);
|
||||
return record.getPayload();
|
||||
} catch (IOException e) {
|
||||
throw new AbortException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,8 +107,11 @@ class LifecycleManagerImpl implements LifecycleManager, MigrationListener {
|
||||
else logDuration(LOG, "Creating database", start);
|
||||
|
||||
db.transaction(false, txn -> {
|
||||
long start1 = now();
|
||||
db.removeTemporaryMessages(txn);
|
||||
logDuration(LOG, "Removing temporary messages", start1);
|
||||
for (OpenDatabaseHook hook : openDatabaseHooks) {
|
||||
long start1 = now();
|
||||
start1 = now();
|
||||
hook.onDatabaseOpened(txn);
|
||||
if (LOG.isLoggable(FINE)) {
|
||||
logDuration(LOG, "Calling open database hook "
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
package org.briarproject.bramble.plugin;
|
||||
|
||||
import org.briarproject.bramble.api.contact.Contact;
|
||||
import org.briarproject.bramble.api.contact.ContactExchangeManager;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.contact.HandshakeManager;
|
||||
import org.briarproject.bramble.api.contact.HandshakeManager.HandshakeResult;
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.ConnectionManager;
|
||||
import org.briarproject.bramble.api.plugin.ConnectionRegistry;
|
||||
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
|
||||
@@ -17,28 +23,34 @@ import org.briarproject.bramble.api.transport.StreamReaderFactory;
|
||||
import org.briarproject.bramble.api.transport.StreamWriter;
|
||||
import org.briarproject.bramble.api.transport.StreamWriterFactory;
|
||||
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
||||
import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH;
|
||||
import static org.briarproject.bramble.util.IoUtils.read;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
|
||||
@NotNullByDefault
|
||||
class ConnectionManagerImpl implements ConnectionManager {
|
||||
|
||||
private static final Logger LOG =
|
||||
Logger.getLogger(ConnectionManagerImpl.class.getName());
|
||||
getLogger(ConnectionManagerImpl.class.getName());
|
||||
|
||||
private final Executor ioExecutor;
|
||||
private final KeyManager keyManager;
|
||||
private final StreamReaderFactory streamReaderFactory;
|
||||
private final StreamWriterFactory streamWriterFactory;
|
||||
private final SyncSessionFactory syncSessionFactory;
|
||||
private final HandshakeManager handshakeManager;
|
||||
private final ContactExchangeManager contactExchangeManager;
|
||||
private final ConnectionRegistry connectionRegistry;
|
||||
|
||||
@Inject
|
||||
@@ -46,12 +58,16 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
KeyManager keyManager, StreamReaderFactory streamReaderFactory,
|
||||
StreamWriterFactory streamWriterFactory,
|
||||
SyncSessionFactory syncSessionFactory,
|
||||
HandshakeManager handshakeManager,
|
||||
ContactExchangeManager contactExchangeManager,
|
||||
ConnectionRegistry connectionRegistry) {
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.keyManager = keyManager;
|
||||
this.streamReaderFactory = streamReaderFactory;
|
||||
this.streamWriterFactory = streamWriterFactory;
|
||||
this.syncSessionFactory = syncSessionFactory;
|
||||
this.handshakeManager = handshakeManager;
|
||||
this.contactExchangeManager = contactExchangeManager;
|
||||
this.connectionRegistry = connectionRegistry;
|
||||
}
|
||||
|
||||
@@ -67,6 +83,12 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
ioExecutor.execute(new ManageIncomingDuplexConnection(t, d));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void manageIncomingConnection(PendingContactId p, TransportId t,
|
||||
DuplexTransportConnection d) {
|
||||
ioExecutor.execute(new ManageIncomingHandshakeConnection(p, t, d));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void manageOutgoingConnection(ContactId c, TransportId t,
|
||||
TransportConnectionWriter w) {
|
||||
@@ -79,16 +101,15 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
ioExecutor.execute(new ManageOutgoingDuplexConnection(c, t, d));
|
||||
}
|
||||
|
||||
private byte[] readTag(TransportConnectionReader r) throws IOException {
|
||||
// Read the tag
|
||||
@Override
|
||||
public void manageOutgoingConnection(PendingContactId p, TransportId t,
|
||||
DuplexTransportConnection d) {
|
||||
ioExecutor.execute(new ManageOutgoingHandshakeConnection(p, t, d));
|
||||
}
|
||||
|
||||
private byte[] readTag(InputStream in) throws IOException {
|
||||
byte[] tag = new byte[TAG_LENGTH];
|
||||
InputStream in = r.getInputStream();
|
||||
int offset = 0;
|
||||
while (offset < tag.length) {
|
||||
int read = in.read(tag, offset, tag.length - offset);
|
||||
if (read == -1) throw new EOFException();
|
||||
offset += read;
|
||||
}
|
||||
read(in, tag);
|
||||
return tag;
|
||||
}
|
||||
|
||||
@@ -96,28 +117,43 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
TransportConnectionReader r) throws IOException {
|
||||
InputStream streamReader = streamReaderFactory.createStreamReader(
|
||||
r.getInputStream(), ctx);
|
||||
// TODO: Pending contacts, handshake mode
|
||||
return syncSessionFactory.createIncomingSession(ctx.getContactId(),
|
||||
streamReader);
|
||||
ContactId c = requireNonNull(ctx.getContactId());
|
||||
return syncSessionFactory.createIncomingSession(c, streamReader);
|
||||
}
|
||||
|
||||
private SyncSession createSimplexOutgoingSession(StreamContext ctx,
|
||||
TransportConnectionWriter w) throws IOException {
|
||||
StreamWriter streamWriter = streamWriterFactory.createStreamWriter(
|
||||
w.getOutputStream(), ctx);
|
||||
// TODO: Pending contacts, handshake mode
|
||||
return syncSessionFactory.createSimplexOutgoingSession(
|
||||
ctx.getContactId(), w.getMaxLatency(), streamWriter);
|
||||
ContactId c = requireNonNull(ctx.getContactId());
|
||||
return syncSessionFactory.createSimplexOutgoingSession(c,
|
||||
w.getMaxLatency(), streamWriter);
|
||||
}
|
||||
|
||||
private SyncSession createDuplexOutgoingSession(StreamContext ctx,
|
||||
TransportConnectionWriter w) throws IOException {
|
||||
StreamWriter streamWriter = streamWriterFactory.createStreamWriter(
|
||||
w.getOutputStream(), ctx);
|
||||
// TODO: Pending contacts, handshake mode
|
||||
return syncSessionFactory.createDuplexOutgoingSession(
|
||||
ctx.getContactId(), w.getMaxLatency(), w.getMaxIdleTime(),
|
||||
streamWriter);
|
||||
ContactId c = requireNonNull(ctx.getContactId());
|
||||
return syncSessionFactory.createDuplexOutgoingSession(c,
|
||||
w.getMaxLatency(), w.getMaxIdleTime(), streamWriter);
|
||||
}
|
||||
|
||||
private void disposeOnError(TransportConnectionReader reader,
|
||||
boolean recognised) {
|
||||
try {
|
||||
reader.dispose(true, recognised);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
}
|
||||
|
||||
private void disposeOnError(TransportConnectionWriter writer) {
|
||||
try {
|
||||
writer.dispose(true);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
}
|
||||
|
||||
private class ManageIncomingSimplexConnection implements Runnable {
|
||||
@@ -136,40 +172,46 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
// Read and recognise the tag
|
||||
StreamContext ctx;
|
||||
try {
|
||||
byte[] tag = readTag(reader);
|
||||
byte[] tag = readTag(reader.getInputStream());
|
||||
ctx = keyManager.getStreamContext(transportId, tag);
|
||||
} catch (IOException | DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeReader(true, false);
|
||||
onError(false);
|
||||
return;
|
||||
}
|
||||
if (ctx == null) {
|
||||
LOG.info("Unrecognised tag");
|
||||
disposeReader(false, false);
|
||||
onError(false);
|
||||
return;
|
||||
}
|
||||
// TODO: Pending contacts
|
||||
ContactId contactId = ctx.getContactId();
|
||||
if (contactId == null) {
|
||||
LOG.warning("Received rendezvous stream, expected contact");
|
||||
onError(true);
|
||||
return;
|
||||
}
|
||||
if (ctx.isHandshakeMode()) {
|
||||
// TODO: Support handshake mode for contacts
|
||||
LOG.warning("Received handshake tag, expected rotation mode");
|
||||
onError(true);
|
||||
return;
|
||||
}
|
||||
connectionRegistry.registerConnection(contactId, transportId, true);
|
||||
try {
|
||||
// Create and run the incoming session
|
||||
createIncomingSession(ctx, reader).run();
|
||||
disposeReader(false, true);
|
||||
reader.dispose(false, true);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeReader(true, true);
|
||||
onError(true);
|
||||
} finally {
|
||||
connectionRegistry.unregisterConnection(contactId, transportId,
|
||||
true);
|
||||
}
|
||||
}
|
||||
|
||||
private void disposeReader(boolean exception, boolean recognised) {
|
||||
try {
|
||||
reader.dispose(exception, recognised);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
private void onError(boolean recognised) {
|
||||
disposeOnError(reader, recognised);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,12 +236,12 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
ctx = keyManager.getStreamContext(contactId, transportId);
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeWriter(true);
|
||||
onError();
|
||||
return;
|
||||
}
|
||||
if (ctx == null) {
|
||||
LOG.warning("Could not allocate stream context");
|
||||
disposeWriter(true);
|
||||
onError();
|
||||
return;
|
||||
}
|
||||
connectionRegistry.registerConnection(contactId, transportId,
|
||||
@@ -207,22 +249,18 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
try {
|
||||
// Create and run the outgoing session
|
||||
createSimplexOutgoingSession(ctx, writer).run();
|
||||
disposeWriter(false);
|
||||
writer.dispose(false);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeWriter(true);
|
||||
onError();
|
||||
} finally {
|
||||
connectionRegistry.unregisterConnection(contactId, transportId,
|
||||
false);
|
||||
}
|
||||
}
|
||||
|
||||
private void disposeWriter(boolean exception) {
|
||||
try {
|
||||
writer.dispose(exception);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
private void onError() {
|
||||
disposeOnError(writer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,15 +270,14 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
private final TransportConnectionReader reader;
|
||||
private final TransportConnectionWriter writer;
|
||||
|
||||
private volatile ContactId contactId = null;
|
||||
private volatile SyncSession incomingSession = null;
|
||||
@Nullable
|
||||
private volatile SyncSession outgoingSession = null;
|
||||
|
||||
private ManageIncomingDuplexConnection(TransportId transportId,
|
||||
DuplexTransportConnection transport) {
|
||||
DuplexTransportConnection connection) {
|
||||
this.transportId = transportId;
|
||||
reader = transport.getReader();
|
||||
writer = transport.getWriter();
|
||||
reader = connection.getReader();
|
||||
writer = connection.getWriter();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -248,82 +285,87 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
// Read and recognise the tag
|
||||
StreamContext ctx;
|
||||
try {
|
||||
byte[] tag = readTag(reader);
|
||||
byte[] tag = readTag(reader.getInputStream());
|
||||
ctx = keyManager.getStreamContext(transportId, tag);
|
||||
} catch (IOException | DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeReader(true, false);
|
||||
onReadError(false);
|
||||
return;
|
||||
}
|
||||
if (ctx == null) {
|
||||
LOG.info("Unrecognised tag");
|
||||
disposeReader(false, false);
|
||||
onReadError(false);
|
||||
return;
|
||||
}
|
||||
ContactId contactId = ctx.getContactId();
|
||||
if (contactId == null) {
|
||||
LOG.warning("Expected contact tag, got rendezvous tag");
|
||||
onReadError(true);
|
||||
return;
|
||||
}
|
||||
if (ctx.isHandshakeMode()) {
|
||||
// TODO: Support handshake mode for contacts
|
||||
LOG.warning("Received handshake tag, expected rotation mode");
|
||||
onReadError(true);
|
||||
return;
|
||||
}
|
||||
contactId = ctx.getContactId();
|
||||
connectionRegistry.registerConnection(contactId, transportId, true);
|
||||
// Start the outgoing session on another thread
|
||||
ioExecutor.execute(this::runOutgoingSession);
|
||||
ioExecutor.execute(() -> runOutgoingSession(contactId));
|
||||
try {
|
||||
// Create and run the incoming session
|
||||
incomingSession = createIncomingSession(ctx, reader);
|
||||
incomingSession.run();
|
||||
disposeReader(false, true);
|
||||
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 (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeReader(true, true);
|
||||
onReadError(true);
|
||||
} finally {
|
||||
connectionRegistry.unregisterConnection(contactId, transportId,
|
||||
true);
|
||||
}
|
||||
}
|
||||
|
||||
private void runOutgoingSession() {
|
||||
private void runOutgoingSession(ContactId contactId) {
|
||||
// Allocate a stream context
|
||||
StreamContext ctx;
|
||||
try {
|
||||
ctx = keyManager.getStreamContext(contactId, transportId);
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeWriter(true);
|
||||
onWriteError();
|
||||
return;
|
||||
}
|
||||
if (ctx == null) {
|
||||
LOG.warning("Could not allocate stream context");
|
||||
disposeWriter(true);
|
||||
onWriteError();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// Create and run the outgoing session
|
||||
outgoingSession = createDuplexOutgoingSession(ctx, writer);
|
||||
outgoingSession.run();
|
||||
disposeWriter(false);
|
||||
SyncSession out = createDuplexOutgoingSession(ctx, writer);
|
||||
outgoingSession = out;
|
||||
out.run();
|
||||
writer.dispose(false);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeWriter(true);
|
||||
onWriteError();
|
||||
}
|
||||
}
|
||||
|
||||
private void disposeReader(boolean exception, boolean recognised) {
|
||||
// Interrupt the outgoing session so it finishes cleanly
|
||||
if (outgoingSession != null) outgoingSession.interrupt();
|
||||
try {
|
||||
reader.dispose(exception, recognised);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
private void onReadError(boolean recognised) {
|
||||
disposeOnError(reader, recognised);
|
||||
disposeOnError(writer);
|
||||
// Interrupt the outgoing session so it finishes
|
||||
SyncSession out = outgoingSession;
|
||||
if (out != null) out.interrupt();
|
||||
}
|
||||
|
||||
private void disposeWriter(boolean exception) {
|
||||
// Interrupt the incoming session if an exception occurred,
|
||||
// otherwise wait for the end of stream marker
|
||||
if (exception && incomingSession != null)
|
||||
incomingSession.interrupt();
|
||||
try {
|
||||
writer.dispose(exception);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
private void onWriteError() {
|
||||
disposeOnError(reader, true);
|
||||
disposeOnError(writer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -334,15 +376,15 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
private final TransportConnectionReader reader;
|
||||
private final TransportConnectionWriter writer;
|
||||
|
||||
private volatile SyncSession incomingSession = null;
|
||||
@Nullable
|
||||
private volatile SyncSession outgoingSession = null;
|
||||
|
||||
private ManageOutgoingDuplexConnection(ContactId contactId,
|
||||
TransportId transportId, DuplexTransportConnection transport) {
|
||||
TransportId transportId, DuplexTransportConnection connection) {
|
||||
this.contactId = contactId;
|
||||
this.transportId = transportId;
|
||||
reader = transport.getReader();
|
||||
writer = transport.getWriter();
|
||||
reader = connection.getReader();
|
||||
writer = connection.getWriter();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -353,24 +395,31 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
ctx = keyManager.getStreamContext(contactId, transportId);
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeWriter(true);
|
||||
onWriteError();
|
||||
return;
|
||||
}
|
||||
if (ctx == null) {
|
||||
LOG.warning("Could not allocate stream context");
|
||||
disposeWriter(true);
|
||||
onWriteError();
|
||||
return;
|
||||
}
|
||||
if (ctx.isHandshakeMode()) {
|
||||
// TODO: Support handshake mode for contacts
|
||||
LOG.warning("Cannot use handshake mode stream context");
|
||||
onWriteError();
|
||||
return;
|
||||
}
|
||||
// Start the incoming session on another thread
|
||||
ioExecutor.execute(this::runIncomingSession);
|
||||
try {
|
||||
// Create and run the outgoing session
|
||||
outgoingSession = createDuplexOutgoingSession(ctx, writer);
|
||||
outgoingSession.run();
|
||||
disposeWriter(false);
|
||||
SyncSession out = createDuplexOutgoingSession(ctx, writer);
|
||||
outgoingSession = out;
|
||||
out.run();
|
||||
writer.dispose(false);
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeWriter(true);
|
||||
onWriteError();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -378,61 +427,268 @@ class ConnectionManagerImpl implements ConnectionManager {
|
||||
// Read and recognise the tag
|
||||
StreamContext ctx;
|
||||
try {
|
||||
byte[] tag = readTag(reader);
|
||||
byte[] tag = readTag(reader.getInputStream());
|
||||
ctx = keyManager.getStreamContext(transportId, tag);
|
||||
} catch (IOException | DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeReader(true, false);
|
||||
onReadError();
|
||||
return;
|
||||
}
|
||||
// Unrecognised tags are suspicious in this case
|
||||
if (ctx == null) {
|
||||
LOG.warning("Unrecognised tag for returning stream");
|
||||
disposeReader(true, false);
|
||||
onReadError();
|
||||
return;
|
||||
}
|
||||
// Check that the stream comes from the expected contact
|
||||
if (!contactId.equals(ctx.getContactId())) {
|
||||
ContactId inContactId = ctx.getContactId();
|
||||
if (inContactId == null) {
|
||||
LOG.warning("Expected contact tag, got rendezvous tag");
|
||||
onReadError();
|
||||
return;
|
||||
}
|
||||
if (!contactId.equals(inContactId)) {
|
||||
LOG.warning("Wrong contact ID for returning stream");
|
||||
disposeReader(true, true);
|
||||
onReadError();
|
||||
return;
|
||||
}
|
||||
if (ctx.isHandshakeMode()) {
|
||||
// TODO: Support handshake mode for contacts
|
||||
LOG.warning("Received handshake tag, expected rotation mode");
|
||||
onReadError();
|
||||
return;
|
||||
}
|
||||
connectionRegistry.registerConnection(contactId, transportId,
|
||||
false);
|
||||
try {
|
||||
// Create and run the incoming session
|
||||
incomingSession = createIncomingSession(ctx, reader);
|
||||
incomingSession.run();
|
||||
disposeReader(false, true);
|
||||
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 (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
disposeReader(true, true);
|
||||
onReadError();
|
||||
} finally {
|
||||
connectionRegistry.unregisterConnection(contactId, transportId,
|
||||
false);
|
||||
}
|
||||
}
|
||||
|
||||
private void disposeReader(boolean exception, boolean recognised) {
|
||||
// Interrupt the outgoing session so it finishes cleanly
|
||||
if (outgoingSession != null) outgoingSession.interrupt();
|
||||
private void onReadError() {
|
||||
// 'Recognised' is always true for outgoing connections
|
||||
disposeOnError(reader, true);
|
||||
disposeOnError(writer);
|
||||
// Interrupt the outgoing session so it finishes
|
||||
SyncSession out = outgoingSession;
|
||||
if (out != null) out.interrupt();
|
||||
}
|
||||
|
||||
private void onWriteError() {
|
||||
disposeOnError(reader, true);
|
||||
disposeOnError(writer);
|
||||
}
|
||||
}
|
||||
|
||||
private class ManageIncomingHandshakeConnection implements Runnable {
|
||||
|
||||
private final PendingContactId pendingContactId;
|
||||
private final TransportId transportId;
|
||||
private final DuplexTransportConnection connection;
|
||||
private final TransportConnectionReader reader;
|
||||
private final TransportConnectionWriter writer;
|
||||
|
||||
private ManageIncomingHandshakeConnection(
|
||||
PendingContactId pendingContactId, TransportId transportId,
|
||||
DuplexTransportConnection connection) {
|
||||
this.pendingContactId = pendingContactId;
|
||||
this.transportId = transportId;
|
||||
this.connection = connection;
|
||||
reader = connection.getReader();
|
||||
writer = connection.getWriter();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// Read and recognise the tag
|
||||
StreamContext ctxIn;
|
||||
try {
|
||||
reader.dispose(exception, recognised);
|
||||
} catch (IOException e) {
|
||||
byte[] tag = readTag(reader.getInputStream());
|
||||
ctxIn = keyManager.getStreamContext(transportId, tag);
|
||||
} catch (IOException | DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
onError(false);
|
||||
return;
|
||||
}
|
||||
if (ctxIn == null) {
|
||||
LOG.info("Unrecognised tag");
|
||||
onError(false);
|
||||
return;
|
||||
}
|
||||
PendingContactId inPendingContactId = ctxIn.getPendingContactId();
|
||||
if (inPendingContactId == null) {
|
||||
LOG.warning("Expected rendezvous tag, got contact tag");
|
||||
onError(true);
|
||||
return;
|
||||
}
|
||||
// Allocate the outgoing stream context
|
||||
StreamContext ctxOut;
|
||||
try {
|
||||
ctxOut = keyManager.getStreamContext(pendingContactId,
|
||||
transportId);
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
onError(true);
|
||||
return;
|
||||
}
|
||||
if (ctxOut == null) {
|
||||
LOG.warning("Could not allocate stream context");
|
||||
onError(true);
|
||||
return;
|
||||
}
|
||||
// Close the connection if it's redundant
|
||||
if (!connectionRegistry.registerConnection(pendingContactId)) {
|
||||
LOG.info("Redundant rendezvous connection");
|
||||
onError(true);
|
||||
return;
|
||||
}
|
||||
// Handshake and exchange contacts
|
||||
try {
|
||||
InputStream in = streamReaderFactory.createStreamReader(
|
||||
reader.getInputStream(), ctxIn);
|
||||
// Flush the output stream to send the outgoing stream header
|
||||
StreamWriter out = streamWriterFactory.createStreamWriter(
|
||||
writer.getOutputStream(), ctxOut);
|
||||
out.getOutputStream().flush();
|
||||
HandshakeResult result = handshakeManager.handshake(
|
||||
pendingContactId, in, out);
|
||||
Contact contact = contactExchangeManager.exchangeContacts(
|
||||
pendingContactId, connection, result.getMasterKey(),
|
||||
result.isAlice(), false);
|
||||
connectionRegistry.unregisterConnection(pendingContactId, true);
|
||||
// Reuse the connection as a transport connection
|
||||
manageOutgoingConnection(contact.getId(), transportId,
|
||||
connection);
|
||||
} catch (IOException | DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
onError(true);
|
||||
connectionRegistry.unregisterConnection(pendingContactId,
|
||||
false);
|
||||
}
|
||||
}
|
||||
|
||||
private void disposeWriter(boolean exception) {
|
||||
// Interrupt the incoming session if an exception occurred,
|
||||
// otherwise wait for the end of stream marker
|
||||
if (exception && incomingSession != null)
|
||||
incomingSession.interrupt();
|
||||
private void onError(boolean recognised) {
|
||||
disposeOnError(reader, recognised);
|
||||
disposeOnError(writer);
|
||||
}
|
||||
}
|
||||
|
||||
private class ManageOutgoingHandshakeConnection implements Runnable {
|
||||
|
||||
private final PendingContactId pendingContactId;
|
||||
private final TransportId transportId;
|
||||
private final DuplexTransportConnection connection;
|
||||
private final TransportConnectionReader reader;
|
||||
private final TransportConnectionWriter writer;
|
||||
|
||||
private ManageOutgoingHandshakeConnection(
|
||||
PendingContactId pendingContactId, TransportId transportId,
|
||||
DuplexTransportConnection connection) {
|
||||
this.pendingContactId = pendingContactId;
|
||||
this.transportId = transportId;
|
||||
this.connection = connection;
|
||||
reader = connection.getReader();
|
||||
writer = connection.getWriter();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// Allocate the outgoing stream context
|
||||
StreamContext ctxOut;
|
||||
try {
|
||||
writer.dispose(exception);
|
||||
ctxOut = keyManager.getStreamContext(pendingContactId,
|
||||
transportId);
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
onError();
|
||||
return;
|
||||
}
|
||||
if (ctxOut == null) {
|
||||
LOG.warning("Could not allocate stream context");
|
||||
onError();
|
||||
return;
|
||||
}
|
||||
// Flush the output stream to send the outgoing stream header
|
||||
StreamWriter out;
|
||||
try {
|
||||
out = streamWriterFactory.createStreamWriter(
|
||||
writer.getOutputStream(), ctxOut);
|
||||
out.getOutputStream().flush();
|
||||
} catch (IOException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
onError();
|
||||
return;
|
||||
}
|
||||
// Read and recognise the tag
|
||||
StreamContext ctxIn;
|
||||
try {
|
||||
byte[] tag = readTag(reader.getInputStream());
|
||||
ctxIn = keyManager.getStreamContext(transportId, tag);
|
||||
} catch (IOException | DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
onError();
|
||||
return;
|
||||
}
|
||||
// Unrecognised tags are suspicious in this case
|
||||
if (ctxIn == null) {
|
||||
LOG.warning("Unrecognised tag for returning stream");
|
||||
onError();
|
||||
return;
|
||||
}
|
||||
// Check that the stream comes from the expected pending contact
|
||||
PendingContactId inPendingContactId = ctxIn.getPendingContactId();
|
||||
if (inPendingContactId == null) {
|
||||
LOG.warning("Expected rendezvous tag, got contact tag");
|
||||
onError();
|
||||
return;
|
||||
}
|
||||
if (!inPendingContactId.equals(pendingContactId)) {
|
||||
LOG.warning("Wrong pending contact ID for returning stream");
|
||||
onError();
|
||||
return;
|
||||
}
|
||||
// Close the connection if it's redundant
|
||||
if (!connectionRegistry.registerConnection(pendingContactId)) {
|
||||
LOG.info("Redundant rendezvous connection");
|
||||
onError();
|
||||
return;
|
||||
}
|
||||
// Handshake and exchange contacts
|
||||
try {
|
||||
InputStream in = streamReaderFactory.createStreamReader(
|
||||
reader.getInputStream(), ctxIn);
|
||||
HandshakeResult result = handshakeManager.handshake(
|
||||
pendingContactId, in, out);
|
||||
Contact contact = contactExchangeManager.exchangeContacts(
|
||||
pendingContactId, connection, result.getMasterKey(),
|
||||
result.isAlice(), false);
|
||||
connectionRegistry.unregisterConnection(pendingContactId, true);
|
||||
// Reuse the connection as a transport connection
|
||||
manageOutgoingConnection(contact.getId(), transportId,
|
||||
connection);
|
||||
} catch (IOException | DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
onError();
|
||||
connectionRegistry.unregisterConnection(pendingContactId,
|
||||
false);
|
||||
}
|
||||
}
|
||||
|
||||
private void onError() {
|
||||
// 'Recognised' is always true for outgoing connections
|
||||
disposeOnError(reader, true);
|
||||
disposeOnError(writer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package org.briarproject.bramble.plugin;
|
||||
|
||||
import org.briarproject.bramble.api.Multiset;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.contact.PendingContactId;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.plugin.ConnectionRegistry;
|
||||
@@ -10,41 +11,49 @@ import org.briarproject.bramble.api.plugin.event.ConnectionClosedEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.ConnectionOpenedEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.ContactConnectedEvent;
|
||||
import org.briarproject.bramble.api.plugin.event.ContactDisconnectedEvent;
|
||||
import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionClosedEvent;
|
||||
import org.briarproject.bramble.api.rendezvous.event.RendezvousConnectionOpenedEvent;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static java.util.logging.Level.INFO;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
|
||||
@ThreadSafe
|
||||
@NotNullByDefault
|
||||
class ConnectionRegistryImpl implements ConnectionRegistry {
|
||||
|
||||
private static final Logger LOG =
|
||||
Logger.getLogger(ConnectionRegistryImpl.class.getName());
|
||||
getLogger(ConnectionRegistryImpl.class.getName());
|
||||
|
||||
private final EventBus eventBus;
|
||||
private final Lock lock = new ReentrantLock();
|
||||
|
||||
// The following are locking: lock
|
||||
private final Map<TransportId, Multiset<ContactId>> connections;
|
||||
private final Object lock = new Object();
|
||||
@GuardedBy("lock")
|
||||
private final Map<TransportId, Multiset<ContactId>> contactConnections;
|
||||
@GuardedBy("lock")
|
||||
private final Multiset<ContactId> contactCounts;
|
||||
@GuardedBy("lock")
|
||||
private final Set<PendingContactId> connectedPendingContacts;
|
||||
|
||||
@Inject
|
||||
ConnectionRegistryImpl(EventBus eventBus) {
|
||||
this.eventBus = eventBus;
|
||||
connections = new HashMap<>();
|
||||
contactConnections = new HashMap<>();
|
||||
contactCounts = new Multiset<>();
|
||||
connectedPendingContacts = new HashSet<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -55,17 +64,14 @@ class ConnectionRegistryImpl implements ConnectionRegistry {
|
||||
else LOG.info("Outgoing connection registered: " + t);
|
||||
}
|
||||
boolean firstConnection = false;
|
||||
lock.lock();
|
||||
try {
|
||||
Multiset<ContactId> m = connections.get(t);
|
||||
synchronized (lock) {
|
||||
Multiset<ContactId> m = contactConnections.get(t);
|
||||
if (m == null) {
|
||||
m = new Multiset<>();
|
||||
connections.put(t, m);
|
||||
contactConnections.put(t, m);
|
||||
}
|
||||
m.add(c);
|
||||
if (contactCounts.add(c) == 1) firstConnection = true;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
eventBus.broadcast(new ConnectionOpenedEvent(c, t, incoming));
|
||||
if (firstConnection) {
|
||||
@@ -82,14 +88,12 @@ class ConnectionRegistryImpl implements ConnectionRegistry {
|
||||
else LOG.info("Outgoing connection unregistered: " + t);
|
||||
}
|
||||
boolean lastConnection = false;
|
||||
lock.lock();
|
||||
try {
|
||||
Multiset<ContactId> m = connections.get(t);
|
||||
if (m == null) throw new IllegalArgumentException();
|
||||
synchronized (lock) {
|
||||
Multiset<ContactId> m = contactConnections.get(t);
|
||||
if (m == null || !m.contains(c))
|
||||
throw new IllegalArgumentException();
|
||||
m.remove(c);
|
||||
if (contactCounts.remove(c) == 0) lastConnection = true;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
eventBus.broadcast(new ConnectionClosedEvent(c, t, incoming));
|
||||
if (lastConnection) {
|
||||
@@ -100,37 +104,47 @@ class ConnectionRegistryImpl implements ConnectionRegistry {
|
||||
|
||||
@Override
|
||||
public Collection<ContactId> getConnectedContacts(TransportId t) {
|
||||
lock.lock();
|
||||
try {
|
||||
Multiset<ContactId> m = connections.get(t);
|
||||
synchronized (lock) {
|
||||
Multiset<ContactId> m = contactConnections.get(t);
|
||||
if (m == null) return Collections.emptyList();
|
||||
List<ContactId> ids = new ArrayList<>(m.keySet());
|
||||
if (LOG.isLoggable(INFO))
|
||||
LOG.info(ids.size() + " contacts connected: " + t);
|
||||
return ids;
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConnected(ContactId c, TransportId t) {
|
||||
lock.lock();
|
||||
try {
|
||||
Multiset<ContactId> m = connections.get(t);
|
||||
synchronized (lock) {
|
||||
Multiset<ContactId> m = contactConnections.get(t);
|
||||
return m != null && m.contains(c);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConnected(ContactId c) {
|
||||
lock.lock();
|
||||
try {
|
||||
synchronized (lock) {
|
||||
return contactCounts.contains(c);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean registerConnection(PendingContactId p) {
|
||||
boolean added;
|
||||
synchronized (lock) {
|
||||
added = connectedPendingContacts.add(p);
|
||||
}
|
||||
if (added) eventBus.broadcast(new RendezvousConnectionOpenedEvent(p));
|
||||
return added;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unregisterConnection(PendingContactId p, boolean success) {
|
||||
synchronized (lock) {
|
||||
if (!connectedPendingContacts.remove(p))
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
eventBus.broadcast(new RendezvousConnectionClosedEvent(p, success));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.briarproject.bramble.plugin;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.db.DbException;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
@@ -8,7 +7,6 @@ import org.briarproject.bramble.api.lifecycle.Service;
|
||||
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.ConnectionRegistry;
|
||||
import org.briarproject.bramble.api.plugin.Plugin;
|
||||
import org.briarproject.bramble.api.plugin.PluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.PluginConfig;
|
||||
@@ -18,22 +16,17 @@ 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.DuplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginCallback;
|
||||
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.simplex.SimplexPlugin;
|
||||
import org.briarproject.bramble.api.plugin.simplex.SimplexPluginCallback;
|
||||
import org.briarproject.bramble.api.plugin.simplex.SimplexPluginFactory;
|
||||
import org.briarproject.bramble.api.properties.TransportProperties;
|
||||
import org.briarproject.bramble.api.properties.TransportPropertyManager;
|
||||
import org.briarproject.bramble.api.settings.Settings;
|
||||
import org.briarproject.bramble.api.settings.SettingsManager;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.api.system.Scheduler;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
@@ -42,7 +35,6 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
@@ -52,6 +44,7 @@ import javax.inject.Inject;
|
||||
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.util.LogUtils.logDuration;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
import static org.briarproject.bramble.util.LogUtils.now;
|
||||
@@ -61,18 +54,14 @@ import static org.briarproject.bramble.util.LogUtils.now;
|
||||
class PluginManagerImpl implements PluginManager, Service {
|
||||
|
||||
private static final Logger LOG =
|
||||
Logger.getLogger(PluginManagerImpl.class.getName());
|
||||
getLogger(PluginManagerImpl.class.getName());
|
||||
|
||||
private final Executor ioExecutor;
|
||||
private final ScheduledExecutorService scheduler;
|
||||
private final EventBus eventBus;
|
||||
private final PluginConfig pluginConfig;
|
||||
private final ConnectionManager connectionManager;
|
||||
private final ConnectionRegistry connectionRegistry;
|
||||
private final SettingsManager settingsManager;
|
||||
private final TransportPropertyManager transportPropertyManager;
|
||||
private final SecureRandom random;
|
||||
private final Clock clock;
|
||||
private final Map<TransportId, Plugin> plugins;
|
||||
private final List<SimplexPlugin> simplexPlugins;
|
||||
private final List<DuplexPlugin> duplexPlugins;
|
||||
@@ -80,46 +69,30 @@ class PluginManagerImpl implements PluginManager, Service {
|
||||
private final AtomicBoolean used = new AtomicBoolean(false);
|
||||
|
||||
@Inject
|
||||
PluginManagerImpl(@IoExecutor Executor ioExecutor,
|
||||
@Scheduler ScheduledExecutorService scheduler, EventBus eventBus,
|
||||
PluginManagerImpl(@IoExecutor Executor ioExecutor, EventBus eventBus,
|
||||
PluginConfig pluginConfig, ConnectionManager connectionManager,
|
||||
ConnectionRegistry connectionRegistry,
|
||||
SettingsManager settingsManager,
|
||||
TransportPropertyManager transportPropertyManager,
|
||||
SecureRandom random, Clock clock) {
|
||||
TransportPropertyManager transportPropertyManager) {
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.scheduler = scheduler;
|
||||
this.eventBus = eventBus;
|
||||
this.pluginConfig = pluginConfig;
|
||||
this.connectionManager = connectionManager;
|
||||
this.connectionRegistry = connectionRegistry;
|
||||
this.settingsManager = settingsManager;
|
||||
this.transportPropertyManager = transportPropertyManager;
|
||||
this.random = random;
|
||||
this.clock = clock;
|
||||
plugins = new ConcurrentHashMap<>();
|
||||
simplexPlugins = new CopyOnWriteArrayList<>();
|
||||
duplexPlugins = new CopyOnWriteArrayList<>();
|
||||
startLatches = new ConcurrentHashMap<>();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startService() {
|
||||
if (used.getAndSet(true)) throw new IllegalStateException();
|
||||
// Instantiate the poller
|
||||
if (pluginConfig.shouldPoll()) {
|
||||
LOG.info("Starting poller");
|
||||
Poller poller = new Poller(ioExecutor, scheduler, connectionManager,
|
||||
connectionRegistry, this, transportPropertyManager, random,
|
||||
clock);
|
||||
eventBus.addListener(poller);
|
||||
}
|
||||
// Instantiate the simplex plugins and start them asynchronously
|
||||
LOG.info("Starting simplex plugins");
|
||||
for (SimplexPluginFactory f : pluginConfig.getSimplexFactories()) {
|
||||
TransportId t = f.getId();
|
||||
SimplexPlugin s = f.createPlugin(new SimplexCallback(t));
|
||||
SimplexPlugin s = f.createPlugin(new Callback(t));
|
||||
if (s == null) {
|
||||
if (LOG.isLoggable(WARNING))
|
||||
LOG.warning("Could not create plugin for " + t);
|
||||
@@ -135,7 +108,7 @@ class PluginManagerImpl implements PluginManager, Service {
|
||||
LOG.info("Starting duplex plugins");
|
||||
for (DuplexPluginFactory f : pluginConfig.getDuplexFactories()) {
|
||||
TransportId t = f.getId();
|
||||
DuplexPlugin d = f.createPlugin(new DuplexCallback(t));
|
||||
DuplexPlugin d = f.createPlugin(new Callback(t));
|
||||
if (d == null) {
|
||||
if (LOG.isLoggable(WARNING))
|
||||
LOG.warning("Could not create plugin for " + t);
|
||||
@@ -196,6 +169,14 @@ class PluginManagerImpl implements PluginManager, Service {
|
||||
return supported;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<DuplexPlugin> getRendezvousPlugins() {
|
||||
List<DuplexPlugin> supported = new ArrayList<>();
|
||||
for (DuplexPlugin d : duplexPlugins)
|
||||
if (d.supportsRendezvous()) supported.add(d);
|
||||
return supported;
|
||||
}
|
||||
|
||||
private class PluginStarter implements Runnable {
|
||||
|
||||
private final Plugin plugin;
|
||||
@@ -266,12 +247,12 @@ class PluginManagerImpl implements PluginManager, Service {
|
||||
}
|
||||
}
|
||||
|
||||
@NotNullByDefault
|
||||
private abstract class PluginCallbackImpl implements PluginCallback {
|
||||
private class Callback implements PluginCallback {
|
||||
|
||||
protected final TransportId id;
|
||||
private final TransportId id;
|
||||
private final AtomicBoolean enabled = new AtomicBoolean(false);
|
||||
|
||||
PluginCallbackImpl(TransportId id) {
|
||||
private Callback(TransportId id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@@ -315,51 +296,30 @@ class PluginManagerImpl implements PluginManager, Service {
|
||||
|
||||
@Override
|
||||
public void transportEnabled() {
|
||||
eventBus.broadcast(new TransportEnabledEvent(id));
|
||||
if (!enabled.getAndSet(true))
|
||||
eventBus.broadcast(new TransportEnabledEvent(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transportDisabled() {
|
||||
eventBus.broadcast(new TransportDisabledEvent(id));
|
||||
}
|
||||
}
|
||||
|
||||
@NotNullByDefault
|
||||
private class SimplexCallback extends PluginCallbackImpl
|
||||
implements SimplexPluginCallback {
|
||||
|
||||
private SimplexCallback(TransportId id) {
|
||||
super(id);
|
||||
if (enabled.getAndSet(false))
|
||||
eventBus.broadcast(new TransportDisabledEvent(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readerCreated(TransportConnectionReader r) {
|
||||
connectionManager.manageIncomingConnection(id, r);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writerCreated(ContactId c, TransportConnectionWriter w) {
|
||||
connectionManager.manageOutgoingConnection(c, id, w);
|
||||
}
|
||||
}
|
||||
|
||||
@NotNullByDefault
|
||||
private class DuplexCallback extends PluginCallbackImpl
|
||||
implements DuplexPluginCallback {
|
||||
|
||||
private DuplexCallback(TransportId id) {
|
||||
super(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void incomingConnectionCreated(DuplexTransportConnection d) {
|
||||
public void handleConnection(DuplexTransportConnection d) {
|
||||
connectionManager.manageIncomingConnection(id, d);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void outgoingConnectionCreated(ContactId c,
|
||||
DuplexTransportConnection d) {
|
||||
connectionManager.manageOutgoingConnection(c, id, d);
|
||||
public void handleReader(TransportConnectionReader r) {
|
||||
connectionManager.manageIncomingConnection(id, r);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleWriter(TransportConnectionWriter w) {
|
||||
// TODO: Support simplex plugins that write to incoming connections
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package org.briarproject.bramble.plugin;
|
||||
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
|
||||
import org.briarproject.bramble.api.plugin.BackoffFactory;
|
||||
import org.briarproject.bramble.api.plugin.ConnectionManager;
|
||||
import org.briarproject.bramble.api.plugin.ConnectionRegistry;
|
||||
import org.briarproject.bramble.api.plugin.PluginConfig;
|
||||
import org.briarproject.bramble.api.plugin.PluginManager;
|
||||
|
||||
import javax.inject.Inject;
|
||||
@@ -18,6 +20,8 @@ public class PluginModule {
|
||||
public static class EagerSingletons {
|
||||
@Inject
|
||||
PluginManager pluginManager;
|
||||
@Inject
|
||||
Poller poller;
|
||||
}
|
||||
|
||||
@Provides
|
||||
@@ -46,4 +50,12 @@ public class PluginModule {
|
||||
lifecycleManager.registerService(pluginManager);
|
||||
return pluginManager;
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
Poller providePoller(PluginConfig config, EventBus eventBus,
|
||||
PollerImpl poller) {
|
||||
if (config.shouldPoll()) eventBus.addListener(poller);
|
||||
return poller;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user