mirror of
https://code.briarproject.org/briar/briar.git
synced 2026-02-12 10:49:06 +01:00
Compare commits
67 Commits
alpha-1.4.
...
2343-mailb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fdcacde915 | ||
|
|
e74021f571 | ||
|
|
6b6880c1ff | ||
|
|
5defd500ae | ||
|
|
37ff06d192 | ||
|
|
85aa21ebf6 | ||
|
|
e448699895 | ||
|
|
200f83bcfe | ||
|
|
89cce89650 | ||
|
|
8982964fbf | ||
|
|
f3a3fa0ea8 | ||
|
|
0865a06ac8 | ||
|
|
f2738c8bc4 | ||
|
|
1321f8775e | ||
|
|
9764aba47d | ||
|
|
913e5da2f5 | ||
|
|
f2ce7a386b | ||
|
|
7607b65e82 | ||
|
|
c13c2d62f5 | ||
|
|
8ea7204cf6 | ||
|
|
6ec382cfc4 | ||
|
|
ad0b28a684 | ||
|
|
0ae94e9579 | ||
|
|
57bd5789d4 | ||
|
|
f7dde1250c | ||
|
|
13d96651b4 | ||
|
|
65029982ce | ||
|
|
380921ce25 | ||
|
|
87ee8cd653 | ||
|
|
d4810a6f71 | ||
|
|
aa56aba1a5 | ||
|
|
35438dbac1 | ||
|
|
543b1178a1 | ||
|
|
7f1071f5cd | ||
|
|
e8c694fe00 | ||
|
|
b58b0c74a9 | ||
|
|
9e5029917e | ||
|
|
12ca74f86a | ||
|
|
622683f45e | ||
|
|
a5563ead28 | ||
|
|
e15f49fde7 | ||
|
|
e66f92f27e | ||
|
|
44acda2045 | ||
|
|
afd92dd916 | ||
|
|
2a969f8e0b | ||
|
|
ddc6606ccf | ||
|
|
1531a24b2d | ||
|
|
2298818af5 | ||
|
|
a19a4f36c6 | ||
|
|
6765de992d | ||
|
|
0ae5361281 | ||
|
|
d8e26eebbe | ||
|
|
692e353046 | ||
|
|
b9ba7aded5 | ||
|
|
4bca9decc1 | ||
|
|
7bbe9068bb | ||
|
|
63060679a3 | ||
|
|
ddb759dbb8 | ||
|
|
feb8854678 | ||
|
|
1af52b21d5 | ||
|
|
b24a18b231 | ||
|
|
8e83743dd7 | ||
|
|
6a91d18003 | ||
|
|
e481a02126 | ||
|
|
825dff27fc | ||
|
|
de3a87fff5 | ||
|
|
85d1addd04 |
10
CONTRIBUTING.md
Normal file
10
CONTRIBUTING.md
Normal file
@@ -0,0 +1,10 @@
|
||||
Folder-Description:
|
||||
===================
|
||||
* `briar-*`: Specifically for the Briar app (Phone/Desktop/Headless)
|
||||
* `bramble-*`: The protocol stack - not necessarily Briar-dependent
|
||||
|
||||
---
|
||||
|
||||
* `*-api`: public stuff that can be referenced from other packages and modules - mostly interfaces + a few utility classes
|
||||
* `*-core`: implementations of api that are portable across Android/Desktop/Headless
|
||||
* `*-java`: implementations of api that are specific to Desktop & Headless
|
||||
@@ -15,8 +15,8 @@ android {
|
||||
defaultConfig {
|
||||
minSdkVersion 16
|
||||
targetSdkVersion 30
|
||||
versionCode 10409
|
||||
versionName "1.4.9"
|
||||
versionCode 10410
|
||||
versionName "1.4.10"
|
||||
consumerProguardFiles 'proguard-rules.txt'
|
||||
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
|
||||
@@ -37,8 +37,14 @@ public interface LifecycleManager {
|
||||
*/
|
||||
enum LifecycleState {
|
||||
|
||||
STARTING, MIGRATING_DATABASE, COMPACTING_DATABASE, STARTING_SERVICES,
|
||||
RUNNING, STOPPING;
|
||||
CREATED,
|
||||
STARTING,
|
||||
MIGRATING_DATABASE,
|
||||
COMPACTING_DATABASE,
|
||||
STARTING_SERVICES,
|
||||
RUNNING,
|
||||
STOPPING,
|
||||
STOPPED;
|
||||
|
||||
public boolean isAfter(LifecycleState state) {
|
||||
return ordinal() > state.ordinal();
|
||||
|
||||
@@ -2,6 +2,7 @@ package org.briarproject.bramble.api.mailbox;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.UniqueId;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
@@ -32,7 +33,7 @@ public abstract class MailboxId extends UniqueId {
|
||||
}
|
||||
try {
|
||||
return fromHexString(token);
|
||||
} catch (IllegalArgumentException e) {
|
||||
} catch (FormatException e) {
|
||||
throw new InvalidMailboxIdException();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import javax.annotation.concurrent.Immutable;
|
||||
@NotNullByDefault
|
||||
public class MailboxProperties {
|
||||
|
||||
private final String baseUrl;
|
||||
private final String onion;
|
||||
private final MailboxAuthToken authToken;
|
||||
private final boolean owner;
|
||||
private final List<MailboxVersion> serverSupports;
|
||||
@@ -23,9 +23,9 @@ public class MailboxProperties {
|
||||
/**
|
||||
* Constructor for properties used by the mailbox's owner.
|
||||
*/
|
||||
public MailboxProperties(String baseUrl, MailboxAuthToken authToken,
|
||||
public MailboxProperties(String onion, MailboxAuthToken authToken,
|
||||
List<MailboxVersion> serverSupports) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.onion = onion;
|
||||
this.authToken = authToken;
|
||||
this.owner = true;
|
||||
this.serverSupports = serverSupports;
|
||||
@@ -36,10 +36,10 @@ public class MailboxProperties {
|
||||
/**
|
||||
* Constructor for properties used by a contact of the mailbox's owner.
|
||||
*/
|
||||
public MailboxProperties(String baseUrl, MailboxAuthToken authToken,
|
||||
public MailboxProperties(String onion, MailboxAuthToken authToken,
|
||||
List<MailboxVersion> serverSupports, MailboxFolderId inboxId,
|
||||
MailboxFolderId outboxId) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.onion = onion;
|
||||
this.authToken = authToken;
|
||||
this.owner = false;
|
||||
this.serverSupports = serverSupports;
|
||||
@@ -47,13 +47,11 @@ public class MailboxProperties {
|
||||
this.outboxId = outboxId;
|
||||
}
|
||||
|
||||
public String getBaseUrl() {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the onion address of the mailbox, excluding the .onion suffix.
|
||||
*/
|
||||
public String getOnion() {
|
||||
return baseUrl.replaceFirst("^http://", "")
|
||||
.replaceFirst("\\.onion$", "");
|
||||
return onion;
|
||||
}
|
||||
|
||||
public MailboxAuthToken getAuthToken() {
|
||||
|
||||
@@ -29,19 +29,35 @@ public interface MailboxUpdateManager {
|
||||
|
||||
/**
|
||||
* The number of properties required for an update message with a mailbox.
|
||||
* <p>
|
||||
* The required properties are {@link #PROP_KEY_ONION},
|
||||
* {@link #PROP_KEY_AUTHTOKEN}, {@link #PROP_KEY_INBOXID} and
|
||||
* {@link #PROP_KEY_OUTBOXID}.
|
||||
*/
|
||||
int PROP_COUNT = 4;
|
||||
|
||||
/**
|
||||
* The required properties of an update message with a mailbox.
|
||||
* The onion address of the mailbox, excluding the .onion suffix.
|
||||
*/
|
||||
String PROP_KEY_ONION = "onion";
|
||||
|
||||
/**
|
||||
* A bearer token for accessing the mailbox (64 hex digits).
|
||||
*/
|
||||
String PROP_KEY_AUTHTOKEN = "authToken";
|
||||
|
||||
/**
|
||||
* A folder ID for downloading messages (64 hex digits).
|
||||
*/
|
||||
String PROP_KEY_INBOXID = "inboxId";
|
||||
|
||||
/**
|
||||
* A folder ID for uploading messages (64 hex digits).
|
||||
*/
|
||||
String PROP_KEY_OUTBOXID = "outboxId";
|
||||
|
||||
/**
|
||||
* Length of the Onion property.
|
||||
* Length of the {@link #PROP_KEY_ONION} property.
|
||||
*/
|
||||
int PROP_ONION_LENGTH = 56;
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.briarproject.bramble.util;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
@@ -95,10 +96,10 @@ public class StringUtils {
|
||||
/**
|
||||
* Converts the given hex string to a byte array.
|
||||
*/
|
||||
public static byte[] fromHexString(String hex) {
|
||||
public static byte[] fromHexString(String hex) throws FormatException {
|
||||
int len = hex.length();
|
||||
if (len % 2 != 0)
|
||||
throw new IllegalArgumentException("Not a hex string");
|
||||
throw new FormatException();
|
||||
byte[] bytes = new byte[len / 2];
|
||||
for (int i = 0, j = 0; i < len; i += 2, j++) {
|
||||
int high = hexDigitToInt(hex.charAt(i));
|
||||
@@ -108,11 +109,11 @@ public class StringUtils {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static int hexDigitToInt(char c) {
|
||||
private static int hexDigitToInt(char c) throws FormatException {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
throw new IllegalArgumentException("Not a hex digit: " + c);
|
||||
throw new FormatException();
|
||||
}
|
||||
|
||||
public static String trim(String s) {
|
||||
@@ -130,13 +131,13 @@ public class StringUtils {
|
||||
return MAC.matcher(mac).matches();
|
||||
}
|
||||
|
||||
public static byte[] macToBytes(String mac) {
|
||||
if (!MAC.matcher(mac).matches()) throw new IllegalArgumentException();
|
||||
public static byte[] macToBytes(String mac) throws FormatException {
|
||||
if (!MAC.matcher(mac).matches()) throw new FormatException();
|
||||
return fromHexString(mac.replaceAll(":", ""));
|
||||
}
|
||||
|
||||
public static String macToString(byte[] mac) {
|
||||
if (mac.length != 6) throw new IllegalArgumentException();
|
||||
public static String macToString(byte[] mac) throws FormatException {
|
||||
if (mac.length != 6) throw new FormatException();
|
||||
StringBuilder s = new StringBuilder();
|
||||
for (byte b : mac) {
|
||||
if (s.length() > 0) s.append(':');
|
||||
|
||||
@@ -230,14 +230,14 @@ public class TestUtils {
|
||||
|
||||
public static MailboxProperties getMailboxProperties(boolean owner,
|
||||
List<MailboxVersion> serverSupports) {
|
||||
String baseUrl = "http://" + getRandomString(56) + ".onion"; // TODO
|
||||
String onion = getRandomString(56);
|
||||
MailboxAuthToken authToken = new MailboxAuthToken(getRandomId());
|
||||
if (owner) {
|
||||
return new MailboxProperties(baseUrl, authToken, serverSupports);
|
||||
return new MailboxProperties(onion, authToken, serverSupports);
|
||||
}
|
||||
MailboxFolderId inboxId = new MailboxFolderId(getRandomId());
|
||||
MailboxFolderId outboxId = new MailboxFolderId(getRandomId());
|
||||
return new MailboxProperties(baseUrl, authToken, serverSupports,
|
||||
return new MailboxProperties(onion, authToken, serverSupports,
|
||||
inboxId, outboxId);
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ dependencies {
|
||||
implementation 'org.bitlet:weupnp:0.1.4'
|
||||
implementation 'net.i2p.crypto:eddsa:0.2.0'
|
||||
implementation 'org.whispersystems:curve25519-java:0.5.0'
|
||||
implementation 'org.briarproject:jtorctl:0.4'
|
||||
implementation 'org.briarproject:jtorctl:0.5'
|
||||
|
||||
//noinspection GradleDependency
|
||||
implementation "com.squareup.okhttp3:okhttp:$okhttp_version"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.briarproject.bramble.account;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.account.AccountManager;
|
||||
import org.briarproject.bramble.api.crypto.CryptoComponent;
|
||||
import org.briarproject.bramble.api.crypto.DecryptionException;
|
||||
@@ -209,7 +210,13 @@ class AccountManagerImpl implements AccountManager {
|
||||
LOG.warning("Failed to load encrypted database key");
|
||||
throw new DecryptionException(INVALID_CIPHERTEXT);
|
||||
}
|
||||
byte[] ciphertext = fromHexString(hex);
|
||||
byte[] ciphertext;
|
||||
try {
|
||||
ciphertext = fromHexString(hex);
|
||||
} catch (FormatException e) {
|
||||
LOG.warning("Encrypted database key has invalid format");
|
||||
throw new DecryptionException(INVALID_CIPHERTEXT);
|
||||
}
|
||||
KeyStrengthener keyStrengthener = databaseConfig.getKeyStrengthener();
|
||||
byte[] plaintext = crypto.decryptWithPassword(ciphertext, password,
|
||||
keyStrengthener);
|
||||
|
||||
@@ -456,8 +456,7 @@ class ClientHelperImpl implements ClientHelper {
|
||||
checkLength(inboxId, UniqueId.LENGTH);
|
||||
byte[] outboxId = properties.getRaw(PROP_KEY_OUTBOXID);
|
||||
checkLength(outboxId, UniqueId.LENGTH);
|
||||
String baseUrl = "http://" + onion + ".onion"; // TODO
|
||||
MailboxProperties props = new MailboxProperties(baseUrl,
|
||||
MailboxProperties props = new MailboxProperties(onion,
|
||||
new MailboxAuthToken(authToken), serverSupportsList,
|
||||
new MailboxFolderId(inboxId), new MailboxFolderId(outboxId));
|
||||
return new MailboxUpdateWithMailbox(clientSupportsList, props);
|
||||
|
||||
@@ -18,7 +18,7 @@ import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
@@ -29,10 +29,12 @@ import static java.util.logging.Level.INFO;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.COMPACTING_DATABASE;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.CREATED;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.MIGRATING_DATABASE;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.RUNNING;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STARTING;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STARTING_SERVICES;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STOPPED;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STOPPING;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.StartResult.ALREADY_RUNNING;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.StartResult.CLOCK_ERROR;
|
||||
@@ -60,12 +62,11 @@ class LifecycleManagerImpl implements LifecycleManager, MigrationListener {
|
||||
private final List<Service> services;
|
||||
private final List<OpenDatabaseHook> openDatabaseHooks;
|
||||
private final List<ExecutorService> executors;
|
||||
private final Semaphore startStopSemaphore = new Semaphore(1);
|
||||
private final CountDownLatch dbLatch = new CountDownLatch(1);
|
||||
private final CountDownLatch startupLatch = new CountDownLatch(1);
|
||||
private final CountDownLatch shutdownLatch = new CountDownLatch(1);
|
||||
|
||||
private volatile LifecycleState state = STARTING;
|
||||
private final AtomicReference<LifecycleState> state =
|
||||
new AtomicReference<>(CREATED);
|
||||
|
||||
@Inject
|
||||
LifecycleManagerImpl(DatabaseComponent db, EventBus eventBus,
|
||||
@@ -102,8 +103,8 @@ class LifecycleManagerImpl implements LifecycleManager, MigrationListener {
|
||||
|
||||
@Override
|
||||
public StartResult startServices(SecretKey dbKey) {
|
||||
if (!startStopSemaphore.tryAcquire()) {
|
||||
LOG.info("Already starting or stopping");
|
||||
if (!state.compareAndSet(CREATED, STARTING)) {
|
||||
LOG.warning("Already running");
|
||||
return ALREADY_RUNNING;
|
||||
}
|
||||
long now = clock.currentTimeMillis();
|
||||
@@ -135,7 +136,7 @@ class LifecycleManagerImpl implements LifecycleManager, MigrationListener {
|
||||
});
|
||||
|
||||
LOG.info("Starting services");
|
||||
state = STARTING_SERVICES;
|
||||
state.set(STARTING_SERVICES);
|
||||
dbLatch.countDown();
|
||||
eventBus.broadcast(new LifecycleEvent(STARTING_SERVICES));
|
||||
|
||||
@@ -148,7 +149,7 @@ class LifecycleManagerImpl implements LifecycleManager, MigrationListener {
|
||||
}
|
||||
}
|
||||
|
||||
state = RUNNING;
|
||||
state.set(RUNNING);
|
||||
startupLatch.countDown();
|
||||
eventBus.broadcast(new LifecycleEvent(RUNNING));
|
||||
return SUCCESS;
|
||||
@@ -164,63 +165,58 @@ class LifecycleManagerImpl implements LifecycleManager, MigrationListener {
|
||||
} catch (ServiceException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
return SERVICE_ERROR;
|
||||
} finally {
|
||||
startStopSemaphore.release();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDatabaseMigration() {
|
||||
state = MIGRATING_DATABASE;
|
||||
state.set(MIGRATING_DATABASE);
|
||||
eventBus.broadcast(new LifecycleEvent(MIGRATING_DATABASE));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDatabaseCompaction() {
|
||||
state = COMPACTING_DATABASE;
|
||||
state.set(COMPACTING_DATABASE);
|
||||
eventBus.broadcast(new LifecycleEvent(COMPACTING_DATABASE));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopServices() {
|
||||
try {
|
||||
startStopSemaphore.acquire();
|
||||
} catch (InterruptedException e) {
|
||||
LOG.warning("Interrupted while waiting to stop services");
|
||||
if (!state.compareAndSet(RUNNING, STOPPING)) {
|
||||
LOG.warning("Not running");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (state == STOPPING) {
|
||||
LOG.info("Already stopped");
|
||||
return;
|
||||
}
|
||||
LOG.info("Stopping services");
|
||||
state = STOPPING;
|
||||
eventBus.broadcast(new LifecycleEvent(STOPPING));
|
||||
for (Service s : services) {
|
||||
LOG.info("Stopping services");
|
||||
eventBus.broadcast(new LifecycleEvent(STOPPING));
|
||||
for (Service s : services) {
|
||||
try {
|
||||
long start = now();
|
||||
s.stopService();
|
||||
if (LOG.isLoggable(FINE)) {
|
||||
logDuration(LOG, "Stopping service "
|
||||
+ s.getClass().getSimpleName(), start);
|
||||
}
|
||||
} catch (ServiceException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
}
|
||||
for (ExecutorService e : executors) {
|
||||
if (LOG.isLoggable(FINE)) {
|
||||
LOG.fine("Stopping executor "
|
||||
+ e.getClass().getSimpleName());
|
||||
}
|
||||
e.shutdownNow();
|
||||
}
|
||||
for (ExecutorService e : executors) {
|
||||
if (LOG.isLoggable(FINE)) {
|
||||
LOG.fine("Stopping executor "
|
||||
+ e.getClass().getSimpleName());
|
||||
}
|
||||
e.shutdownNow();
|
||||
}
|
||||
try {
|
||||
long start = now();
|
||||
db.close();
|
||||
logDuration(LOG, "Closing database", start);
|
||||
shutdownLatch.countDown();
|
||||
} catch (DbException | ServiceException e) {
|
||||
} catch (DbException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
} finally {
|
||||
startStopSemaphore.release();
|
||||
}
|
||||
state.set(STOPPED);
|
||||
shutdownLatch.countDown();
|
||||
eventBus.broadcast(new LifecycleEvent(STOPPED));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -240,6 +236,6 @@ class LifecycleManagerImpl implements LifecycleManager, MigrationListener {
|
||||
|
||||
@Override
|
||||
public LifecycleState getLifecycleState() {
|
||||
return state;
|
||||
return state.get();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import java.util.logging.Logger;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
import javax.inject.Inject;
|
||||
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
|
||||
@@ -30,7 +29,6 @@ class ContactMailboxClient implements MailboxClient {
|
||||
@Nullable
|
||||
private MailboxWorker uploadWorker = null, downloadWorker = null;
|
||||
|
||||
@Inject
|
||||
ContactMailboxClient(MailboxWorkerFactory workerFactory,
|
||||
ConnectivityChecker connectivityChecker,
|
||||
TorReachabilityMonitor reachabilityMonitor) {
|
||||
|
||||
@@ -1,73 +1,25 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.api.Cancellable;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFolderId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxProperties;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.mailbox.ConnectivityChecker.ConnectivityObserver;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.ApiException;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.MailboxFile;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.TolerableFailureException;
|
||||
import org.briarproject.bramble.mailbox.TorReachabilityMonitor.TorReachabilityObserver;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Queue;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
|
||||
import static java.util.logging.Level.INFO;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static java.util.Collections.emptyList;
|
||||
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
|
||||
@ThreadSafe
|
||||
@NotNullByDefault
|
||||
class ContactMailboxDownloadWorker implements MailboxWorker,
|
||||
ConnectivityObserver, TorReachabilityObserver {
|
||||
|
||||
/**
|
||||
* When the worker is started it waits for a connectivity check, then
|
||||
* starts its first download cycle: checking the inbox, downloading and
|
||||
* deleting any files, and checking again until the inbox is empty.
|
||||
* <p>
|
||||
* The worker then waits for our Tor hidden service to be reachable before
|
||||
* starting its second download cycle. This ensures that if a contact
|
||||
* tried and failed to connect to our hidden service before it was
|
||||
* reachable, and therefore uploaded a file to the mailbox instead, we'll
|
||||
* find the file in the second download cycle.
|
||||
*/
|
||||
private enum State {
|
||||
CREATED,
|
||||
CONNECTIVITY_CHECK,
|
||||
DOWNLOAD_CYCLE_1,
|
||||
WAITING_FOR_TOR,
|
||||
DOWNLOAD_CYCLE_2,
|
||||
FINISHED,
|
||||
DESTROYED
|
||||
}
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(ContactMailboxDownloadWorker.class.getName());
|
||||
|
||||
private final ConnectivityChecker connectivityChecker;
|
||||
private final TorReachabilityMonitor torReachabilityMonitor;
|
||||
private final MailboxApiCaller mailboxApiCaller;
|
||||
private final MailboxApi mailboxApi;
|
||||
private final MailboxFileManager mailboxFileManager;
|
||||
private final MailboxProperties mailboxProperties;
|
||||
private final Object lock = new Object();
|
||||
|
||||
@GuardedBy("lock")
|
||||
private State state = State.CREATED;
|
||||
|
||||
@GuardedBy("lock")
|
||||
@Nullable
|
||||
private Cancellable apiCall = null;
|
||||
class ContactMailboxDownloadWorker extends MailboxDownloadWorker {
|
||||
|
||||
ContactMailboxDownloadWorker(
|
||||
ConnectivityChecker connectivityChecker,
|
||||
@@ -76,57 +28,14 @@ class ContactMailboxDownloadWorker implements MailboxWorker,
|
||||
MailboxApi mailboxApi,
|
||||
MailboxFileManager mailboxFileManager,
|
||||
MailboxProperties mailboxProperties) {
|
||||
super(connectivityChecker, torReachabilityMonitor, mailboxApiCaller,
|
||||
mailboxApi, mailboxFileManager, mailboxProperties);
|
||||
if (mailboxProperties.isOwner()) throw new IllegalArgumentException();
|
||||
this.connectivityChecker = connectivityChecker;
|
||||
this.torReachabilityMonitor = torReachabilityMonitor;
|
||||
this.mailboxApiCaller = mailboxApiCaller;
|
||||
this.mailboxApi = mailboxApi;
|
||||
this.mailboxFileManager = mailboxFileManager;
|
||||
this.mailboxProperties = mailboxProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
LOG.info("Started");
|
||||
synchronized (lock) {
|
||||
// Don't allow the worker to be reused
|
||||
if (state != State.CREATED) return;
|
||||
state = State.CONNECTIVITY_CHECK;
|
||||
}
|
||||
// Avoid leaking observer in case destroy() is called concurrently
|
||||
// before observer is added
|
||||
connectivityChecker.checkConnectivity(mailboxProperties, this);
|
||||
boolean destroyed;
|
||||
synchronized (lock) {
|
||||
destroyed = state == State.DESTROYED;
|
||||
}
|
||||
if (destroyed) connectivityChecker.removeObserver(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
LOG.info("Destroyed");
|
||||
Cancellable apiCall;
|
||||
synchronized (lock) {
|
||||
state = State.DESTROYED;
|
||||
apiCall = this.apiCall;
|
||||
this.apiCall = null;
|
||||
}
|
||||
if (apiCall != null) apiCall.cancel();
|
||||
connectivityChecker.removeObserver(this);
|
||||
torReachabilityMonitor.removeObserver(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConnectivityCheckSucceeded() {
|
||||
LOG.info("Connectivity check succeeded");
|
||||
synchronized (lock) {
|
||||
if (state != State.CONNECTIVITY_CHECK) return;
|
||||
state = State.DOWNLOAD_CYCLE_1;
|
||||
// Start first download cycle
|
||||
apiCall = mailboxApiCaller.retryWithBackoff(
|
||||
new SimpleApiCall(this::apiCallListInbox));
|
||||
}
|
||||
protected ApiCall createApiCallForDownloadCycle() {
|
||||
return new SimpleApiCall(this::apiCallListInbox);
|
||||
}
|
||||
|
||||
private void apiCallListInbox() throws IOException, ApiException {
|
||||
@@ -134,110 +43,23 @@ class ContactMailboxDownloadWorker implements MailboxWorker,
|
||||
if (state == State.DESTROYED) return;
|
||||
}
|
||||
LOG.info("Listing inbox");
|
||||
List<MailboxFile> files = mailboxApi.getFiles(mailboxProperties,
|
||||
requireNonNull(mailboxProperties.getInboxId()));
|
||||
if (files.isEmpty()) onDownloadCycleFinished();
|
||||
else downloadNextFile(new LinkedList<>(files));
|
||||
}
|
||||
|
||||
private void onDownloadCycleFinished() {
|
||||
boolean addObserver = false;
|
||||
synchronized (lock) {
|
||||
if (state == State.DOWNLOAD_CYCLE_1) {
|
||||
LOG.info("First download cycle finished");
|
||||
state = State.WAITING_FOR_TOR;
|
||||
apiCall = null;
|
||||
addObserver = true;
|
||||
} else if (state == State.DOWNLOAD_CYCLE_2) {
|
||||
LOG.info("Second download cycle finished");
|
||||
state = State.FINISHED;
|
||||
apiCall = null;
|
||||
}
|
||||
}
|
||||
if (addObserver) {
|
||||
// Avoid leaking observer in case destroy() is called concurrently
|
||||
// before observer is added
|
||||
torReachabilityMonitor.addOneShotObserver(this);
|
||||
boolean destroyed;
|
||||
synchronized (lock) {
|
||||
destroyed = state == State.DESTROYED;
|
||||
}
|
||||
if (destroyed) torReachabilityMonitor.removeObserver(this);
|
||||
}
|
||||
}
|
||||
|
||||
private void downloadNextFile(Queue<MailboxFile> queue) {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
MailboxFile file = queue.remove();
|
||||
apiCall = mailboxApiCaller.retryWithBackoff(
|
||||
new SimpleApiCall(() -> apiCallDownloadFile(file, queue)));
|
||||
}
|
||||
}
|
||||
|
||||
private void apiCallDownloadFile(MailboxFile file,
|
||||
Queue<MailboxFile> queue) throws IOException, ApiException {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
}
|
||||
LOG.info("Downloading file");
|
||||
File tempFile = mailboxFileManager.createTempFileForDownload();
|
||||
MailboxFolderId folderId =
|
||||
requireNonNull(mailboxProperties.getInboxId());
|
||||
List<MailboxFile> files;
|
||||
try {
|
||||
mailboxApi.getFile(mailboxProperties,
|
||||
requireNonNull(mailboxProperties.getInboxId()),
|
||||
file.name, tempFile);
|
||||
} catch (IOException | ApiException e) {
|
||||
if (!tempFile.delete()) {
|
||||
LOG.warning("Failed to delete temporary file");
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
mailboxFileManager.handleDownloadedFile(tempFile);
|
||||
deleteFile(file, queue);
|
||||
}
|
||||
|
||||
private void deleteFile(MailboxFile file, Queue<MailboxFile> queue) {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
apiCall = mailboxApiCaller.retryWithBackoff(
|
||||
new SimpleApiCall(() -> apiCallDeleteFile(file, queue)));
|
||||
}
|
||||
}
|
||||
|
||||
private void apiCallDeleteFile(MailboxFile file, Queue<MailboxFile> queue)
|
||||
throws IOException, ApiException {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
}
|
||||
try {
|
||||
mailboxApi.deleteFile(mailboxProperties,
|
||||
requireNonNull(mailboxProperties.getInboxId()), file.name);
|
||||
files = mailboxApi.getFiles(mailboxProperties, folderId);
|
||||
} catch (TolerableFailureException e) {
|
||||
// Catch this so we can continue to the next file
|
||||
logException(LOG, INFO, e);
|
||||
LOG.warning("Inbox folder does not exist");
|
||||
files = emptyList();
|
||||
}
|
||||
if (queue.isEmpty()) {
|
||||
// List the inbox again to check for files that may have arrived
|
||||
// while we were downloading
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
apiCall = mailboxApiCaller.retryWithBackoff(
|
||||
new SimpleApiCall(this::apiCallListInbox));
|
||||
}
|
||||
if (files.isEmpty()) {
|
||||
onDownloadCycleFinished();
|
||||
} else {
|
||||
Queue<FolderFile> queue = new LinkedList<>();
|
||||
for (MailboxFile file : files) {
|
||||
queue.add(new FolderFile(folderId, file.name));
|
||||
}
|
||||
downloadNextFile(queue);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTorReachable() {
|
||||
LOG.info("Our Tor hidden service is reachable");
|
||||
synchronized (lock) {
|
||||
if (state != State.WAITING_FOR_TOR) return;
|
||||
state = State.DOWNLOAD_CYCLE_2;
|
||||
// Start second download cycle
|
||||
apiCall = mailboxApiCaller.retryWithBackoff(
|
||||
new SimpleApiCall(this::apiCallListInbox));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,9 +91,13 @@ interface MailboxApi {
|
||||
* Used by owner and contacts to list their files to retrieve.
|
||||
* <p>
|
||||
* Returns 200 OK with the list of files in JSON.
|
||||
*
|
||||
* @throws TolerableFailureException if response code is 404 (folder does
|
||||
* not exist or client is not authorised to download from it)
|
||||
*/
|
||||
List<MailboxFile> getFiles(MailboxProperties properties,
|
||||
MailboxFolderId folderId) throws IOException, ApiException;
|
||||
MailboxFolderId folderId)
|
||||
throws IOException, ApiException, TolerableFailureException;
|
||||
|
||||
/**
|
||||
* Used by owner and contacts to retrieve a file.
|
||||
@@ -102,17 +106,22 @@ interface MailboxApi {
|
||||
* in the response body.
|
||||
*
|
||||
* @param file the empty file the response bytes will be written into.
|
||||
* @throws TolerableFailureException if response code is 404 (folder does
|
||||
* not exist, client is not authorised to download from folder, or file
|
||||
* does not exist)
|
||||
*/
|
||||
void getFile(MailboxProperties properties, MailboxFolderId folderId,
|
||||
MailboxFileId fileId, File file) throws IOException, ApiException;
|
||||
MailboxFileId fileId, File file)
|
||||
throws IOException, ApiException, TolerableFailureException;
|
||||
|
||||
/**
|
||||
* Used by owner and contacts to delete files.
|
||||
* <p>
|
||||
* Returns 200 OK (no exception) if deletion was successful.
|
||||
*
|
||||
* @throws TolerableFailureException on 404 response,
|
||||
* because file was most likely deleted already.
|
||||
* @throws TolerableFailureException if response code is 404 (folder does
|
||||
* not exist, client is not authorised to download from folder, or file
|
||||
* does not exist)
|
||||
*/
|
||||
void deleteFile(MailboxProperties properties, MailboxFolderId folderId,
|
||||
MailboxFileId fileId)
|
||||
|
||||
@@ -42,18 +42,22 @@ import static org.briarproject.bramble.util.IoUtils.copyAndClose;
|
||||
@NotNullByDefault
|
||||
class MailboxApiImpl implements MailboxApi {
|
||||
|
||||
private final WeakSingletonProvider<OkHttpClient> httpClientProvider;
|
||||
private final JsonMapper mapper = JsonMapper.builder()
|
||||
.enable(BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES)
|
||||
.build();
|
||||
private static final MediaType JSON =
|
||||
requireNonNull(MediaType.parse("application/json; charset=utf-8"));
|
||||
private static final MediaType FILE =
|
||||
requireNonNull(MediaType.parse("application/octet-stream"));
|
||||
|
||||
private final WeakSingletonProvider<OkHttpClient> httpClientProvider;
|
||||
private final JsonMapper mapper = JsonMapper.builder()
|
||||
.enable(BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES)
|
||||
.build();
|
||||
private final UrlConverter urlConverter;
|
||||
|
||||
@Inject
|
||||
MailboxApiImpl(WeakSingletonProvider<OkHttpClient> httpClientProvider) {
|
||||
MailboxApiImpl(WeakSingletonProvider<OkHttpClient> httpClientProvider,
|
||||
UrlConverter urlConverter) {
|
||||
this.httpClientProvider = httpClientProvider;
|
||||
this.urlConverter = urlConverter;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -78,7 +82,7 @@ class MailboxApiImpl implements MailboxApi {
|
||||
throws IOException, ApiException {
|
||||
if (!properties.isOwner()) throw new IllegalArgumentException();
|
||||
Request request = getRequestBuilder(properties.getAuthToken())
|
||||
.url(properties.getBaseUrl() + "/setup")
|
||||
.url(getBaseUrl(properties) + "/setup")
|
||||
.put(EMPTY_REQUEST)
|
||||
.build();
|
||||
OkHttpClient client = httpClientProvider.get();
|
||||
@@ -93,7 +97,7 @@ class MailboxApiImpl implements MailboxApi {
|
||||
if (tokenNode == null) {
|
||||
throw new ApiException();
|
||||
}
|
||||
return new MailboxProperties(properties.getBaseUrl(),
|
||||
return new MailboxProperties(properties.getOnion(),
|
||||
MailboxAuthToken.fromString(tokenNode.textValue()),
|
||||
parseServerSupports(node));
|
||||
} catch (JacksonException | InvalidMailboxIdException e) {
|
||||
@@ -137,7 +141,7 @@ class MailboxApiImpl implements MailboxApi {
|
||||
throws IOException, ApiException {
|
||||
if (!properties.isOwner()) throw new IllegalArgumentException();
|
||||
Request request = getRequestBuilder(properties.getAuthToken())
|
||||
.url(properties.getBaseUrl() + "/")
|
||||
.url(getBaseUrl(properties) + "/")
|
||||
.delete()
|
||||
.build();
|
||||
OkHttpClient client = httpClientProvider.get();
|
||||
@@ -162,7 +166,7 @@ class MailboxApiImpl implements MailboxApi {
|
||||
public void deleteContact(MailboxProperties properties, ContactId contactId)
|
||||
throws IOException, ApiException, TolerableFailureException {
|
||||
if (!properties.isOwner()) throw new IllegalArgumentException();
|
||||
String url = properties.getBaseUrl() + "/contacts/" +
|
||||
String url = getBaseUrl(properties) + "/contacts/" +
|
||||
contactId.getInt();
|
||||
Request request = getRequestBuilder(properties.getAuthToken())
|
||||
.delete()
|
||||
@@ -212,9 +216,11 @@ class MailboxApiImpl implements MailboxApi {
|
||||
|
||||
@Override
|
||||
public List<MailboxFile> getFiles(MailboxProperties properties,
|
||||
MailboxFolderId folderId) throws IOException, ApiException {
|
||||
MailboxFolderId folderId)
|
||||
throws IOException, ApiException, TolerableFailureException {
|
||||
String path = "/files/" + folderId;
|
||||
Response response = sendGetRequest(properties, path);
|
||||
if (response.code() == 404) throw new TolerableFailureException();
|
||||
if (response.code() != 200) throw new ApiException();
|
||||
|
||||
ResponseBody body = response.body();
|
||||
@@ -248,9 +254,11 @@ class MailboxApiImpl implements MailboxApi {
|
||||
|
||||
@Override
|
||||
public void getFile(MailboxProperties properties, MailboxFolderId folderId,
|
||||
MailboxFileId fileId, File file) throws IOException, ApiException {
|
||||
MailboxFileId fileId, File file)
|
||||
throws IOException, ApiException, TolerableFailureException {
|
||||
String path = "/files/" + folderId + "/" + fileId;
|
||||
Response response = sendGetRequest(properties, path);
|
||||
if (response.code() == 404) throw new TolerableFailureException();
|
||||
if (response.code() != 200) throw new ApiException();
|
||||
|
||||
ResponseBody body = response.body();
|
||||
@@ -266,7 +274,7 @@ class MailboxApiImpl implements MailboxApi {
|
||||
String path = "/files/" + folderId + "/" + fileId;
|
||||
Request request = getRequestBuilder(properties.getAuthToken())
|
||||
.delete()
|
||||
.url(properties.getBaseUrl() + path)
|
||||
.url(getBaseUrl(properties) + path)
|
||||
.build();
|
||||
OkHttpClient client = httpClientProvider.get();
|
||||
Response response = client.newCall(request).execute();
|
||||
@@ -308,7 +316,7 @@ class MailboxApiImpl implements MailboxApi {
|
||||
private Response sendGetRequest(MailboxProperties properties, String path)
|
||||
throws IOException {
|
||||
Request request = getRequestBuilder(properties.getAuthToken())
|
||||
.url(properties.getBaseUrl() + path)
|
||||
.url(getBaseUrl(properties) + path)
|
||||
.build();
|
||||
OkHttpClient client = httpClientProvider.get();
|
||||
return client.newCall(request).execute();
|
||||
@@ -317,7 +325,7 @@ class MailboxApiImpl implements MailboxApi {
|
||||
private Response sendPostRequest(MailboxProperties properties, String path,
|
||||
RequestBody body) throws IOException {
|
||||
Request request = getRequestBuilder(properties.getAuthToken())
|
||||
.url(properties.getBaseUrl() + path)
|
||||
.url(getBaseUrl(properties) + path)
|
||||
.post(body)
|
||||
.build();
|
||||
OkHttpClient client = httpClientProvider.get();
|
||||
@@ -339,4 +347,7 @@ class MailboxApiImpl implements MailboxApi {
|
||||
return (ArrayNode) arrayNode;
|
||||
}
|
||||
|
||||
private String getBaseUrl(MailboxProperties properties) {
|
||||
return urlConverter.convertOnionToBaseUrl(properties.getOnion());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,10 @@ interface MailboxClient {
|
||||
|
||||
/**
|
||||
* Assigns a contact to the client for upload.
|
||||
*
|
||||
* @param properties Properties for communicating with the mailbox
|
||||
* managed by this client.
|
||||
* @param folderId The ID of the folder to which files will be uploaded.
|
||||
*/
|
||||
void assignContactForUpload(ContactId c, MailboxProperties properties,
|
||||
MailboxFolderId folderId);
|
||||
@@ -35,6 +39,11 @@ interface MailboxClient {
|
||||
|
||||
/**
|
||||
* Assigns a contact to the client for download.
|
||||
*
|
||||
* @param properties Properties for communicating with the mailbox
|
||||
* managed by this client.
|
||||
* @param folderId The ID of the folder from which files will be
|
||||
* downloaded.
|
||||
*/
|
||||
void assignContactForDownload(ContactId c, MailboxProperties properties,
|
||||
MailboxFolderId folderId);
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.api.Cancellable;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFileId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFolderId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxProperties;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.mailbox.ConnectivityChecker.ConnectivityObserver;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.ApiException;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.TolerableFailureException;
|
||||
import org.briarproject.bramble.mailbox.TorReachabilityMonitor.TorReachabilityObserver;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Queue;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
|
||||
@ThreadSafe
|
||||
@NotNullByDefault
|
||||
abstract class MailboxDownloadWorker implements MailboxWorker,
|
||||
ConnectivityObserver, TorReachabilityObserver {
|
||||
|
||||
/**
|
||||
* When the worker is started it waits for a connectivity check, then
|
||||
* starts its first download cycle: checking for files to download,
|
||||
* downloading and deleting the files, and checking again until all files
|
||||
* have been downloaded and deleted.
|
||||
* <p>
|
||||
* The worker then waits for our Tor hidden service to be reachable before
|
||||
* starting its second download cycle. This ensures that if a contact
|
||||
* tried and failed to connect to our hidden service before it was
|
||||
* reachable, and therefore uploaded a file to the mailbox instead, we'll
|
||||
* find the file in the second download cycle.
|
||||
*/
|
||||
protected enum State {
|
||||
CREATED,
|
||||
CONNECTIVITY_CHECK,
|
||||
DOWNLOAD_CYCLE_1,
|
||||
WAITING_FOR_TOR,
|
||||
DOWNLOAD_CYCLE_2,
|
||||
FINISHED,
|
||||
DESTROYED
|
||||
}
|
||||
|
||||
protected static final Logger LOG =
|
||||
getLogger(MailboxDownloadWorker.class.getName());
|
||||
|
||||
private final ConnectivityChecker connectivityChecker;
|
||||
private final TorReachabilityMonitor torReachabilityMonitor;
|
||||
protected final MailboxApiCaller mailboxApiCaller;
|
||||
protected final MailboxApi mailboxApi;
|
||||
private final MailboxFileManager mailboxFileManager;
|
||||
protected final MailboxProperties mailboxProperties;
|
||||
protected final Object lock = new Object();
|
||||
|
||||
@GuardedBy("lock")
|
||||
protected State state = State.CREATED;
|
||||
|
||||
@GuardedBy("lock")
|
||||
@Nullable
|
||||
protected Cancellable apiCall = null;
|
||||
|
||||
/**
|
||||
* Creates the API call that starts the worker's download cycle.
|
||||
*/
|
||||
protected abstract ApiCall createApiCallForDownloadCycle();
|
||||
|
||||
MailboxDownloadWorker(
|
||||
ConnectivityChecker connectivityChecker,
|
||||
TorReachabilityMonitor torReachabilityMonitor,
|
||||
MailboxApiCaller mailboxApiCaller,
|
||||
MailboxApi mailboxApi,
|
||||
MailboxFileManager mailboxFileManager,
|
||||
MailboxProperties mailboxProperties) {
|
||||
this.connectivityChecker = connectivityChecker;
|
||||
this.torReachabilityMonitor = torReachabilityMonitor;
|
||||
this.mailboxApiCaller = mailboxApiCaller;
|
||||
this.mailboxApi = mailboxApi;
|
||||
this.mailboxFileManager = mailboxFileManager;
|
||||
this.mailboxProperties = mailboxProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
LOG.info("Started");
|
||||
synchronized (lock) {
|
||||
// Don't allow the worker to be reused
|
||||
if (state != State.CREATED) return;
|
||||
state = State.CONNECTIVITY_CHECK;
|
||||
}
|
||||
// Avoid leaking observer in case destroy() is called concurrently
|
||||
// before observer is added
|
||||
connectivityChecker.checkConnectivity(mailboxProperties, this);
|
||||
boolean destroyed;
|
||||
synchronized (lock) {
|
||||
destroyed = state == State.DESTROYED;
|
||||
}
|
||||
if (destroyed) connectivityChecker.removeObserver(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
LOG.info("Destroyed");
|
||||
Cancellable apiCall;
|
||||
synchronized (lock) {
|
||||
state = State.DESTROYED;
|
||||
apiCall = this.apiCall;
|
||||
this.apiCall = null;
|
||||
}
|
||||
if (apiCall != null) apiCall.cancel();
|
||||
connectivityChecker.removeObserver(this);
|
||||
torReachabilityMonitor.removeObserver(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onConnectivityCheckSucceeded() {
|
||||
LOG.info("Connectivity check succeeded");
|
||||
synchronized (lock) {
|
||||
if (state != State.CONNECTIVITY_CHECK) return;
|
||||
state = State.DOWNLOAD_CYCLE_1;
|
||||
// Start first download cycle
|
||||
apiCall = mailboxApiCaller.retryWithBackoff(
|
||||
createApiCallForDownloadCycle());
|
||||
}
|
||||
}
|
||||
|
||||
void onDownloadCycleFinished() {
|
||||
boolean addObserver = false;
|
||||
synchronized (lock) {
|
||||
if (state == State.DOWNLOAD_CYCLE_1) {
|
||||
LOG.info("First download cycle finished");
|
||||
state = State.WAITING_FOR_TOR;
|
||||
apiCall = null;
|
||||
addObserver = true;
|
||||
} else if (state == State.DOWNLOAD_CYCLE_2) {
|
||||
LOG.info("Second download cycle finished");
|
||||
state = State.FINISHED;
|
||||
apiCall = null;
|
||||
}
|
||||
}
|
||||
if (addObserver) {
|
||||
// Avoid leaking observer in case destroy() is called concurrently
|
||||
// before observer is added
|
||||
torReachabilityMonitor.addOneShotObserver(this);
|
||||
boolean destroyed;
|
||||
synchronized (lock) {
|
||||
destroyed = state == State.DESTROYED;
|
||||
}
|
||||
if (destroyed) torReachabilityMonitor.removeObserver(this);
|
||||
}
|
||||
}
|
||||
|
||||
void downloadNextFile(Queue<FolderFile> queue) {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
if (queue.isEmpty()) {
|
||||
// Check for files again, as new files may have arrived while
|
||||
// we were downloading
|
||||
apiCall = mailboxApiCaller.retryWithBackoff(
|
||||
createApiCallForDownloadCycle());
|
||||
} else {
|
||||
FolderFile file = queue.remove();
|
||||
apiCall = mailboxApiCaller.retryWithBackoff(
|
||||
new SimpleApiCall(() ->
|
||||
apiCallDownloadFile(file, queue)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void apiCallDownloadFile(FolderFile file, Queue<FolderFile> queue)
|
||||
throws IOException, ApiException {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
}
|
||||
LOG.info("Downloading file");
|
||||
File tempFile = mailboxFileManager.createTempFileForDownload();
|
||||
try {
|
||||
mailboxApi.getFile(mailboxProperties, file.folderId, file.fileId,
|
||||
tempFile);
|
||||
} catch (IOException | ApiException e) {
|
||||
if (!tempFile.delete()) {
|
||||
LOG.warning("Failed to delete temporary file");
|
||||
}
|
||||
throw e;
|
||||
} catch (TolerableFailureException e) {
|
||||
// File not found - continue to the next file
|
||||
LOG.warning("File does not exist");
|
||||
if (!tempFile.delete()) {
|
||||
LOG.warning("Failed to delete temporary file");
|
||||
}
|
||||
downloadNextFile(queue);
|
||||
return;
|
||||
}
|
||||
mailboxFileManager.handleDownloadedFile(tempFile);
|
||||
deleteFile(file, queue);
|
||||
}
|
||||
|
||||
private void deleteFile(FolderFile file, Queue<FolderFile> queue) {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
apiCall = mailboxApiCaller.retryWithBackoff(
|
||||
new SimpleApiCall(() -> apiCallDeleteFile(file, queue)));
|
||||
}
|
||||
}
|
||||
|
||||
private void apiCallDeleteFile(FolderFile file, Queue<FolderFile> queue)
|
||||
throws IOException, ApiException {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
}
|
||||
try {
|
||||
mailboxApi.deleteFile(mailboxProperties, file.folderId,
|
||||
file.fileId);
|
||||
} catch (TolerableFailureException e) {
|
||||
// File not found - continue to the next file
|
||||
LOG.warning("File does not exist");
|
||||
}
|
||||
downloadNextFile(queue);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTorReachable() {
|
||||
LOG.info("Our Tor hidden service is reachable");
|
||||
synchronized (lock) {
|
||||
if (state != State.WAITING_FOR_TOR) return;
|
||||
state = State.DOWNLOAD_CYCLE_2;
|
||||
// Start second download cycle
|
||||
apiCall = mailboxApiCaller.retryWithBackoff(
|
||||
createApiCallForDownloadCycle());
|
||||
}
|
||||
}
|
||||
|
||||
// Package access for testing
|
||||
static class FolderFile {
|
||||
|
||||
final MailboxFolderId folderId;
|
||||
final MailboxFileId fileId;
|
||||
|
||||
FolderFile(MailboxFolderId folderId, MailboxFileId fileId) {
|
||||
this.folderId = folderId;
|
||||
this.fileId = fileId;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,12 @@ public class MailboxModule {
|
||||
}
|
||||
|
||||
@Provides
|
||||
MailboxApi providesMailboxApi(MailboxApiImpl mailboxApi) {
|
||||
UrlConverter provideUrlConverter(UrlConverterImpl urlConverter) {
|
||||
return urlConverter;
|
||||
}
|
||||
|
||||
@Provides
|
||||
MailboxApi provideMailboxApi(MailboxApiImpl mailboxApi) {
|
||||
return mailboxApi;
|
||||
}
|
||||
|
||||
|
||||
@@ -177,10 +177,9 @@ class MailboxPairingTaskImpl implements MailboxPairingTask {
|
||||
LOG.info("QR code is valid");
|
||||
byte[] onionPubKey = Arrays.copyOfRange(bytes, 1, 33);
|
||||
String onion = crypto.encodeOnion(onionPubKey);
|
||||
String baseUrl = "http://" + onion + ".onion"; // TODO
|
||||
byte[] tokenBytes = Arrays.copyOfRange(bytes, 33, 65);
|
||||
MailboxAuthToken setupToken = new MailboxAuthToken(tokenBytes);
|
||||
return new MailboxProperties(baseUrl, setupToken, new ArrayList<>());
|
||||
return new MailboxProperties(onion, setupToken, new ArrayList<>());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ class MailboxSettingsManagerImpl implements MailboxSettingsManager {
|
||||
public void setOwnMailboxProperties(Transaction txn, MailboxProperties p)
|
||||
throws DbException {
|
||||
Settings s = new Settings();
|
||||
s.put(SETTINGS_KEY_ONION, p.getBaseUrl());
|
||||
s.put(SETTINGS_KEY_ONION, p.getOnion());
|
||||
s.put(SETTINGS_KEY_TOKEN, p.getAuthToken().toString());
|
||||
List<MailboxVersion> serverSupports = p.getServerSupports();
|
||||
encodeServerSupports(serverSupports, s);
|
||||
|
||||
@@ -242,8 +242,7 @@ class MailboxUpdateManagerImpl implements MailboxUpdateManager,
|
||||
private void createAndSendUpdateWithMailbox(Transaction txn, Contact c,
|
||||
List<MailboxVersion> serverSupports, String ownOnion)
|
||||
throws DbException {
|
||||
String baseUrl = "http://" + ownOnion + ".onion"; // TODO
|
||||
MailboxProperties properties = new MailboxProperties(baseUrl,
|
||||
MailboxProperties properties = new MailboxProperties(ownOnion,
|
||||
new MailboxAuthToken(crypto.generateUniqueId().getBytes()),
|
||||
serverSupports,
|
||||
new MailboxFolderId(crypto.generateUniqueId().getBytes()),
|
||||
|
||||
@@ -24,4 +24,8 @@ interface MailboxWorkerFactory {
|
||||
ConnectivityChecker connectivityChecker,
|
||||
TorReachabilityMonitor reachabilityMonitor,
|
||||
MailboxProperties properties);
|
||||
|
||||
MailboxWorker createContactListWorkerForOwnMailbox(
|
||||
ConnectivityChecker connectivityChecker,
|
||||
MailboxProperties properties);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.lifecycle.IoExecutor;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFolderId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxProperties;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxUpdateManager;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.api.system.TaskScheduler;
|
||||
@@ -27,6 +28,7 @@ class MailboxWorkerFactoryImpl implements MailboxWorkerFactory {
|
||||
private final MailboxApiCaller mailboxApiCaller;
|
||||
private final MailboxApi mailboxApi;
|
||||
private final MailboxFileManager mailboxFileManager;
|
||||
private final MailboxUpdateManager mailboxUpdateManager;
|
||||
|
||||
@Inject
|
||||
MailboxWorkerFactoryImpl(@IoExecutor Executor ioExecutor,
|
||||
@@ -36,7 +38,8 @@ class MailboxWorkerFactoryImpl implements MailboxWorkerFactory {
|
||||
EventBus eventBus,
|
||||
MailboxApiCaller mailboxApiCaller,
|
||||
MailboxApi mailboxApi,
|
||||
MailboxFileManager mailboxFileManager) {
|
||||
MailboxFileManager mailboxFileManager,
|
||||
MailboxUpdateManager mailboxUpdateManager) {
|
||||
this.ioExecutor = ioExecutor;
|
||||
this.db = db;
|
||||
this.clock = clock;
|
||||
@@ -45,6 +48,7 @@ class MailboxWorkerFactoryImpl implements MailboxWorkerFactory {
|
||||
this.mailboxApiCaller = mailboxApiCaller;
|
||||
this.mailboxApi = mailboxApi;
|
||||
this.mailboxFileManager = mailboxFileManager;
|
||||
this.mailboxUpdateManager = mailboxUpdateManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -75,7 +79,17 @@ class MailboxWorkerFactoryImpl implements MailboxWorkerFactory {
|
||||
ConnectivityChecker connectivityChecker,
|
||||
TorReachabilityMonitor reachabilityMonitor,
|
||||
MailboxProperties properties) {
|
||||
// TODO
|
||||
throw new UnsupportedOperationException();
|
||||
return new OwnMailboxDownloadWorker(connectivityChecker,
|
||||
reachabilityMonitor, mailboxApiCaller, mailboxApi,
|
||||
mailboxFileManager, properties);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MailboxWorker createContactListWorkerForOwnMailbox(
|
||||
ConnectivityChecker connectivityChecker,
|
||||
MailboxProperties properties) {
|
||||
return new OwnMailboxContactListWorker(ioExecutor, db, eventBus,
|
||||
connectivityChecker, mailboxApiCaller, mailboxApi,
|
||||
mailboxUpdateManager, properties);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFolderId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxProperties;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import javax.annotation.concurrent.GuardedBy;
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
|
||||
@ThreadSafe
|
||||
@NotNullByDefault
|
||||
class OwnMailboxClient implements MailboxClient {
|
||||
|
||||
private static final Logger LOG =
|
||||
getLogger(OwnMailboxClient.class.getName());
|
||||
|
||||
private final MailboxWorkerFactory workerFactory;
|
||||
private final ConnectivityChecker connectivityChecker;
|
||||
private final TorReachabilityMonitor reachabilityMonitor;
|
||||
private final MailboxWorker contactListWorker;
|
||||
private final Object lock = new Object();
|
||||
|
||||
/**
|
||||
* Upload workers: one worker per contact assigned for upload.
|
||||
*/
|
||||
@GuardedBy("lock")
|
||||
private final Map<ContactId, MailboxWorker> uploadWorkers = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Download worker: shared between all contacts assigned for download.
|
||||
* Null if no contacts are assigned for download.
|
||||
*/
|
||||
@GuardedBy("lock")
|
||||
@Nullable
|
||||
private MailboxWorker downloadWorker = null;
|
||||
|
||||
/**
|
||||
* IDs of contacts assigned for download, so that we know when to
|
||||
* create/destroy the download worker.
|
||||
*/
|
||||
@GuardedBy("lock")
|
||||
private final Set<ContactId> assignedForDownload = new HashSet<>();
|
||||
|
||||
OwnMailboxClient(MailboxWorkerFactory workerFactory,
|
||||
ConnectivityChecker connectivityChecker,
|
||||
TorReachabilityMonitor reachabilityMonitor,
|
||||
MailboxProperties properties) {
|
||||
if (!properties.isOwner()) throw new IllegalArgumentException();
|
||||
this.workerFactory = workerFactory;
|
||||
this.connectivityChecker = connectivityChecker;
|
||||
this.reachabilityMonitor = reachabilityMonitor;
|
||||
contactListWorker = workerFactory.createContactListWorkerForOwnMailbox(
|
||||
connectivityChecker, properties);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
LOG.info("Started");
|
||||
contactListWorker.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
LOG.info("Destroyed");
|
||||
List<MailboxWorker> uploadWorkers;
|
||||
MailboxWorker downloadWorker;
|
||||
synchronized (lock) {
|
||||
uploadWorkers = new ArrayList<>(this.uploadWorkers.values());
|
||||
this.uploadWorkers.clear();
|
||||
downloadWorker = this.downloadWorker;
|
||||
this.downloadWorker = null;
|
||||
}
|
||||
// Destroy the workers (with apologies to Mr Marx and Mr Engels)
|
||||
for (MailboxWorker worker : uploadWorkers) worker.destroy();
|
||||
if (downloadWorker != null) downloadWorker.destroy();
|
||||
contactListWorker.destroy();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void assignContactForUpload(ContactId contactId,
|
||||
MailboxProperties properties, MailboxFolderId folderId) {
|
||||
LOG.info("Contact assigned for upload");
|
||||
if (!properties.isOwner()) throw new IllegalArgumentException();
|
||||
MailboxWorker uploadWorker = workerFactory.createUploadWorker(
|
||||
connectivityChecker, properties, folderId, contactId);
|
||||
synchronized (lock) {
|
||||
MailboxWorker old = uploadWorkers.put(contactId, uploadWorker);
|
||||
if (old != null) throw new IllegalStateException();
|
||||
}
|
||||
uploadWorker.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deassignContactForUpload(ContactId contactId) {
|
||||
LOG.info("Contact deassigned for upload");
|
||||
MailboxWorker uploadWorker;
|
||||
synchronized (lock) {
|
||||
uploadWorker = uploadWorkers.remove(contactId);
|
||||
}
|
||||
if (uploadWorker != null) uploadWorker.destroy();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void assignContactForDownload(ContactId contactId,
|
||||
MailboxProperties properties, MailboxFolderId folderId) {
|
||||
LOG.info("Contact assigned for download");
|
||||
if (!properties.isOwner()) throw new IllegalArgumentException();
|
||||
// Create a download worker if we don't already have one. The worker
|
||||
// will use the API to discover which folders have files to download,
|
||||
// so it doesn't need to track the set of assigned contacts
|
||||
MailboxWorker toStart = null;
|
||||
synchronized (lock) {
|
||||
if (!assignedForDownload.add(contactId)) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
if (downloadWorker == null) {
|
||||
toStart = workerFactory.createDownloadWorkerForOwnMailbox(
|
||||
connectivityChecker, reachabilityMonitor, properties);
|
||||
downloadWorker = toStart;
|
||||
}
|
||||
}
|
||||
if (toStart != null) toStart.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deassignContactForDownload(ContactId contactId) {
|
||||
LOG.info("Contact deassigned for download");
|
||||
// If there are no more contacts assigned for download, destroy the
|
||||
// download worker
|
||||
MailboxWorker toDestroy = null;
|
||||
synchronized (lock) {
|
||||
if (!assignedForDownload.remove(contactId)) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
if (assignedForDownload.isEmpty()) {
|
||||
toDestroy = downloadWorker;
|
||||
downloadWorker = null;
|
||||
}
|
||||
}
|
||||
if (toDestroy != null) toDestroy.destroy();
|
||||
}
|
||||
}
|
||||
@@ -303,7 +303,7 @@ class OwnMailboxContactListWorker
|
||||
mailboxApi.deleteContact(mailboxProperties, c);
|
||||
} catch (TolerableFailureException e) {
|
||||
// Catch this so we can continue to the next update
|
||||
logException(LOG, INFO, e);
|
||||
LOG.warning("Contact does not exist");
|
||||
}
|
||||
updateContactList();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFolderId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxProperties;
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.ApiException;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.MailboxFile;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.TolerableFailureException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
|
||||
import javax.annotation.concurrent.ThreadSafe;
|
||||
|
||||
import static java.util.Collections.shuffle;
|
||||
import static java.util.logging.Level.INFO;
|
||||
|
||||
@ThreadSafe
|
||||
@NotNullByDefault
|
||||
class OwnMailboxDownloadWorker extends MailboxDownloadWorker {
|
||||
|
||||
/**
|
||||
* The maximum number of files that will be downloaded before checking
|
||||
* again for folders with available files. This ensures that if a file
|
||||
* arrives during a download cycle, its folder will be checked within a
|
||||
* reasonable amount of time even if some other folder has a very large
|
||||
* number of files.
|
||||
* <p>
|
||||
* Package access for testing.
|
||||
*/
|
||||
static final int MAX_ROUND_ROBIN_FILES = 1000;
|
||||
|
||||
OwnMailboxDownloadWorker(
|
||||
ConnectivityChecker connectivityChecker,
|
||||
TorReachabilityMonitor torReachabilityMonitor,
|
||||
MailboxApiCaller mailboxApiCaller,
|
||||
MailboxApi mailboxApi,
|
||||
MailboxFileManager mailboxFileManager,
|
||||
MailboxProperties mailboxProperties) {
|
||||
super(connectivityChecker, torReachabilityMonitor, mailboxApiCaller,
|
||||
mailboxApi, mailboxFileManager, mailboxProperties);
|
||||
if (!mailboxProperties.isOwner()) throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ApiCall createApiCallForDownloadCycle() {
|
||||
return new SimpleApiCall(this::apiCallListFolders);
|
||||
}
|
||||
|
||||
private void apiCallListFolders() throws IOException, ApiException {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
}
|
||||
LOG.info("Listing folders with available files");
|
||||
List<MailboxFolderId> folders =
|
||||
mailboxApi.getFolders(mailboxProperties);
|
||||
if (folders.isEmpty()) onDownloadCycleFinished();
|
||||
else listNextFolder(new LinkedList<>(folders), new HashMap<>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the next folder from `queue` and starts a task to list the
|
||||
* files in the folder and add them to `available`.
|
||||
*/
|
||||
private void listNextFolder(Queue<MailboxFolderId> queue,
|
||||
Map<MailboxFolderId, Queue<MailboxFile>> available) {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
MailboxFolderId folder = queue.remove();
|
||||
apiCall = mailboxApiCaller.retryWithBackoff(new SimpleApiCall(() ->
|
||||
apiCallListFolder(folder, queue, available)));
|
||||
}
|
||||
}
|
||||
|
||||
private void apiCallListFolder(MailboxFolderId folder,
|
||||
Queue<MailboxFolderId> queue,
|
||||
Map<MailboxFolderId, Queue<MailboxFile>> available)
|
||||
throws IOException, ApiException {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
}
|
||||
LOG.info("Listing folder");
|
||||
try {
|
||||
List<MailboxFile> files =
|
||||
mailboxApi.getFiles(mailboxProperties, folder);
|
||||
if (!files.isEmpty()) {
|
||||
available.put(folder, new LinkedList<>(files));
|
||||
}
|
||||
} catch (TolerableFailureException e) {
|
||||
LOG.warning("Folder does not exist");
|
||||
}
|
||||
if (queue.isEmpty()) {
|
||||
LOG.info("Finished listing folders");
|
||||
if (available.isEmpty()) onDownloadCycleFinished();
|
||||
else createDownloadQueue(available);
|
||||
} else {
|
||||
listNextFolder(queue, available);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits the given folders in round-robin order to create a queue of up to
|
||||
* {@link #MAX_ROUND_ROBIN_FILES} to download.
|
||||
*/
|
||||
private void createDownloadQueue(
|
||||
Map<MailboxFolderId, Queue<MailboxFile>> available) {
|
||||
synchronized (lock) {
|
||||
if (state == State.DESTROYED) return;
|
||||
}
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info(available.size() + " folders have available files");
|
||||
}
|
||||
Queue<FolderFile> queue = createRoundRobinQueue(available);
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Downloading " + queue.size() + " files");
|
||||
}
|
||||
downloadNextFile(queue);
|
||||
}
|
||||
|
||||
// Package access for testing
|
||||
Queue<FolderFile> createRoundRobinQueue(
|
||||
Map<MailboxFolderId, Queue<MailboxFile>> available) {
|
||||
List<MailboxFolderId> roundRobin = new ArrayList<>(available.keySet());
|
||||
// Shuffle the folders so we don't always favour the same folders
|
||||
shuffle(roundRobin);
|
||||
Queue<FolderFile> queue = new LinkedList<>();
|
||||
while (queue.size() < MAX_ROUND_ROBIN_FILES && !available.isEmpty()) {
|
||||
Iterator<MailboxFolderId> it = roundRobin.iterator();
|
||||
while (queue.size() < MAX_ROUND_ROBIN_FILES && it.hasNext()) {
|
||||
MailboxFolderId folder = it.next();
|
||||
Queue<MailboxFile> files = available.get(folder);
|
||||
MailboxFile file = files.remove();
|
||||
queue.add(new FolderFile(folder, file.name));
|
||||
if (files.isEmpty()) {
|
||||
available.remove(folder);
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
return queue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
/**
|
||||
* An interface for converting an onion address to an HTTP URL, allowing the
|
||||
* conversion to be customised for integration tests.
|
||||
*/
|
||||
@NotNullByDefault
|
||||
interface UrlConverter {
|
||||
|
||||
/**
|
||||
* Converts a raw onion address, excluding the .onion suffix, into an
|
||||
* HTTP URL.
|
||||
*/
|
||||
String convertOnionToBaseUrl(String onion);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
||||
@NotNullByDefault
|
||||
class UrlConverterImpl implements UrlConverter {
|
||||
|
||||
@Inject
|
||||
UrlConverterImpl() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convertOnionToBaseUrl(String onion) {
|
||||
return "http://" + onion + ".onion";
|
||||
}
|
||||
}
|
||||
@@ -427,7 +427,13 @@ abstract class AbstractBluetoothPlugin<S, SS> implements BluetoothPlugin,
|
||||
BdfList descriptor = new BdfList();
|
||||
descriptor.add(TRANSPORT_ID_BLUETOOTH);
|
||||
String address = getBluetoothAddress();
|
||||
if (address != null) descriptor.add(macToBytes(address));
|
||||
if (address != null) {
|
||||
try {
|
||||
descriptor.add(macToBytes(address));
|
||||
} catch (FormatException e) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
return new BluetoothKeyAgreementListener(descriptor, ss);
|
||||
}
|
||||
|
||||
|
||||
@@ -285,7 +285,7 @@ class LanTcpPlugin extends TcpPlugin {
|
||||
if (ip.length == 16) addrs.add(InetAddress.getByAddress(ip));
|
||||
}
|
||||
return addrs;
|
||||
} catch (IllegalArgumentException | UnknownHostException e) {
|
||||
} catch (FormatException | UnknownHostException e) {
|
||||
return emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,6 +65,7 @@ import javax.annotation.concurrent.ThreadSafe;
|
||||
import javax.net.SocketFactory;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.Collections.emptyList;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static java.util.Collections.singletonMap;
|
||||
import static java.util.logging.Level.INFO;
|
||||
@@ -93,9 +94,7 @@ import static org.briarproject.bramble.api.plugin.TorConstants.PROP_ONION_V3;
|
||||
import static org.briarproject.bramble.api.plugin.TorConstants.REASON_BATTERY;
|
||||
import static org.briarproject.bramble.api.plugin.TorConstants.REASON_COUNTRY_BLOCKED;
|
||||
import static org.briarproject.bramble.api.plugin.TorConstants.REASON_MOBILE_DATA;
|
||||
import static org.briarproject.bramble.plugin.tor.CircumventionProvider.BridgeType.DEFAULT_OBFS4;
|
||||
import static org.briarproject.bramble.plugin.tor.CircumventionProvider.BridgeType.MEEK;
|
||||
import static org.briarproject.bramble.plugin.tor.CircumventionProvider.BridgeType.NON_DEFAULT_OBFS4;
|
||||
import static org.briarproject.bramble.plugin.tor.TorRendezvousCrypto.SEED_BYTES;
|
||||
import static org.briarproject.bramble.util.IoUtils.copyAndClose;
|
||||
import static org.briarproject.bramble.util.IoUtils.tryToClose;
|
||||
@@ -239,8 +238,14 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
// Load the settings
|
||||
settings = callback.getSettings();
|
||||
// Install or update the assets if necessary
|
||||
if (!assetsAreUpToDate()) installAssets();
|
||||
try {
|
||||
// Install or update the assets if necessary
|
||||
if (!assetsAreUpToDate()) installAssets();
|
||||
// Start from the default config every time
|
||||
extract(getConfigInputStream(), configFile);
|
||||
} catch (IOException e) {
|
||||
throw new PluginException(e);
|
||||
}
|
||||
if (cookieFile.exists() && !cookieFile.delete())
|
||||
LOG.warning("Old auth cookie not deleted");
|
||||
// Start a new Tor process
|
||||
@@ -302,7 +307,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
info = controlConnection.getInfo("status/circuit-established");
|
||||
if ("1".equals(info)) {
|
||||
LOG.info("Tor has already built a circuit");
|
||||
state.getAndSetCircuitBuilt(true);
|
||||
state.setCircuitBuilt(true);
|
||||
}
|
||||
} catch (TorNotRunningException e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -321,25 +326,20 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
return doneFile.lastModified() > getLastUpdateTime();
|
||||
}
|
||||
|
||||
private void installAssets() throws PluginException {
|
||||
try {
|
||||
// The done file may already exist from a previous installation
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
doneFile.delete();
|
||||
// The GeoIP file may exist from a previous installation - we can
|
||||
// save some space by deleting it.
|
||||
// TODO: Remove after a reasonable migration period
|
||||
// (added 2022-03-29)
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
geoIpFile.delete();
|
||||
installTorExecutable();
|
||||
installObfs4Executable();
|
||||
extract(getConfigInputStream(), configFile);
|
||||
if (!doneFile.createNewFile())
|
||||
LOG.warning("Failed to create done file");
|
||||
} catch (IOException e) {
|
||||
throw new PluginException(e);
|
||||
}
|
||||
private void installAssets() throws IOException {
|
||||
// The done file may already exist from a previous installation
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
doneFile.delete();
|
||||
// The GeoIP file may exist from a previous installation - we can
|
||||
// save some space by deleting it.
|
||||
// TODO: Remove after a reasonable migration period
|
||||
// (added 2022-03-29)
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
geoIpFile.delete();
|
||||
installTorExecutable();
|
||||
installObfs4Executable();
|
||||
if (!doneFile.createNewFile())
|
||||
LOG.warning("Failed to create done file");
|
||||
}
|
||||
|
||||
protected void extract(InputStream in, File dest) throws IOException {
|
||||
@@ -398,6 +398,10 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
append(strb, "SocksPort", torSocksPort);
|
||||
strb.append("GeoIPFile\n");
|
||||
strb.append("GeoIPv6File\n");
|
||||
append(strb, "ConnectionPadding", 0);
|
||||
String obfs4Path = getObfs4ExecutableFile().getAbsolutePath();
|
||||
append(strb, "ClientTransportPlugin obfs4 exec", obfs4Path);
|
||||
append(strb, "ClientTransportPlugin meek_lite exec", obfs4Path);
|
||||
//noinspection CharsetObjectCanBeUsed
|
||||
return new ByteArrayInputStream(
|
||||
strb.toString().getBytes(Charset.forName("UTF-8")));
|
||||
@@ -547,7 +551,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
|
||||
protected void enableNetwork(boolean enable) throws IOException {
|
||||
state.enableNetwork(enable);
|
||||
if (!state.enableNetwork(enable)) return; // Unchanged
|
||||
try {
|
||||
controlConnection.setConf("DisableNetwork", enable ? "0" : "1");
|
||||
} catch (TorNotRunningException e) {
|
||||
@@ -555,28 +559,20 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
}
|
||||
|
||||
private void enableBridges(boolean enable, List<BridgeType> bridgeTypes)
|
||||
private void enableBridges(List<BridgeType> bridgeTypes)
|
||||
throws IOException {
|
||||
if (!state.setBridgeTypes(bridgeTypes)) return; // Unchanged
|
||||
try {
|
||||
if (enable) {
|
||||
if (bridgeTypes.isEmpty()) {
|
||||
controlConnection.setConf("UseBridges", "0");
|
||||
controlConnection.resetConf(singletonList("Bridge"));
|
||||
} else {
|
||||
Collection<String> conf = new ArrayList<>();
|
||||
conf.add("UseBridges 1");
|
||||
File obfs4File = getObfs4ExecutableFile();
|
||||
if (bridgeTypes.contains(MEEK)) {
|
||||
conf.add("ClientTransportPlugin meek_lite exec " +
|
||||
obfs4File.getAbsolutePath());
|
||||
}
|
||||
if (bridgeTypes.contains(DEFAULT_OBFS4) ||
|
||||
bridgeTypes.contains(NON_DEFAULT_OBFS4)) {
|
||||
conf.add("ClientTransportPlugin obfs4 exec " +
|
||||
obfs4File.getAbsolutePath());
|
||||
}
|
||||
for (BridgeType bridgeType : bridgeTypes) {
|
||||
conf.addAll(circumventionProvider.getBridges(bridgeType));
|
||||
}
|
||||
controlConnection.setConf(conf);
|
||||
} else {
|
||||
controlConnection.setConf("UseBridges", "0");
|
||||
}
|
||||
} catch (TorNotRunningException e) {
|
||||
throw new RuntimeException(e);
|
||||
@@ -590,7 +586,6 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
if (controlSocket != null && controlConnection != null) {
|
||||
try {
|
||||
LOG.info("Stopping Tor");
|
||||
controlConnection.setConf("DisableNetwork", "1");
|
||||
controlConnection.shutdownTor("TERM");
|
||||
controlSocket.close();
|
||||
} catch (TorNotRunningException e) {
|
||||
@@ -758,7 +753,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
public void circuitStatus(String status, String id, String path) {
|
||||
// In case of races between receiving CIRCUIT_ESTABLISHED and setting
|
||||
// DisableNetwork, set our circuitBuilt flag if not already set
|
||||
if (status.equals("BUILT") && !state.getAndSetCircuitBuilt(true)) {
|
||||
if (status.equals("BUILT") && state.setCircuitBuilt(true)) {
|
||||
LOG.info("Circuit built");
|
||||
backoff.reset();
|
||||
}
|
||||
@@ -805,6 +800,13 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void controlConnectionClosed() {
|
||||
if (state.isTorRunning()) {
|
||||
throw new RuntimeException("Control connection closed");
|
||||
}
|
||||
}
|
||||
|
||||
private String removeSeverity(String msg) {
|
||||
return msg.replaceFirst("[^ ]+ ", "");
|
||||
}
|
||||
@@ -815,12 +817,12 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
state.setBootstrapped();
|
||||
backoff.reset();
|
||||
} else if (msg.startsWith("CIRCUIT_ESTABLISHED")) {
|
||||
if (!state.getAndSetCircuitBuilt(true)) {
|
||||
if (state.setCircuitBuilt(true)) {
|
||||
LOG.info("Circuit built");
|
||||
backoff.reset();
|
||||
}
|
||||
} else if (msg.startsWith("CIRCUIT_NOT_ESTABLISHED")) {
|
||||
if (state.getAndSetCircuitBuilt(false)) {
|
||||
if (state.setCircuitBuilt(false)) {
|
||||
LOG.info("Circuit not built");
|
||||
// TODO: Disable and re-enable network to prompt Tor to rebuild
|
||||
// its guard/bridge connections? This will also close any
|
||||
@@ -911,10 +913,8 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
|
||||
int reasonsDisabled = 0;
|
||||
boolean enableNetwork = false, enableBridges = false;
|
||||
boolean enableConnectionPadding = false;
|
||||
List<BridgeType> bridgeTypes =
|
||||
circumventionProvider.getSuitableBridgeTypes(country);
|
||||
boolean enableNetwork = false, enableConnectionPadding = false;
|
||||
List<BridgeType> bridgeTypes = emptyList();
|
||||
|
||||
if (!online) {
|
||||
LOG.info("Disabling network, device is offline");
|
||||
@@ -943,8 +943,12 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
enableNetwork = true;
|
||||
if (network == PREF_TOR_NETWORK_WITH_BRIDGES ||
|
||||
(automatic && bridgesWork)) {
|
||||
if (ipv6Only) bridgeTypes = singletonList(MEEK);
|
||||
enableBridges = true;
|
||||
if (ipv6Only) {
|
||||
bridgeTypes = singletonList(MEEK);
|
||||
} else {
|
||||
bridgeTypes = circumventionProvider
|
||||
.getSuitableBridgeTypes(country);
|
||||
}
|
||||
if (LOG.isLoggable(INFO)) {
|
||||
LOG.info("Using bridge types " + bridgeTypes);
|
||||
}
|
||||
@@ -964,9 +968,9 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
|
||||
try {
|
||||
if (enableNetwork) {
|
||||
enableBridges(enableBridges, bridgeTypes);
|
||||
enableBridges(bridgeTypes);
|
||||
enableConnectionPadding(enableConnectionPadding);
|
||||
useIpv6(ipv6Only);
|
||||
enableIpv6(ipv6Only);
|
||||
}
|
||||
enableNetwork(enableNetwork);
|
||||
} catch (IOException e) {
|
||||
@@ -976,6 +980,7 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
|
||||
private void enableConnectionPadding(boolean enable) throws IOException {
|
||||
if (!state.enableConnectionPadding(enable)) return; // Unchanged
|
||||
try {
|
||||
controlConnection.setConf("ConnectionPadding", enable ? "1" : "0");
|
||||
} catch (TorNotRunningException e) {
|
||||
@@ -983,10 +988,11 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
}
|
||||
|
||||
private void useIpv6(boolean ipv6Only) throws IOException {
|
||||
private void enableIpv6(boolean enable) throws IOException {
|
||||
if (!state.enableIpv6(enable)) return; // Unchanged
|
||||
try {
|
||||
controlConnection.setConf("ClientUseIPv4", ipv6Only ? "0" : "1");
|
||||
controlConnection.setConf("ClientUseIPv6", ipv6Only ? "1" : "0");
|
||||
controlConnection.setConf("ClientUseIPv4", enable ? "0" : "1");
|
||||
controlConnection.setConf("ClientUseIPv6", enable ? "1" : "0");
|
||||
} catch (TorNotRunningException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
@@ -1001,6 +1007,8 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
stopped = false,
|
||||
networkInitialised = false,
|
||||
networkEnabled = false,
|
||||
paddingEnabled = false,
|
||||
ipv6Enabled = false,
|
||||
bootstrapped = false,
|
||||
circuitBuilt = false,
|
||||
settingsChecked = false;
|
||||
@@ -1015,6 +1023,9 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
@GuardedBy("this")
|
||||
private int orConnectionsConnected = 0;
|
||||
|
||||
@GuardedBy("this")
|
||||
private List<BridgeType> bridgeTypes = emptyList();
|
||||
|
||||
private synchronized void setStarted() {
|
||||
started = true;
|
||||
callback.pluginStateChanged(getState());
|
||||
@@ -1035,28 +1046,66 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
}
|
||||
|
||||
private synchronized void setBootstrapped() {
|
||||
boolean wasBootstrapped = bootstrapped;
|
||||
bootstrapped = true;
|
||||
callback.pluginStateChanged(getState());
|
||||
if (!wasBootstrapped) callback.pluginStateChanged(getState());
|
||||
}
|
||||
|
||||
private synchronized boolean getAndSetCircuitBuilt(boolean built) {
|
||||
boolean old = circuitBuilt;
|
||||
/**
|
||||
* Sets the `circuitBuilt` flag and returns true if the flag has
|
||||
* changed.
|
||||
*/
|
||||
private synchronized boolean setCircuitBuilt(boolean built) {
|
||||
if (built == circuitBuilt) return false; // Unchanged
|
||||
circuitBuilt = built;
|
||||
if (built != old) callback.pluginStateChanged(getState());
|
||||
return old;
|
||||
callback.pluginStateChanged(getState());
|
||||
return true; // Changed
|
||||
}
|
||||
|
||||
private synchronized void enableNetwork(boolean enable) {
|
||||
/**
|
||||
* Sets the `networkEnabled` flag and returns true if the flag has
|
||||
* changed.
|
||||
*/
|
||||
private synchronized boolean enableNetwork(boolean enable) {
|
||||
boolean wasInitialised = networkInitialised;
|
||||
boolean wasEnabled = networkEnabled;
|
||||
networkInitialised = true;
|
||||
networkEnabled = enable;
|
||||
if (!enable) circuitBuilt = false;
|
||||
callback.pluginStateChanged(getState());
|
||||
if (!wasInitialised || enable != wasEnabled) {
|
||||
callback.pluginStateChanged(getState());
|
||||
}
|
||||
return enable != wasEnabled;
|
||||
}
|
||||
|
||||
private synchronized void setReasonsDisabled(int reasonsDisabled) {
|
||||
/**
|
||||
* Sets the `paddingEnabled` flag and returns true if the flag has
|
||||
* changed. Doesn't affect getState().
|
||||
*/
|
||||
private synchronized boolean enableConnectionPadding(boolean enable) {
|
||||
if (enable == paddingEnabled) return false; // Unchanged
|
||||
paddingEnabled = enable;
|
||||
return true; // Changed
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the `ipv6Enabled` flag and returns true if the flag has
|
||||
* changed. Doesn't affect getState().
|
||||
*/
|
||||
private synchronized boolean enableIpv6(boolean enable) {
|
||||
if (enable == ipv6Enabled) return false; // Unchanged
|
||||
ipv6Enabled = enable;
|
||||
return true; // Changed
|
||||
}
|
||||
|
||||
private synchronized void setReasonsDisabled(int reasons) {
|
||||
boolean wasChecked = settingsChecked;
|
||||
settingsChecked = true;
|
||||
this.reasonsDisabled = reasonsDisabled;
|
||||
callback.pluginStateChanged(getState());
|
||||
int oldReasons = reasonsDisabled;
|
||||
reasonsDisabled = reasons;
|
||||
if (!wasChecked || reasons != oldReasons) {
|
||||
callback.pluginStateChanged(getState());
|
||||
}
|
||||
}
|
||||
|
||||
// Doesn't affect getState()
|
||||
@@ -1071,6 +1120,17 @@ abstract class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
|
||||
if (serverSocket == ss) serverSocket = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the list of bridge types being used and returns true if the
|
||||
* list has changed. The list is empty if bridges are disabled.
|
||||
* Doesn't affect getState().
|
||||
*/
|
||||
private synchronized boolean setBridgeTypes(List<BridgeType> types) {
|
||||
if (types.equals(bridgeTypes)) return false; // Unchanged
|
||||
bridgeTypes = types;
|
||||
return true; // Changed
|
||||
}
|
||||
|
||||
private synchronized State getState() {
|
||||
if (!started || stopped || !settingsChecked) {
|
||||
return STARTING_STOPPING;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.briarproject.bramble.connection;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.connection.ConnectionRegistry;
|
||||
import org.briarproject.bramble.api.connection.InterruptibleConnection;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
@@ -57,6 +58,10 @@ public class ConnectionRegistryImplTest extends BrambleMockTestCase {
|
||||
private final Priority high =
|
||||
new Priority(fromHexString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"));
|
||||
|
||||
public ConnectionRegistryImplTest() throws FormatException {
|
||||
// required for throws declaration
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRegisterMultipleConnections() {
|
||||
context.checking(new Expectations() {{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.briarproject.bramble.crypto;
|
||||
|
||||
import org.bouncycastle.crypto.digests.Blake2bDigest;
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.test.BrambleTestCase;
|
||||
import org.briarproject.bramble.util.StringUtils;
|
||||
import org.junit.Test;
|
||||
@@ -47,7 +48,7 @@ public class Blake2bDigestTest extends BrambleTestCase {
|
||||
};
|
||||
|
||||
@Test
|
||||
public void testDigestWithKeyedTestVectors() {
|
||||
public void testDigestWithKeyedTestVectors() throws FormatException {
|
||||
for (String[] keyedTestVector : KEYED_TEST_VECTORS) {
|
||||
byte[] input = StringUtils.fromHexString(keyedTestVector[0]);
|
||||
byte[] key = StringUtils.fromHexString(keyedTestVector[1]);
|
||||
@@ -63,7 +64,8 @@ public class Blake2bDigestTest extends BrambleTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDigestWithKeyedTestVectorsAndRandomUpdate() {
|
||||
public void testDigestWithKeyedTestVectorsAndRandomUpdate()
|
||||
throws FormatException {
|
||||
Random random = new Random();
|
||||
for (int i = 0; i < 100; i++) {
|
||||
for (String[] keyedTestVector : KEYED_TEST_VECTORS) {
|
||||
@@ -138,7 +140,7 @@ public class Blake2bDigestTest extends BrambleTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runSelfTest() {
|
||||
public void runSelfTest() throws FormatException {
|
||||
Blake2bDigest testDigest = new Blake2bDigest(256);
|
||||
byte[] md = new byte[64];
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.briarproject.bramble.crypto;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.crypto.AgreementPublicKey;
|
||||
import org.briarproject.bramble.api.crypto.CryptoComponent;
|
||||
import org.briarproject.bramble.api.crypto.KeyPair;
|
||||
@@ -83,7 +84,7 @@ public class KeyAgreementTest extends BrambleTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRfc7748TestVector() {
|
||||
public void testRfc7748TestVector() throws FormatException {
|
||||
byte[] aPriv = parsePrivateKey(ALICE_PRIVATE);
|
||||
byte[] aPub = fromHexString(ALICE_PUBLIC);
|
||||
byte[] bPriv = parsePrivateKey(BOB_PRIVATE);
|
||||
@@ -97,7 +98,8 @@ public class KeyAgreementTest extends BrambleTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDerivesSameSharedSecretFromEquivalentPublicKey() {
|
||||
public void testDerivesSameSharedSecretFromEquivalentPublicKey()
|
||||
throws FormatException {
|
||||
byte[] aPub = fromHexString(ALICE_PUBLIC);
|
||||
byte[] bPriv = parsePrivateKey(BOB_PRIVATE);
|
||||
byte[] sharedSecret = fromHexString(SHARED_SECRET);
|
||||
@@ -168,7 +170,7 @@ public class KeyAgreementTest extends BrambleTestCase {
|
||||
return crypto.deriveSharedSecret(label, publicKey, keyPair, inputs);
|
||||
}
|
||||
|
||||
private byte[] parsePrivateKey(String hex) {
|
||||
private byte[] parsePrivateKey(String hex) throws FormatException {
|
||||
// Private keys need to be clamped because curve25519-java does the
|
||||
// clamping at key generation time, not multiplication time
|
||||
return AgreementKeyParser.clamp(fromHexString(hex));
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.briarproject.bramble.crypto;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.crypto.SecretKey;
|
||||
import org.briarproject.bramble.test.BrambleTestCase;
|
||||
import org.briarproject.bramble.util.StringUtils;
|
||||
@@ -15,11 +16,11 @@ public class XSalsa20Poly1305AuthenticatedCipherTest extends BrambleTestCase {
|
||||
|
||||
// Test vectors from the NaCl paper
|
||||
// http://cr.yp.to/highspeed/naclcrypto-20090310.pdf
|
||||
private static final byte[] TEST_KEY = StringUtils.fromHexString(
|
||||
private final byte[] TEST_KEY = StringUtils.fromHexString(
|
||||
"1b27556473e985d462cd51197a9a46c76009549eac6474f206c4ee0844f68389");
|
||||
private static final byte[] TEST_IV = StringUtils.fromHexString(
|
||||
private final byte[] TEST_IV = StringUtils.fromHexString(
|
||||
"69696ee955b62b73cd62bda875fc73d68219e0036b7a0b37");
|
||||
private static final byte[] TEST_PLAINTEXT = StringUtils.fromHexString(
|
||||
private final byte[] TEST_PLAINTEXT = StringUtils.fromHexString(
|
||||
"be075fc53c81f2d5cf141316" +
|
||||
"ebeb0c7b5228c52a4c62cbd4" +
|
||||
"4b66849b64244ffce5ecbaaf" +
|
||||
@@ -31,7 +32,7 @@ public class XSalsa20Poly1305AuthenticatedCipherTest extends BrambleTestCase {
|
||||
"048977eb48f59ffd4924ca1c" +
|
||||
"60902e52f0a089bc76897040" +
|
||||
"e082f937763848645e0705");
|
||||
private static final byte[] TEST_CIPHERTEXT = StringUtils.fromHexString(
|
||||
private final byte[] TEST_CIPHERTEXT = StringUtils.fromHexString(
|
||||
"f3ffc7703f9400e52a7dfb4b" +
|
||||
"3d3305d98e993b9f48681273" +
|
||||
"c29650ba32fc76ce48332ea7" +
|
||||
@@ -46,6 +47,10 @@ public class XSalsa20Poly1305AuthenticatedCipherTest extends BrambleTestCase {
|
||||
"a43d14a6599b1f654cb45a74" +
|
||||
"e355a5");
|
||||
|
||||
public XSalsa20Poly1305AuthenticatedCipherTest() throws FormatException {
|
||||
// required for throws declaration
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncrypt() throws Exception {
|
||||
SecretKey k = new SecretKey(TEST_KEY);
|
||||
|
||||
@@ -618,11 +618,12 @@ public class BdfReaderImplTest extends BrambleTestCase {
|
||||
r.readDictionary();
|
||||
}
|
||||
|
||||
private void setContents(String hex) {
|
||||
private void setContents(String hex) throws FormatException {
|
||||
setContents(hex, DEFAULT_MAX_BUFFER_SIZE);
|
||||
}
|
||||
|
||||
private void setContents(String hex, int maxBufferSize) {
|
||||
private void setContents(String hex, int maxBufferSize)
|
||||
throws FormatException {
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(fromHexString(hex));
|
||||
r = new BdfReaderImpl(in, DEFAULT_NESTED_LIMIT, maxBufferSize);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import org.briarproject.bramble.api.db.DatabaseComponent;
|
||||
import org.briarproject.bramble.api.db.Transaction;
|
||||
import org.briarproject.bramble.api.event.EventBus;
|
||||
import org.briarproject.bramble.api.lifecycle.LifecycleManager.OpenDatabaseHook;
|
||||
import org.briarproject.bramble.api.lifecycle.Service;
|
||||
import org.briarproject.bramble.api.lifecycle.event.LifecycleEvent;
|
||||
import org.briarproject.bramble.api.system.Clock;
|
||||
import org.briarproject.bramble.test.BrambleMockTestCase;
|
||||
@@ -12,12 +13,10 @@ import org.briarproject.bramble.test.DbExpectations;
|
||||
import org.jmock.Expectations;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import static junit.framework.TestCase.assertTrue;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.RUNNING;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STARTING;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STOPPING;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.LifecycleState.STOPPED;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.StartResult.ALREADY_RUNNING;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.StartResult.CLOCK_ERROR;
|
||||
import static org.briarproject.bramble.api.lifecycle.LifecycleManager.StartResult.SUCCESS;
|
||||
import static org.briarproject.bramble.api.system.Clock.MAX_REASONABLE_TIME_MS;
|
||||
@@ -30,6 +29,8 @@ public class LifecycleManagerImplTest extends BrambleMockTestCase {
|
||||
private final DatabaseComponent db = context.mock(DatabaseComponent.class);
|
||||
private final EventBus eventBus = context.mock(EventBus.class);
|
||||
private final Clock clock = context.mock(Clock.class);
|
||||
private final OpenDatabaseHook hook = context.mock(OpenDatabaseHook.class);
|
||||
private final Service service = context.mock(Service.class);
|
||||
|
||||
private final SecretKey dbKey = getSecretKey();
|
||||
|
||||
@@ -40,8 +41,6 @@ public class LifecycleManagerImplTest extends BrambleMockTestCase {
|
||||
public void testOpenDatabaseHooksAreCalledAtStartup() throws Exception {
|
||||
long now = System.currentTimeMillis();
|
||||
Transaction txn = new Transaction(null, false);
|
||||
AtomicBoolean called = new AtomicBoolean(false);
|
||||
OpenDatabaseHook hook = transaction -> called.set(true);
|
||||
|
||||
context.checking(new DbExpectations() {{
|
||||
oneOf(clock).currentTimeMillis();
|
||||
@@ -50,6 +49,7 @@ public class LifecycleManagerImplTest extends BrambleMockTestCase {
|
||||
will(returnValue(false));
|
||||
oneOf(db).transaction(with(false), withDbRunnable(txn));
|
||||
oneOf(db).removeTemporaryMessages(txn);
|
||||
oneOf(hook).onDatabaseOpened(txn);
|
||||
allowing(eventBus).broadcast(with(any(LifecycleEvent.class)));
|
||||
}});
|
||||
|
||||
@@ -57,7 +57,38 @@ public class LifecycleManagerImplTest extends BrambleMockTestCase {
|
||||
|
||||
assertEquals(SUCCESS, lifecycleManager.startServices(dbKey));
|
||||
assertEquals(RUNNING, lifecycleManager.getLifecycleState());
|
||||
assertTrue(called.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServicesAreStartedAndStopped() throws Exception {
|
||||
long now = System.currentTimeMillis();
|
||||
Transaction txn = new Transaction(null, false);
|
||||
|
||||
context.checking(new DbExpectations() {{
|
||||
oneOf(clock).currentTimeMillis();
|
||||
will(returnValue(now));
|
||||
oneOf(db).open(dbKey, lifecycleManager);
|
||||
will(returnValue(false));
|
||||
oneOf(db).transaction(with(false), withDbRunnable(txn));
|
||||
oneOf(db).removeTemporaryMessages(txn);
|
||||
oneOf(service).startService();
|
||||
allowing(eventBus).broadcast(with(any(LifecycleEvent.class)));
|
||||
}});
|
||||
|
||||
lifecycleManager.registerService(service);
|
||||
|
||||
assertEquals(SUCCESS, lifecycleManager.startServices(dbKey));
|
||||
assertEquals(RUNNING, lifecycleManager.getLifecycleState());
|
||||
context.assertIsSatisfied();
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(db).close();
|
||||
oneOf(service).stopService();
|
||||
allowing(eventBus).broadcast(with(any(LifecycleEvent.class)));
|
||||
}});
|
||||
|
||||
lifecycleManager.stopServices();
|
||||
assertEquals(STOPPED, lifecycleManager.getLifecycleState());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -84,6 +115,31 @@ public class LifecycleManagerImplTest extends BrambleMockTestCase {
|
||||
assertEquals(STARTING, lifecycleManager.getLifecycleState());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSecondCallToStartServicesReturnsEarly() throws Exception {
|
||||
long now = System.currentTimeMillis();
|
||||
Transaction txn = new Transaction(null, false);
|
||||
|
||||
context.checking(new DbExpectations() {{
|
||||
oneOf(clock).currentTimeMillis();
|
||||
will(returnValue(now));
|
||||
oneOf(db).open(dbKey, lifecycleManager);
|
||||
will(returnValue(false));
|
||||
oneOf(db).transaction(with(false), withDbRunnable(txn));
|
||||
oneOf(db).removeTemporaryMessages(txn);
|
||||
allowing(eventBus).broadcast(with(any(LifecycleEvent.class)));
|
||||
}});
|
||||
|
||||
assertEquals(SUCCESS, lifecycleManager.startServices(dbKey));
|
||||
assertEquals(RUNNING, lifecycleManager.getLifecycleState());
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Calling startServices() again should not try to open the DB or
|
||||
// start the services again
|
||||
assertEquals(ALREADY_RUNNING, lifecycleManager.startServices(dbKey));
|
||||
assertEquals(RUNNING, lifecycleManager.getLifecycleState());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSecondCallToStopServicesReturnsEarly() throws Exception {
|
||||
long now = System.currentTimeMillis();
|
||||
@@ -96,7 +152,7 @@ public class LifecycleManagerImplTest extends BrambleMockTestCase {
|
||||
will(returnValue(false));
|
||||
oneOf(db).transaction(with(false), withDbRunnable(txn));
|
||||
oneOf(db).removeTemporaryMessages(txn);
|
||||
exactly(2).of(eventBus).broadcast(with(any(LifecycleEvent.class)));
|
||||
allowing(eventBus).broadcast(with(any(LifecycleEvent.class)));
|
||||
}});
|
||||
|
||||
assertEquals(SUCCESS, lifecycleManager.startServices(dbKey));
|
||||
@@ -104,17 +160,17 @@ public class LifecycleManagerImplTest extends BrambleMockTestCase {
|
||||
context.assertIsSatisfied();
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(eventBus).broadcast(with(any(LifecycleEvent.class)));
|
||||
oneOf(db).close();
|
||||
allowing(eventBus).broadcast(with(any(LifecycleEvent.class)));
|
||||
}});
|
||||
|
||||
lifecycleManager.stopServices();
|
||||
assertEquals(STOPPING, lifecycleManager.getLifecycleState());
|
||||
assertEquals(STOPPED, lifecycleManager.getLifecycleState());
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// Calling stopServices() again should not broadcast another event or
|
||||
// try to close the DB again
|
||||
lifecycleManager.stopServices();
|
||||
assertEquals(STOPPING, lifecycleManager.getLifecycleState());
|
||||
assertEquals(STOPPED, lifecycleManager.getLifecycleState());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ public class ContactMailboxClientTest extends BrambleMockTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assignContactForDownloadAndDestroyClient() {
|
||||
public void testAssignContactForDownloadAndDestroyClient() {
|
||||
client.start();
|
||||
|
||||
// When the contact is assigned, the worker should be created and
|
||||
@@ -89,7 +89,7 @@ public class ContactMailboxClientTest extends BrambleMockTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assignAndDeassignContactForDownload() {
|
||||
public void testAssignAndDeassignContactForDownload() {
|
||||
client.start();
|
||||
|
||||
// When the contact is assigned, the worker should be created and
|
||||
|
||||
@@ -1,88 +1,68 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.api.Cancellable;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFileId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxProperties;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.MailboxFile;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.TolerableFailureException;
|
||||
import org.briarproject.bramble.test.BrambleMockTestCase;
|
||||
import org.briarproject.bramble.test.CaptureArgumentAction;
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.lib.action.DoAllAction;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.Collections.emptyList;
|
||||
import static org.briarproject.bramble.api.mailbox.MailboxConstants.CLIENT_SUPPORTS;
|
||||
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
|
||||
import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory;
|
||||
import static org.briarproject.bramble.test.TestUtils.getMailboxProperties;
|
||||
import static org.briarproject.bramble.test.TestUtils.getRandomId;
|
||||
import static org.briarproject.bramble.test.TestUtils.getTestDirectory;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class ContactMailboxDownloadWorkerTest extends BrambleMockTestCase {
|
||||
public class ContactMailboxDownloadWorkerTest
|
||||
extends MailboxDownloadWorkerTest<ContactMailboxDownloadWorker> {
|
||||
|
||||
private final ConnectivityChecker connectivityChecker =
|
||||
context.mock(ConnectivityChecker.class);
|
||||
private final TorReachabilityMonitor torReachabilityMonitor =
|
||||
context.mock(TorReachabilityMonitor.class);
|
||||
private final MailboxApiCaller mailboxApiCaller =
|
||||
context.mock(MailboxApiCaller.class);
|
||||
private final MailboxApi mailboxApi = context.mock(MailboxApi.class);
|
||||
private final MailboxFileManager mailboxFileManager =
|
||||
context.mock(MailboxFileManager.class);
|
||||
private final Cancellable apiCall = context.mock(Cancellable.class);
|
||||
|
||||
private final MailboxProperties mailboxProperties =
|
||||
getMailboxProperties(false, CLIENT_SUPPORTS);
|
||||
private final long now = System.currentTimeMillis();
|
||||
private final MailboxFile file1 =
|
||||
new MailboxFile(new MailboxFileId(getRandomId()), now - 1);
|
||||
private final MailboxFile file2 =
|
||||
new MailboxFile(new MailboxFileId(getRandomId()), now);
|
||||
private final List<MailboxFile> files = asList(file1, file2);
|
||||
|
||||
private File testDir, tempFile;
|
||||
private ContactMailboxDownloadWorker worker;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
testDir = getTestDirectory();
|
||||
tempFile = new File(testDir, "temp");
|
||||
public ContactMailboxDownloadWorkerTest() {
|
||||
mailboxProperties = getMailboxProperties(false, CLIENT_SUPPORTS);
|
||||
worker = new ContactMailboxDownloadWorker(connectivityChecker,
|
||||
torReachabilityMonitor, mailboxApiCaller, mailboxApi,
|
||||
mailboxFileManager, mailboxProperties);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
deleteTestDirectory(testDir);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testChecksConnectivityWhenStartedAndRemovesObserverWhenDestroyed() {
|
||||
// When the worker is started it should start a connectivity check
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(connectivityChecker).checkConnectivity(
|
||||
with(mailboxProperties), with(worker));
|
||||
}});
|
||||
|
||||
expectStartConnectivityCheck();
|
||||
worker.start();
|
||||
|
||||
// When the worker is destroyed it should remove the connectivity
|
||||
// and reachability observers
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(connectivityChecker).removeObserver(worker);
|
||||
oneOf(torReachabilityMonitor).removeObserver(worker);
|
||||
}});
|
||||
expectRemoveObservers();
|
||||
worker.destroy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testChecksForFilesWhenConnectivityCheckSucceeds()
|
||||
throws Exception {
|
||||
// When the worker is started it should start a connectivity check
|
||||
expectStartConnectivityCheck();
|
||||
worker.start();
|
||||
|
||||
// When the connectivity check succeeds, a list-inbox task should be
|
||||
// started for the first download cycle
|
||||
AtomicReference<ApiCall> listTask = new AtomicReference<>();
|
||||
expectStartTask(listTask);
|
||||
worker.onConnectivityCheckSucceeded();
|
||||
|
||||
// When the list-inbox tasks runs and finds no files to download,
|
||||
// it should add a Tor reachability observer
|
||||
expectCheckForFiles(mailboxProperties.getInboxId(), emptyList());
|
||||
expectAddReachabilityObserver();
|
||||
assertFalse(listTask.get().callApi());
|
||||
|
||||
// When the reachability observer is called, a list-inbox task should
|
||||
// be started for the second download cycle
|
||||
expectStartTask(listTask);
|
||||
worker.onTorReachable();
|
||||
|
||||
// When the list-inbox tasks runs and finds no files to download,
|
||||
// it should finish the second download cycle
|
||||
expectCheckForFiles(mailboxProperties.getInboxId(), emptyList());
|
||||
assertFalse(listTask.get().callApi());
|
||||
|
||||
// When the worker is destroyed it should remove the connectivity
|
||||
// and reachability observers
|
||||
expectRemoveObservers();
|
||||
worker.destroy();
|
||||
}
|
||||
|
||||
@@ -90,150 +70,67 @@ public class ContactMailboxDownloadWorkerTest extends BrambleMockTestCase {
|
||||
public void testDownloadsFilesWhenConnectivityCheckSucceeds()
|
||||
throws Exception {
|
||||
// When the worker is started it should start a connectivity check
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(connectivityChecker).checkConnectivity(
|
||||
with(mailboxProperties), with(worker));
|
||||
}});
|
||||
|
||||
expectStartConnectivityCheck();
|
||||
worker.start();
|
||||
|
||||
// When the connectivity check succeeds, a list-inbox task should be
|
||||
// started for the first download cycle
|
||||
AtomicReference<ApiCall> listTask = new AtomicReference<>();
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxApiCaller).retryWithBackoff(with(any(ApiCall.class)));
|
||||
will(new DoAllAction(
|
||||
new CaptureArgumentAction<>(listTask, ApiCall.class, 0),
|
||||
returnValue(apiCall)
|
||||
));
|
||||
}});
|
||||
|
||||
expectStartTask(listTask);
|
||||
worker.onConnectivityCheckSucceeded();
|
||||
|
||||
// When the list-inbox tasks runs and finds some files to download,
|
||||
// it should start a download task for the first file
|
||||
AtomicReference<ApiCall> downloadTask = new AtomicReference<>();
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxApi).getFiles(mailboxProperties,
|
||||
requireNonNull(mailboxProperties.getInboxId()));
|
||||
will(returnValue(files));
|
||||
oneOf(mailboxApiCaller).retryWithBackoff(with(any(ApiCall.class)));
|
||||
will(new DoAllAction(
|
||||
new CaptureArgumentAction<>(downloadTask, ApiCall.class, 0),
|
||||
returnValue(apiCall)
|
||||
));
|
||||
}});
|
||||
|
||||
expectCheckForFiles(mailboxProperties.getInboxId(), files);
|
||||
expectStartTask(downloadTask);
|
||||
assertFalse(listTask.get().callApi());
|
||||
|
||||
// When the first download task runs it should download the file to the
|
||||
// location provided by the file manager and start a delete task
|
||||
AtomicReference<ApiCall> deleteTask = new AtomicReference<>();
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxFileManager).createTempFileForDownload();
|
||||
will(returnValue(tempFile));
|
||||
oneOf(mailboxApi).getFile(mailboxProperties,
|
||||
requireNonNull(mailboxProperties.getInboxId()),
|
||||
file1.name, tempFile);
|
||||
oneOf(mailboxFileManager).handleDownloadedFile(tempFile);
|
||||
oneOf(mailboxApiCaller).retryWithBackoff(with(any(ApiCall.class)));
|
||||
will(new DoAllAction(
|
||||
new CaptureArgumentAction<>(deleteTask, ApiCall.class, 0),
|
||||
returnValue(apiCall)
|
||||
));
|
||||
}});
|
||||
|
||||
expectDownloadFile(mailboxProperties.getInboxId(), file1);
|
||||
expectStartTask(deleteTask);
|
||||
assertFalse(downloadTask.get().callApi());
|
||||
|
||||
// When the first delete task runs it should delete the file, ignore
|
||||
// the tolerable failure, and start a download task for the next file
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxApi).deleteFile(mailboxProperties,
|
||||
requireNonNull(mailboxProperties.getInboxId()), file1.name);
|
||||
will(throwException(new TolerableFailureException()));
|
||||
oneOf(mailboxApiCaller).retryWithBackoff(with(any(ApiCall.class)));
|
||||
will(new DoAllAction(
|
||||
new CaptureArgumentAction<>(downloadTask, ApiCall.class, 0),
|
||||
returnValue(apiCall)
|
||||
));
|
||||
}});
|
||||
|
||||
expectDeleteFile(mailboxProperties.getInboxId(), file1, true);
|
||||
expectStartTask(downloadTask);
|
||||
assertFalse(deleteTask.get().callApi());
|
||||
|
||||
// When the second download task runs it should download the file to
|
||||
// the location provided by the file manager and start a delete task
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxFileManager).createTempFileForDownload();
|
||||
will(returnValue(tempFile));
|
||||
oneOf(mailboxApi).getFile(mailboxProperties,
|
||||
requireNonNull(mailboxProperties.getInboxId()),
|
||||
file2.name, tempFile);
|
||||
oneOf(mailboxFileManager).handleDownloadedFile(tempFile);
|
||||
oneOf(mailboxApiCaller).retryWithBackoff(with(any(ApiCall.class)));
|
||||
will(new DoAllAction(
|
||||
new CaptureArgumentAction<>(deleteTask, ApiCall.class, 0),
|
||||
returnValue(apiCall)
|
||||
));
|
||||
}});
|
||||
|
||||
expectDownloadFile(mailboxProperties.getInboxId(), file2);
|
||||
expectStartTask(deleteTask);
|
||||
assertFalse(downloadTask.get().callApi());
|
||||
|
||||
// When the second delete task runs it should delete the file and
|
||||
// start a list-inbox task to check for files that may have arrived
|
||||
// since the first download cycle started
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxApi).deleteFile(mailboxProperties,
|
||||
requireNonNull(mailboxProperties.getInboxId()), file2.name);
|
||||
will(throwException(new TolerableFailureException()));
|
||||
oneOf(mailboxApiCaller).retryWithBackoff(with(any(ApiCall.class)));
|
||||
will(new DoAllAction(
|
||||
new CaptureArgumentAction<>(listTask, ApiCall.class, 0),
|
||||
returnValue(apiCall)
|
||||
));
|
||||
}});
|
||||
|
||||
expectDeleteFile(mailboxProperties.getInboxId(), file2, false);
|
||||
expectStartTask(listTask);
|
||||
assertFalse(deleteTask.get().callApi());
|
||||
|
||||
// When the list-inbox tasks runs and finds no more files to download,
|
||||
// it should add a Tor reachability observer
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxApi).getFiles(mailboxProperties,
|
||||
requireNonNull(mailboxProperties.getInboxId()));
|
||||
will(returnValue(emptyList()));
|
||||
oneOf(torReachabilityMonitor).addOneShotObserver(worker);
|
||||
}});
|
||||
|
||||
expectCheckForFiles(mailboxProperties.getInboxId(), emptyList());
|
||||
expectAddReachabilityObserver();
|
||||
assertFalse(listTask.get().callApi());
|
||||
|
||||
// When the reachability observer is called, a list-inbox task should
|
||||
// be started for the second download cycle
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxApiCaller).retryWithBackoff(with(any(ApiCall.class)));
|
||||
will(new DoAllAction(
|
||||
new CaptureArgumentAction<>(listTask, ApiCall.class, 0),
|
||||
returnValue(apiCall)
|
||||
));
|
||||
}});
|
||||
|
||||
expectStartTask(listTask);
|
||||
worker.onTorReachable();
|
||||
|
||||
// When the list-inbox tasks runs and finds no more files to download,
|
||||
// it should finish the second download cycle
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxApi).getFiles(mailboxProperties,
|
||||
requireNonNull(mailboxProperties.getInboxId()));
|
||||
will(returnValue(emptyList()));
|
||||
}});
|
||||
|
||||
expectCheckForFiles(mailboxProperties.getInboxId(), emptyList());
|
||||
assertFalse(listTask.get().callApi());
|
||||
|
||||
// When the worker is destroyed it should remove the connectivity
|
||||
// and reachability observers
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(connectivityChecker).removeObserver(worker);
|
||||
oneOf(torReachabilityMonitor).removeObserver(worker);
|
||||
}});
|
||||
|
||||
expectRemoveObservers();
|
||||
worker.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.api.WeakSingletonProvider;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.mailbox.InvalidMailboxIdException;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxAuthToken;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFileId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFolderId;
|
||||
@@ -13,7 +11,6 @@ import org.briarproject.bramble.mailbox.MailboxApi.MailboxFile;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.TolerableFailureException;
|
||||
import org.briarproject.bramble.test.BrambleTestCase;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
@@ -25,14 +22,11 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.net.SocketFactory;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
|
||||
import static java.util.Collections.emptyList;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
import static org.briarproject.bramble.mailbox.MailboxIntegrationTestUtils.SETUP_TOKEN;
|
||||
import static org.briarproject.bramble.mailbox.MailboxIntegrationTestUtils.URL_BASE;
|
||||
import static org.briarproject.bramble.mailbox.MailboxIntegrationTestUtils.createMailboxApi;
|
||||
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
|
||||
import static org.briarproject.bramble.test.TestUtils.getRandomId;
|
||||
import static org.briarproject.bramble.test.TestUtils.isOptionalTestEnabled;
|
||||
@@ -40,56 +34,31 @@ import static org.briarproject.bramble.test.TestUtils.readBytes;
|
||||
import static org.briarproject.bramble.test.TestUtils.writeBytes;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assume.assumeTrue;
|
||||
|
||||
public class MailboxIntegrationTest extends BrambleTestCase {
|
||||
public class MailboxApiIntegrationTest extends BrambleTestCase {
|
||||
|
||||
@Rule
|
||||
public TemporaryFolder folder = new TemporaryFolder();
|
||||
|
||||
private final static String URL_BASE = "http://127.0.0.1:8000";
|
||||
private final static MailboxAuthToken SETUP_TOKEN;
|
||||
private static final MailboxApi api = createMailboxApi();
|
||||
|
||||
static {
|
||||
try {
|
||||
SETUP_TOKEN = MailboxAuthToken.fromString(
|
||||
"54686973206973206120736574757020746f6b656e20666f722042726961722e");
|
||||
} catch (InvalidMailboxIdException e) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
private static final OkHttpClient client = new OkHttpClient.Builder()
|
||||
.socketFactory(SocketFactory.getDefault())
|
||||
.connectTimeout(60_000, MILLISECONDS)
|
||||
.build();
|
||||
private static final WeakSingletonProvider<OkHttpClient>
|
||||
httpClientProvider =
|
||||
new WeakSingletonProvider<OkHttpClient>() {
|
||||
@Override
|
||||
@Nonnull
|
||||
public OkHttpClient createInstance() {
|
||||
return client;
|
||||
}
|
||||
};
|
||||
private final static MailboxApiImpl api =
|
||||
new MailboxApiImpl(httpClientProvider);
|
||||
// needs to be static to keep values across different tests
|
||||
private static MailboxProperties ownerProperties;
|
||||
|
||||
/**
|
||||
* Called before each test to make sure the mailbox is setup once
|
||||
* before starting with individual tests.
|
||||
* {@link BeforeClass} needs to be static, so we can't use the API class.
|
||||
*/
|
||||
@Before
|
||||
public void ensureSetup() throws IOException, ApiException {
|
||||
@BeforeClass
|
||||
public static void setUp() throws IOException, ApiException {
|
||||
// Skip this test unless it's explicitly enabled in the environment
|
||||
assumeTrue(isOptionalTestEnabled(MailboxIntegrationTest.class));
|
||||
assumeTrue(isOptionalTestEnabled(MailboxApiIntegrationTest.class));
|
||||
|
||||
if (ownerProperties != null) return;
|
||||
assertNull(ownerProperties);
|
||||
MailboxProperties setupProperties = new MailboxProperties(
|
||||
URL_BASE, SETUP_TOKEN, new ArrayList<>());
|
||||
ownerProperties = api.setup(setupProperties);
|
||||
@@ -98,7 +67,7 @@ public class MailboxIntegrationTest extends BrambleTestCase {
|
||||
@AfterClass
|
||||
// we can't test wiping as a regular test as it stops the mailbox
|
||||
public static void wipe() throws IOException, ApiException {
|
||||
if (!isOptionalTestEnabled(MailboxIntegrationTest.class)) return;
|
||||
if (!isOptionalTestEnabled(MailboxApiIntegrationTest.class)) return;
|
||||
|
||||
api.wipeMailbox(ownerProperties);
|
||||
|
||||
@@ -121,7 +90,7 @@ public class MailboxIntegrationTest extends BrambleTestCase {
|
||||
ContactId contactId = new ContactId(1);
|
||||
MailboxContact contact = getMailboxContact(contactId);
|
||||
MailboxProperties contactProperties = new MailboxProperties(
|
||||
ownerProperties.getBaseUrl(), contact.token,
|
||||
ownerProperties.getOnion(), contact.token,
|
||||
new ArrayList<>(), contact.inboxId, contact.outboxId);
|
||||
api.addContact(ownerProperties, contact);
|
||||
|
||||
@@ -167,7 +136,7 @@ public class MailboxIntegrationTest extends BrambleTestCase {
|
||||
ContactId contactId = new ContactId(1);
|
||||
MailboxContact contact = getMailboxContact(contactId);
|
||||
MailboxProperties contactProperties = new MailboxProperties(
|
||||
ownerProperties.getBaseUrl(), contact.token,
|
||||
ownerProperties.getOnion(), contact.token,
|
||||
new ArrayList<>(), contact.inboxId, contact.outboxId);
|
||||
api.addContact(ownerProperties, contact);
|
||||
|
||||
@@ -184,7 +153,7 @@ public class MailboxIntegrationTest extends BrambleTestCase {
|
||||
MailboxFileId fileName1 = files1.get(0).name;
|
||||
|
||||
// owner can't check files
|
||||
assertThrows(ApiException.class, () ->
|
||||
assertThrows(TolerableFailureException.class, () ->
|
||||
api.getFiles(ownerProperties, contact.inboxId));
|
||||
|
||||
// contact downloads file
|
||||
@@ -195,12 +164,13 @@ public class MailboxIntegrationTest extends BrambleTestCase {
|
||||
|
||||
// owner can't download file, even if knowing name
|
||||
File file1forbidden = folder.newFile();
|
||||
assertThrows(ApiException.class, () -> api.getFile(ownerProperties,
|
||||
contact.inboxId, fileName1, file1forbidden));
|
||||
assertThrows(TolerableFailureException.class, () ->
|
||||
api.getFile(ownerProperties, contact.inboxId, fileName1,
|
||||
file1forbidden));
|
||||
assertEquals(0, file1forbidden.length());
|
||||
|
||||
// owner can't delete file
|
||||
assertThrows(ApiException.class, () ->
|
||||
assertThrows(TolerableFailureException.class, () ->
|
||||
api.deleteFile(ownerProperties, contact.inboxId, fileName1));
|
||||
|
||||
// contact deletes file
|
||||
@@ -230,7 +200,7 @@ public class MailboxIntegrationTest extends BrambleTestCase {
|
||||
MailboxFileId file3name = files2.get(1).name;
|
||||
|
||||
// contact can't list files in contact's outbox
|
||||
assertThrows(ApiException.class, () ->
|
||||
assertThrows(TolerableFailureException.class, () ->
|
||||
api.getFiles(contactProperties, contact.outboxId));
|
||||
|
||||
// owner downloads both files from contact's outbox
|
||||
@@ -250,17 +220,19 @@ public class MailboxIntegrationTest extends BrambleTestCase {
|
||||
// contact can't download files again, even if knowing name
|
||||
File file2forbidden = folder.newFile();
|
||||
File file3forbidden = folder.newFile();
|
||||
assertThrows(ApiException.class, () -> api.getFile(contactProperties,
|
||||
contact.outboxId, file2name, file2forbidden));
|
||||
assertThrows(ApiException.class, () -> api.getFile(contactProperties,
|
||||
contact.outboxId, file3name, file3forbidden));
|
||||
assertThrows(TolerableFailureException.class, () ->
|
||||
api.getFile(contactProperties, contact.outboxId, file2name,
|
||||
file2forbidden));
|
||||
assertThrows(TolerableFailureException.class, () ->
|
||||
api.getFile(contactProperties, contact.outboxId, file3name,
|
||||
file3forbidden));
|
||||
assertEquals(0, file1forbidden.length());
|
||||
assertEquals(0, file2forbidden.length());
|
||||
|
||||
// contact can't delete files in outbox
|
||||
assertThrows(ApiException.class, () ->
|
||||
assertThrows(TolerableFailureException.class, () ->
|
||||
api.deleteFile(contactProperties, contact.outboxId, file2name));
|
||||
assertThrows(ApiException.class, () ->
|
||||
assertThrows(TolerableFailureException.class, () ->
|
||||
api.deleteFile(contactProperties, contact.outboxId, file3name));
|
||||
|
||||
// owner deletes files
|
||||
@@ -68,7 +68,10 @@ public class MailboxApiTest extends BrambleTestCase {
|
||||
return client;
|
||||
}
|
||||
};
|
||||
private final MailboxApiImpl api = new MailboxApiImpl(httpClientProvider);
|
||||
// We aren't using a real onion address, so use the given address verbatim
|
||||
private final UrlConverter urlConverter = onion -> onion;
|
||||
private final MailboxApiImpl api = new MailboxApiImpl(httpClientProvider,
|
||||
urlConverter);
|
||||
|
||||
private final MailboxAuthToken token = new MailboxAuthToken(getRandomId());
|
||||
private final MailboxAuthToken token2 = new MailboxAuthToken(getRandomId());
|
||||
@@ -627,6 +630,7 @@ public class MailboxApiTest extends BrambleTestCase {
|
||||
server.enqueue(new MockResponse().setBody(invalidResponse3));
|
||||
server.enqueue(new MockResponse().setBody(invalidResponse4));
|
||||
server.enqueue(new MockResponse().setResponseCode(401));
|
||||
server.enqueue(new MockResponse().setResponseCode(404));
|
||||
server.enqueue(new MockResponse().setResponseCode(500));
|
||||
server.start();
|
||||
String baseUrl = getBaseUrl(server);
|
||||
@@ -703,13 +707,21 @@ public class MailboxApiTest extends BrambleTestCase {
|
||||
assertEquals("GET", request8.getMethod());
|
||||
assertToken(request8, token);
|
||||
|
||||
// 500 internal server error
|
||||
assertThrows(ApiException.class,
|
||||
() -> api.getFiles(properties, contactInboxId));
|
||||
// 404 not found
|
||||
assertThrows(TolerableFailureException.class, () ->
|
||||
api.getFiles(properties, contactInboxId));
|
||||
RecordedRequest request9 = server.takeRequest();
|
||||
assertEquals("/files/" + contactInboxId, request9.getPath());
|
||||
assertEquals("GET", request9.getMethod());
|
||||
assertToken(request9, token);
|
||||
|
||||
// 500 internal server error
|
||||
assertThrows(ApiException.class,
|
||||
() -> api.getFiles(properties, contactInboxId));
|
||||
RecordedRequest request10 = server.takeRequest();
|
||||
assertEquals("/files/" + contactInboxId, request10.getPath());
|
||||
assertEquals("GET", request10.getMethod());
|
||||
assertToken(request10, token);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.api.Cancellable;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFileId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFolderId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxProperties;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.MailboxFile;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.TolerableFailureException;
|
||||
import org.briarproject.bramble.test.BrambleMockTestCase;
|
||||
import org.briarproject.bramble.test.CaptureArgumentAction;
|
||||
import org.jmock.Expectations;
|
||||
import org.jmock.lib.action.DoAllAction;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.briarproject.bramble.test.TestUtils.deleteTestDirectory;
|
||||
import static org.briarproject.bramble.test.TestUtils.getRandomId;
|
||||
import static org.briarproject.bramble.test.TestUtils.getTestDirectory;
|
||||
|
||||
abstract class MailboxDownloadWorkerTest<W extends MailboxDownloadWorker>
|
||||
extends BrambleMockTestCase {
|
||||
|
||||
final ConnectivityChecker connectivityChecker =
|
||||
context.mock(ConnectivityChecker.class);
|
||||
final TorReachabilityMonitor torReachabilityMonitor =
|
||||
context.mock(TorReachabilityMonitor.class);
|
||||
final MailboxApiCaller mailboxApiCaller =
|
||||
context.mock(MailboxApiCaller.class);
|
||||
final MailboxApi mailboxApi = context.mock(MailboxApi.class);
|
||||
final MailboxFileManager mailboxFileManager =
|
||||
context.mock(MailboxFileManager.class);
|
||||
private final Cancellable apiCall = context.mock(Cancellable.class);
|
||||
|
||||
private final long now = System.currentTimeMillis();
|
||||
final MailboxFile file1 =
|
||||
new MailboxFile(new MailboxFileId(getRandomId()), now - 1);
|
||||
final MailboxFile file2 =
|
||||
new MailboxFile(new MailboxFileId(getRandomId()), now);
|
||||
final List<MailboxFile> files = asList(file1, file2);
|
||||
|
||||
private File testDir, tempFile;
|
||||
MailboxProperties mailboxProperties;
|
||||
W worker;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
testDir = getTestDirectory();
|
||||
tempFile = new File(testDir, "temp");
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
deleteTestDirectory(testDir);
|
||||
}
|
||||
|
||||
|
||||
void expectStartConnectivityCheck() {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(connectivityChecker).checkConnectivity(
|
||||
with(mailboxProperties), with(worker));
|
||||
}});
|
||||
}
|
||||
|
||||
void expectStartTask(AtomicReference<ApiCall> task) {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxApiCaller).retryWithBackoff(with(any(ApiCall.class)));
|
||||
will(new DoAllAction(
|
||||
new CaptureArgumentAction<>(task, ApiCall.class, 0),
|
||||
returnValue(apiCall)
|
||||
));
|
||||
}});
|
||||
}
|
||||
|
||||
void expectCheckForFoldersWithAvailableFiles(
|
||||
List<MailboxFolderId> folderIds) throws Exception {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxApi).getFolders(mailboxProperties);
|
||||
will(returnValue(folderIds));
|
||||
}});
|
||||
}
|
||||
|
||||
void expectCheckForFiles(MailboxFolderId folderId,
|
||||
List<MailboxFile> files) throws Exception {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxApi).getFiles(mailboxProperties, folderId);
|
||||
will(returnValue(files));
|
||||
}});
|
||||
}
|
||||
|
||||
void expectDownloadFile(MailboxFolderId folderId,
|
||||
MailboxFile file)
|
||||
throws Exception {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxFileManager).createTempFileForDownload();
|
||||
will(returnValue(tempFile));
|
||||
oneOf(mailboxApi).getFile(mailboxProperties, folderId, file.name,
|
||||
tempFile);
|
||||
oneOf(mailboxFileManager).handleDownloadedFile(tempFile);
|
||||
}});
|
||||
}
|
||||
|
||||
void expectDeleteFile(MailboxFolderId folderId, MailboxFile file,
|
||||
boolean tolerableFailure) throws Exception {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(mailboxApi).deleteFile(mailboxProperties, folderId,
|
||||
file.name);
|
||||
if (tolerableFailure) {
|
||||
will(throwException(new TolerableFailureException()));
|
||||
}
|
||||
}});
|
||||
}
|
||||
|
||||
void expectAddReachabilityObserver() {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(torReachabilityMonitor).addOneShotObserver(worker);
|
||||
}});
|
||||
}
|
||||
|
||||
void expectRemoveObservers() {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(connectivityChecker).removeObserver(worker);
|
||||
oneOf(torReachabilityMonitor).removeObserver(worker);
|
||||
}});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.BrambleCoreModule;
|
||||
import org.briarproject.bramble.test.BrambleCoreIntegrationTestModule;
|
||||
import org.briarproject.bramble.test.BrambleIntegrationTestComponent;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import dagger.Component;
|
||||
|
||||
@Singleton
|
||||
@Component(modules = {
|
||||
BrambleCoreIntegrationTestModule.class,
|
||||
BrambleCoreModule.class
|
||||
})
|
||||
interface MailboxIntegrationTestComponent extends
|
||||
BrambleIntegrationTestComponent {
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.BrambleCoreEagerSingletons;
|
||||
import org.briarproject.bramble.api.WeakSingletonProvider;
|
||||
import org.briarproject.bramble.api.mailbox.InvalidMailboxIdException;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxAuthToken;
|
||||
import org.briarproject.bramble.io.IoModule;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.inject.Singleton;
|
||||
import javax.net.SocketFactory;
|
||||
|
||||
import dagger.Module;
|
||||
import dagger.Provides;
|
||||
import okhttp3.OkHttpClient;
|
||||
|
||||
import static java.util.concurrent.TimeUnit.MILLISECONDS;
|
||||
|
||||
class MailboxIntegrationTestUtils {
|
||||
|
||||
static final String URL_BASE = "http://127.0.0.1:8000";
|
||||
static final MailboxAuthToken SETUP_TOKEN;
|
||||
|
||||
static {
|
||||
try {
|
||||
SETUP_TOKEN = MailboxAuthToken.fromString(
|
||||
"54686973206973206120736574757020746f6b656e20666f722042726961722e");
|
||||
} catch (InvalidMailboxIdException e) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
}
|
||||
|
||||
static WeakSingletonProvider<OkHttpClient> createHttpClientProvider() {
|
||||
OkHttpClient client = new OkHttpClient.Builder()
|
||||
.socketFactory(SocketFactory.getDefault())
|
||||
.connectTimeout(60_000, MILLISECONDS)
|
||||
.build();
|
||||
return new WeakSingletonProvider<OkHttpClient>() {
|
||||
@Override
|
||||
@Nonnull
|
||||
public OkHttpClient createInstance() {
|
||||
return client;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
static MailboxApi createMailboxApi() {
|
||||
return new MailboxApiImpl(createHttpClientProvider(), onion -> onion);
|
||||
}
|
||||
|
||||
static MailboxIntegrationTestComponent createTestComponent() {
|
||||
MailboxIntegrationTestComponent component =
|
||||
DaggerMailboxIntegrationTestComponent
|
||||
.builder()
|
||||
.ioModule(new TestIoModule())
|
||||
.mailboxModule(new TestMailboxModule())
|
||||
.build();
|
||||
BrambleCoreEagerSingletons.Helper.injectEagerSingletons(component);
|
||||
return component;
|
||||
}
|
||||
|
||||
@Module
|
||||
static class TestIoModule extends IoModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
WeakSingletonProvider<OkHttpClient> provideOkHttpClientProvider() {
|
||||
return createHttpClientProvider();
|
||||
}
|
||||
}
|
||||
|
||||
@Module
|
||||
static class TestMailboxModule extends MailboxModule {
|
||||
|
||||
@Provides
|
||||
UrlConverter provideUrlConverter() {
|
||||
return onion -> onion;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,7 +55,6 @@ public class MailboxPairingTaskImplTest extends BrambleMockTestCase {
|
||||
|
||||
private final String onion = getRandomString(56);
|
||||
private final byte[] onionBytes = getRandomBytes(32);
|
||||
private final String baseUrl = "http://" + onion + ".onion"; // TODO
|
||||
private final MailboxAuthToken setupToken =
|
||||
new MailboxAuthToken(getRandomId());
|
||||
private final MailboxAuthToken ownerToken =
|
||||
@@ -63,9 +62,9 @@ public class MailboxPairingTaskImplTest extends BrambleMockTestCase {
|
||||
private final String validPayload = getValidPayload();
|
||||
private final long time = System.currentTimeMillis();
|
||||
private final MailboxProperties setupProperties = new MailboxProperties(
|
||||
baseUrl, setupToken, new ArrayList<>());
|
||||
onion, setupToken, new ArrayList<>());
|
||||
private final MailboxProperties ownerProperties = new MailboxProperties(
|
||||
baseUrl, ownerToken, new ArrayList<>());
|
||||
onion, ownerToken, new ArrayList<>());
|
||||
|
||||
@Test
|
||||
public void testInitialQrCodeReceivedState() {
|
||||
@@ -207,7 +206,7 @@ public class MailboxPairingTaskImplTest extends BrambleMockTestCase {
|
||||
private PredicateMatcher<MailboxProperties> matches(MailboxProperties p2) {
|
||||
return new PredicateMatcher<>(MailboxProperties.class, p1 ->
|
||||
p1.getAuthToken().equals(p2.getAuthToken()) &&
|
||||
p1.getBaseUrl().equals(p2.getBaseUrl()) &&
|
||||
p1.getOnion().equals(p2.getOnion()) &&
|
||||
p1.isOwner() == p2.isOwner() &&
|
||||
p1.getServerSupports().equals(p2.getServerSupports()));
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ public class MailboxSettingsManagerImplTest extends BrambleMockTestCase {
|
||||
|
||||
MailboxProperties properties = manager.getOwnMailboxProperties(txn);
|
||||
assertNotNull(properties);
|
||||
assertEquals(onion, properties.getBaseUrl());
|
||||
assertEquals(onion, properties.getOnion());
|
||||
assertEquals(token, properties.getAuthToken());
|
||||
assertEquals(serverSupports, properties.getServerSupports());
|
||||
assertTrue(properties.isOwner());
|
||||
|
||||
@@ -109,7 +109,7 @@ public class MailboxUpdateManagerImplTest extends BrambleMockTestCase {
|
||||
updateNoMailbox = new MailboxUpdate(someClientSupportsList);
|
||||
|
||||
updateProps = getMailboxProperties(false, someServerSupportsList);
|
||||
ownProps = new MailboxProperties(updateProps.getBaseUrl(),
|
||||
ownProps = new MailboxProperties(updateProps.getOnion(),
|
||||
updateProps.getAuthToken(), someServerSupportsList);
|
||||
updateWithMailbox = new MailboxUpdateWithMailbox(someClientSupportsList,
|
||||
updateProps);
|
||||
@@ -170,7 +170,7 @@ public class MailboxUpdateManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
expectStoreMessage(txn, contactGroup.getId(), 1, someClientSupports,
|
||||
emptyServerSupports, emptyPropsDict, true);
|
||||
emptyServerSupports, emptyPropsDict);
|
||||
|
||||
oneOf(clientHelper).mergeGroupMetadata(txn, localGroup.getId(),
|
||||
sentDict);
|
||||
@@ -225,7 +225,7 @@ public class MailboxUpdateManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
expectStoreMessage(txn, contactGroup.getId(), 1, someClientSupports,
|
||||
someServerSupports, propsDict, true);
|
||||
someServerSupports, propsDict);
|
||||
|
||||
oneOf(clientHelper).mergeGroupMetadata(txn, localGroup.getId(),
|
||||
sentDict);
|
||||
@@ -276,7 +276,7 @@ public class MailboxUpdateManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(emptyMessageMetadata));
|
||||
expectStoreMessage(txn, contactGroup.getId(), 1, someClientSupports,
|
||||
emptyServerSupports, emptyPropsDict, true);
|
||||
emptyServerSupports, emptyPropsDict);
|
||||
|
||||
oneOf(clientHelper).mergeGroupMetadata(txn, localGroup.getId(),
|
||||
sentDict);
|
||||
@@ -341,7 +341,7 @@ public class MailboxUpdateManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(emptyMessageMetadata));
|
||||
expectStoreMessage(txn, contactGroup.getId(), 1, someClientSupports,
|
||||
emptyServerSupports, emptyPropsDict, true);
|
||||
emptyServerSupports, emptyPropsDict);
|
||||
|
||||
oneOf(clientHelper).mergeGroupMetadata(txn, localGroup.getId(),
|
||||
sentDict);
|
||||
@@ -400,7 +400,7 @@ public class MailboxUpdateManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
expectStoreMessage(txn, contactGroup.getId(), 2,
|
||||
newerClientSupports, someServerSupports, propsDict, true);
|
||||
newerClientSupports, someServerSupports, propsDict);
|
||||
oneOf(db).removeMessage(txn, messageId);
|
||||
|
||||
oneOf(clientHelper).mergeGroupMetadata(txn, localGroup.getId(),
|
||||
@@ -441,7 +441,7 @@ public class MailboxUpdateManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
expectStoreMessage(txn, contactGroup.getId(), 1, someClientSupports,
|
||||
emptyServerSupports, emptyPropsDict, true);
|
||||
emptyServerSupports, emptyPropsDict);
|
||||
}});
|
||||
|
||||
MailboxUpdateManagerImpl t = createInstance(someClientSupportsList);
|
||||
@@ -484,7 +484,7 @@ public class MailboxUpdateManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
expectStoreMessage(txn, contactGroup.getId(), 1, someClientSupports,
|
||||
someServerSupports, propsDict, true);
|
||||
someServerSupports, propsDict);
|
||||
}});
|
||||
|
||||
MailboxUpdateManagerImpl t = createInstance(someClientSupportsList);
|
||||
@@ -674,7 +674,7 @@ public class MailboxUpdateManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
expectStoreMessage(txn, contactGroup.getId(), 2, someClientSupports,
|
||||
someServerSupports, propsDict, true);
|
||||
someServerSupports, propsDict);
|
||||
oneOf(db).removeMessage(txn, latestId);
|
||||
}});
|
||||
|
||||
@@ -712,7 +712,7 @@ public class MailboxUpdateManagerImplTest extends BrambleMockTestCase {
|
||||
contactGroup.getId());
|
||||
will(returnValue(messageMetadata));
|
||||
expectStoreMessage(txn, contactGroup.getId(), 2, someClientSupports,
|
||||
emptyServerSupports, emptyPropsDict, true);
|
||||
emptyServerSupports, emptyPropsDict);
|
||||
oneOf(db).removeMessage(txn, latestId);
|
||||
}});
|
||||
|
||||
@@ -890,15 +890,14 @@ public class MailboxUpdateManagerImplTest extends BrambleMockTestCase {
|
||||
|
||||
private void expectStoreMessage(Transaction txn, GroupId g,
|
||||
long version, BdfList clientSupports, BdfList serverSupports,
|
||||
BdfDictionary properties, boolean local)
|
||||
throws Exception {
|
||||
BdfDictionary properties) throws Exception {
|
||||
BdfList body = BdfList.of(version, clientSupports, serverSupports,
|
||||
properties);
|
||||
Message message = getMessage(g);
|
||||
long timestamp = message.getTimestamp();
|
||||
BdfDictionary meta = BdfDictionary.of(
|
||||
new BdfEntry(MSG_KEY_VERSION, version),
|
||||
new BdfEntry(MSG_KEY_LOCAL, local)
|
||||
new BdfEntry(MSG_KEY_LOCAL, true)
|
||||
);
|
||||
|
||||
context.checking(new Expectations() {{
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFolderId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxProperties;
|
||||
import org.briarproject.bramble.test.BrambleMockTestCase;
|
||||
import org.jmock.Expectations;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.briarproject.bramble.api.mailbox.MailboxConstants.CLIENT_SUPPORTS;
|
||||
import static org.briarproject.bramble.test.TestUtils.getContactId;
|
||||
import static org.briarproject.bramble.test.TestUtils.getMailboxProperties;
|
||||
import static org.briarproject.bramble.test.TestUtils.getRandomId;
|
||||
|
||||
public class OwnMailboxClientTest extends BrambleMockTestCase {
|
||||
|
||||
private final MailboxWorkerFactory workerFactory =
|
||||
context.mock(MailboxWorkerFactory.class);
|
||||
private final ConnectivityChecker connectivityChecker =
|
||||
context.mock(ConnectivityChecker.class);
|
||||
private final TorReachabilityMonitor reachabilityMonitor =
|
||||
context.mock(TorReachabilityMonitor.class);
|
||||
private final MailboxWorker contactListWorker =
|
||||
context.mock(MailboxWorker.class, "contactListWorker");
|
||||
private final MailboxWorker uploadWorker1 =
|
||||
context.mock(MailboxWorker.class, "uploadWorker1");
|
||||
private final MailboxWorker uploadWorker2 =
|
||||
context.mock(MailboxWorker.class, "uploadWorker2");
|
||||
private final MailboxWorker downloadWorker =
|
||||
context.mock(MailboxWorker.class, "downloadWorker");
|
||||
|
||||
private final MailboxProperties properties =
|
||||
getMailboxProperties(true, CLIENT_SUPPORTS);
|
||||
private final MailboxFolderId folderId = new MailboxFolderId(getRandomId());
|
||||
private final ContactId contactId1 = getContactId();
|
||||
private final ContactId contactId2 = getContactId();
|
||||
|
||||
private final OwnMailboxClient client;
|
||||
|
||||
public OwnMailboxClientTest() {
|
||||
expectCreateContactListWorker();
|
||||
client = new OwnMailboxClient(workerFactory, connectivityChecker,
|
||||
reachabilityMonitor, properties);
|
||||
context.assertIsSatisfied();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartAndDestroyWithNoContactsAssigned() {
|
||||
expectStartWorker(contactListWorker);
|
||||
client.start();
|
||||
|
||||
expectDestroyWorker(contactListWorker);
|
||||
client.destroy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAssignContactForUploadAndDestroyClient() {
|
||||
expectStartWorker(contactListWorker);
|
||||
client.start();
|
||||
|
||||
// When the contact is assigned, the worker should be created and
|
||||
// started
|
||||
expectCreateUploadWorker(contactId1, uploadWorker1);
|
||||
expectStartWorker(uploadWorker1);
|
||||
client.assignContactForUpload(contactId1, properties, folderId);
|
||||
|
||||
// When the client is destroyed, the worker should be destroyed
|
||||
expectDestroyWorker(uploadWorker1);
|
||||
expectDestroyWorker(contactListWorker);
|
||||
client.destroy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAssignAndDeassignContactForUpload() {
|
||||
expectStartWorker(contactListWorker);
|
||||
client.start();
|
||||
|
||||
// When the contact is assigned, the worker should be created and
|
||||
// started
|
||||
expectCreateUploadWorker(contactId1, uploadWorker1);
|
||||
expectStartWorker(uploadWorker1);
|
||||
client.assignContactForUpload(contactId1, properties, folderId);
|
||||
|
||||
// When the contact is deassigned, the worker should be destroyed
|
||||
expectDestroyWorker(uploadWorker1);
|
||||
client.deassignContactForUpload(contactId1);
|
||||
context.assertIsSatisfied();
|
||||
|
||||
expectDestroyWorker(contactListWorker);
|
||||
client.destroy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAssignAndDeassignTwoContactsForUpload() {
|
||||
expectStartWorker(contactListWorker);
|
||||
client.start();
|
||||
|
||||
// When the first contact is assigned, the first worker should be
|
||||
// created and started
|
||||
expectCreateUploadWorker(contactId1, uploadWorker1);
|
||||
expectStartWorker(uploadWorker1);
|
||||
client.assignContactForUpload(contactId1, properties, folderId);
|
||||
|
||||
// When the second contact is assigned, the second worker should be
|
||||
// created and started
|
||||
expectCreateUploadWorker(contactId2, uploadWorker2);
|
||||
expectStartWorker(uploadWorker2);
|
||||
client.assignContactForUpload(contactId2, properties, folderId);
|
||||
|
||||
// When the second contact is deassigned, the second worker should be
|
||||
// destroyed
|
||||
expectDestroyWorker(uploadWorker2);
|
||||
client.deassignContactForUpload(contactId2);
|
||||
context.assertIsSatisfied();
|
||||
|
||||
// When the first contact is deassigned, the first worker should be
|
||||
// destroyed
|
||||
expectDestroyWorker(uploadWorker1);
|
||||
client.deassignContactForUpload(contactId1);
|
||||
context.assertIsSatisfied();
|
||||
|
||||
expectDestroyWorker(contactListWorker);
|
||||
client.destroy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAssignContactForDownloadAndDestroyClient() {
|
||||
expectStartWorker(contactListWorker);
|
||||
client.start();
|
||||
|
||||
// When the contact is assigned, the worker should be created and
|
||||
// started
|
||||
expectCreateDownloadWorker();
|
||||
expectStartWorker(downloadWorker);
|
||||
client.assignContactForDownload(contactId1, properties, folderId);
|
||||
|
||||
// When the client is destroyed, the worker should be destroyed
|
||||
expectDestroyWorker(downloadWorker);
|
||||
expectDestroyWorker(contactListWorker);
|
||||
client.destroy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAssignAndDeassignTwoContactsForDownload() {
|
||||
expectStartWorker(contactListWorker);
|
||||
client.start();
|
||||
|
||||
// When the first contact is assigned, the worker should be created and
|
||||
// started
|
||||
expectCreateDownloadWorker();
|
||||
expectStartWorker(downloadWorker);
|
||||
client.assignContactForDownload(contactId1, properties, folderId);
|
||||
|
||||
// When the second contact is assigned, nothing should happen to the
|
||||
// worker
|
||||
client.assignContactForDownload(contactId2, properties, folderId);
|
||||
|
||||
// When the first contact is deassigned, nothing should happen to the
|
||||
// worker
|
||||
client.deassignContactForDownload(contactId1);
|
||||
|
||||
// When the second contact is deassigned, the worker should be
|
||||
// destroyed
|
||||
expectDestroyWorker(downloadWorker);
|
||||
client.deassignContactForDownload(contactId2);
|
||||
context.assertIsSatisfied();
|
||||
|
||||
expectDestroyWorker(contactListWorker);
|
||||
client.destroy();
|
||||
}
|
||||
|
||||
private void expectCreateContactListWorker() {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(workerFactory).createContactListWorkerForOwnMailbox(
|
||||
connectivityChecker, properties);
|
||||
will(returnValue(contactListWorker));
|
||||
}});
|
||||
}
|
||||
|
||||
private void expectCreateUploadWorker(ContactId contactId,
|
||||
MailboxWorker worker) {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(workerFactory).createUploadWorker(connectivityChecker,
|
||||
properties, folderId, contactId);
|
||||
will(returnValue(worker));
|
||||
}});
|
||||
}
|
||||
|
||||
private void expectCreateDownloadWorker() {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(workerFactory).createDownloadWorkerForOwnMailbox(
|
||||
connectivityChecker, reachabilityMonitor, properties);
|
||||
will(returnValue(downloadWorker));
|
||||
}});
|
||||
}
|
||||
|
||||
private void expectStartWorker(MailboxWorker worker) {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(worker).start();
|
||||
}});
|
||||
}
|
||||
|
||||
private void expectDestroyWorker(MailboxWorker worker) {
|
||||
context.checking(new Expectations() {{
|
||||
oneOf(worker).destroy();
|
||||
}});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.test.BrambleTestCase;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.briarproject.bramble.mailbox.MailboxIntegrationTestUtils.createTestComponent;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class OwnMailboxContactListWorkerIntegrationTest
|
||||
extends BrambleTestCase {
|
||||
|
||||
private MailboxIntegrationTestComponent component;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
component = createTestComponent();
|
||||
}
|
||||
|
||||
// Just test that we can build the component. TODO: Write actual tests
|
||||
@Test
|
||||
public void testBuild() {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package org.briarproject.bramble.mailbox;
|
||||
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFileId;
|
||||
import org.briarproject.bramble.api.mailbox.MailboxFolderId;
|
||||
import org.briarproject.bramble.mailbox.MailboxApi.MailboxFile;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.Collections.emptyList;
|
||||
import static org.briarproject.bramble.api.mailbox.MailboxConstants.CLIENT_SUPPORTS;
|
||||
import static org.briarproject.bramble.mailbox.MailboxDownloadWorker.FolderFile;
|
||||
import static org.briarproject.bramble.mailbox.OwnMailboxDownloadWorker.MAX_ROUND_ROBIN_FILES;
|
||||
import static org.briarproject.bramble.test.TestUtils.getMailboxProperties;
|
||||
import static org.briarproject.bramble.test.TestUtils.getRandomId;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class OwnMailboxDownloadWorkerTest
|
||||
extends MailboxDownloadWorkerTest<OwnMailboxDownloadWorker> {
|
||||
|
||||
private final MailboxFolderId folderId1 =
|
||||
new MailboxFolderId(getRandomId());
|
||||
private final MailboxFolderId folderId2 =
|
||||
new MailboxFolderId(getRandomId());
|
||||
private final List<MailboxFolderId> folderIds =
|
||||
asList(folderId1, folderId2);
|
||||
|
||||
public OwnMailboxDownloadWorkerTest() {
|
||||
mailboxProperties = getMailboxProperties(true, CLIENT_SUPPORTS);
|
||||
worker = new OwnMailboxDownloadWorker(connectivityChecker,
|
||||
torReachabilityMonitor, mailboxApiCaller, mailboxApi,
|
||||
mailboxFileManager, mailboxProperties);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setUp() {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testChecksConnectivityWhenStartedAndRemovesObserverWhenDestroyed() {
|
||||
// When the worker is started it should start a connectivity check
|
||||
expectStartConnectivityCheck();
|
||||
worker.start();
|
||||
|
||||
// When the worker is destroyed it should remove the connectivity
|
||||
// and reachability observers
|
||||
expectRemoveObservers();
|
||||
worker.destroy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testChecksForFilesWhenConnectivityCheckSucceeds()
|
||||
throws Exception {
|
||||
// When the worker is started it should start a connectivity check
|
||||
expectStartConnectivityCheck();
|
||||
worker.start();
|
||||
|
||||
// When the connectivity check succeeds, a list-folders task should be
|
||||
// started for the first download cycle
|
||||
AtomicReference<ApiCall> listFoldersTask = new AtomicReference<>();
|
||||
expectStartTask(listFoldersTask);
|
||||
worker.onConnectivityCheckSucceeded();
|
||||
|
||||
// When the list-folders tasks runs and finds no folders with files
|
||||
// to download, it should add a Tor reachability observer
|
||||
expectCheckForFoldersWithAvailableFiles(emptyList());
|
||||
expectAddReachabilityObserver();
|
||||
assertFalse(listFoldersTask.get().callApi());
|
||||
|
||||
// When the reachability observer is called, a list-folders task should
|
||||
// be started for the second download cycle
|
||||
expectStartTask(listFoldersTask);
|
||||
worker.onTorReachable();
|
||||
|
||||
// When the list-folders tasks runs and finds no folders with files
|
||||
// to download, it should finish the second download cycle
|
||||
expectCheckForFoldersWithAvailableFiles(emptyList());
|
||||
assertFalse(listFoldersTask.get().callApi());
|
||||
|
||||
// When the worker is destroyed it should remove the connectivity
|
||||
// and reachability observers
|
||||
expectRemoveObservers();
|
||||
worker.destroy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDownloadsFilesWhenConnectivityCheckSucceeds()
|
||||
throws Exception {
|
||||
// When the worker is started it should start a connectivity check
|
||||
expectStartConnectivityCheck();
|
||||
worker.start();
|
||||
|
||||
// When the connectivity check succeeds, a list-folders task should be
|
||||
// started for the first download cycle
|
||||
AtomicReference<ApiCall> listFoldersTask = new AtomicReference<>();
|
||||
expectStartTask(listFoldersTask);
|
||||
worker.onConnectivityCheckSucceeded();
|
||||
|
||||
// When the list-folders tasks runs and finds some folders with files
|
||||
// to download, it should start a list-files task for the first folder
|
||||
AtomicReference<ApiCall> listFilesTask = new AtomicReference<>();
|
||||
expectCheckForFoldersWithAvailableFiles(folderIds);
|
||||
expectStartTask(listFilesTask);
|
||||
assertFalse(listFoldersTask.get().callApi());
|
||||
|
||||
// When the first list-files task runs and finds no files to download,
|
||||
// it should start a second list-files task for the next folder
|
||||
expectCheckForFiles(folderId1, emptyList());
|
||||
expectStartTask(listFilesTask);
|
||||
assertFalse(listFilesTask.get().callApi());
|
||||
|
||||
// When the second list-files task runs and finds some files to
|
||||
// download, it should create the round-robin queue and start a
|
||||
// download task for the first file
|
||||
AtomicReference<ApiCall> downloadTask = new AtomicReference<>();
|
||||
expectCheckForFiles(folderId2, files);
|
||||
expectStartTask(downloadTask);
|
||||
assertFalse(listFilesTask.get().callApi());
|
||||
|
||||
// When the first download task runs it should download the file to the
|
||||
// location provided by the file manager and start a delete task
|
||||
AtomicReference<ApiCall> deleteTask = new AtomicReference<>();
|
||||
expectDownloadFile(folderId2, file1);
|
||||
expectStartTask(deleteTask);
|
||||
assertFalse(downloadTask.get().callApi());
|
||||
|
||||
// When the first delete task runs it should delete the file, ignore
|
||||
// the tolerable failure, and start a download task for the next file
|
||||
expectDeleteFile(folderId2, file1, true); // Delete fails tolerably
|
||||
expectStartTask(downloadTask);
|
||||
assertFalse(deleteTask.get().callApi());
|
||||
|
||||
// When the second download task runs it should download the file to
|
||||
// the location provided by the file manager and start a delete task
|
||||
expectDownloadFile(folderId2, file2);
|
||||
expectStartTask(deleteTask);
|
||||
assertFalse(downloadTask.get().callApi());
|
||||
|
||||
// When the second delete task runs it should delete the file and
|
||||
// start a list-inbox task to check for files that may have arrived
|
||||
// since the first download cycle started
|
||||
expectDeleteFile(folderId2, file2, false); // Delete succeeds
|
||||
expectStartTask(listFoldersTask);
|
||||
assertFalse(deleteTask.get().callApi());
|
||||
|
||||
// When the list-inbox tasks runs and finds no more files to download,
|
||||
// it should add a Tor reachability observer
|
||||
expectCheckForFoldersWithAvailableFiles(emptyList());
|
||||
expectAddReachabilityObserver();
|
||||
assertFalse(listFoldersTask.get().callApi());
|
||||
|
||||
// When the reachability observer is called, a list-inbox task should
|
||||
// be started for the second download cycle
|
||||
expectStartTask(listFoldersTask);
|
||||
worker.onTorReachable();
|
||||
|
||||
// When the list-inbox tasks runs and finds no more files to download,
|
||||
// it should finish the second download cycle
|
||||
expectCheckForFoldersWithAvailableFiles(emptyList());
|
||||
assertFalse(listFoldersTask.get().callApi());
|
||||
|
||||
// When the worker is destroyed it should remove the connectivity
|
||||
// and reachability observers
|
||||
expectRemoveObservers();
|
||||
worker.destroy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRoundRobinQueueVisitsAllFolders() {
|
||||
// Ten folders with two files each
|
||||
Map<MailboxFolderId, Queue<MailboxFile>> available =
|
||||
createAvailableFiles(10, 2);
|
||||
Queue<FolderFile> queue = worker.createRoundRobinQueue(available);
|
||||
// Check that all files were queued
|
||||
for (MailboxFolderId folderId : available.keySet()) {
|
||||
assertEquals(2, countFilesWithFolderId(queue, folderId));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSizeOfRoundRobinQueueIsLimited() {
|
||||
// Two folders with MAX_ROUND_ROBIN_FILES each
|
||||
Map<MailboxFolderId, Queue<MailboxFile>> available =
|
||||
createAvailableFiles(2, MAX_ROUND_ROBIN_FILES);
|
||||
Queue<FolderFile> queue = worker.createRoundRobinQueue(available);
|
||||
// Check that half the files in each folder were queued
|
||||
for (MailboxFolderId folderId : available.keySet()) {
|
||||
assertEquals(MAX_ROUND_ROBIN_FILES / 2,
|
||||
countFilesWithFolderId(queue, folderId));
|
||||
}
|
||||
}
|
||||
|
||||
private Map<MailboxFolderId, Queue<MailboxFile>> createAvailableFiles(
|
||||
int numFolders, int numFiles) {
|
||||
Map<MailboxFolderId, Queue<MailboxFile>> available = new HashMap<>();
|
||||
List<MailboxFolderId> folderIds = createFolderIds(numFolders);
|
||||
for (MailboxFolderId folderId : folderIds) {
|
||||
available.put(folderId, createFiles(numFiles));
|
||||
}
|
||||
return available;
|
||||
}
|
||||
|
||||
private List<MailboxFolderId> createFolderIds(int size) {
|
||||
List<MailboxFolderId> folderIds = new ArrayList<>(size);
|
||||
for (int i = 0; i < size; i++) {
|
||||
folderIds.add(new MailboxFolderId(getRandomId()));
|
||||
}
|
||||
return folderIds;
|
||||
}
|
||||
|
||||
private Queue<MailboxFile> createFiles(int size) {
|
||||
Queue<MailboxFile> files = new LinkedList<>();
|
||||
for (int i = 0; i < size; i++) {
|
||||
files.add(new MailboxFile(new MailboxFileId(getRandomId()), i));
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
private int countFilesWithFolderId(Queue<FolderFile> queue,
|
||||
MailboxFolderId folderId) {
|
||||
int count = 0;
|
||||
for (FolderFile file : queue) {
|
||||
if (file.folderId.equals(folderId)) count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.briarproject.bramble.util;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.test.BrambleTestCase;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -11,7 +12,7 @@ import static org.junit.Assert.fail;
|
||||
public class ByteUtilsTest extends BrambleTestCase {
|
||||
|
||||
@Test
|
||||
public void testReadUint16() {
|
||||
public void testReadUint16() throws FormatException {
|
||||
byte[] b = StringUtils.fromHexString("00000000");
|
||||
assertEquals(0, ByteUtils.readUint16(b, 1));
|
||||
b = StringUtils.fromHexString("00000100");
|
||||
@@ -33,7 +34,7 @@ public class ByteUtilsTest extends BrambleTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReadUint32() {
|
||||
public void testReadUint32() throws FormatException {
|
||||
byte[] b = StringUtils.fromHexString("000000000000");
|
||||
assertEquals(0, ByteUtils.readUint32(b, 1));
|
||||
b = StringUtils.fromHexString("000000000100");
|
||||
@@ -55,7 +56,7 @@ public class ByteUtilsTest extends BrambleTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReadUint64() {
|
||||
public void testReadUint64() throws FormatException {
|
||||
byte[] b = StringUtils.fromHexString("00000000000000000000");
|
||||
assertEquals(0L, ByteUtils.readUint64(b, 1));
|
||||
b = StringUtils.fromHexString("00000000000000000100");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.briarproject.bramble.util;
|
||||
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.test.BrambleTestCase;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -24,18 +25,19 @@ public class StringUtilsTest extends BrambleTestCase {
|
||||
assertEquals("", StringUtils.toHexString(new byte[0]));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testFromHexStringRejectsInvalidLength() {
|
||||
@Test(expected = FormatException.class)
|
||||
public void testFromHexStringRejectsInvalidLength() throws FormatException {
|
||||
StringUtils.fromHexString("12345");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testFromHexStringRejectsInvalidCharacter() {
|
||||
@Test(expected = FormatException.class)
|
||||
public void testFromHexStringRejectsInvalidCharacter()
|
||||
throws FormatException {
|
||||
StringUtils.fromHexString("ABCDEFGH");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFromHexStringUppercase() {
|
||||
public void testFromHexStringUppercase() throws FormatException {
|
||||
String s = "000102037F800A0B0C0D0EFF";
|
||||
byte[] expected = new byte[] {
|
||||
0x00, 0x01, 0x02, 0x03, 0x7F, (byte) 0x80,
|
||||
@@ -45,7 +47,7 @@ public class StringUtilsTest extends BrambleTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFromHexStringLowercase() {
|
||||
public void testFromHexStringLowercase() throws FormatException {
|
||||
String s = "000102037f800a0b0c0d0eff";
|
||||
byte[] expected = new byte[] {
|
||||
0x00, 0x01, 0x02, 0x03, 0x7F, (byte) 0x80,
|
||||
@@ -55,7 +57,7 @@ public class StringUtilsTest extends BrambleTestCase {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFromHexStringEmptyInput() {
|
||||
public void testFromHexStringEmptyInput() throws FormatException {
|
||||
assertArrayEquals(new byte[0], StringUtils.fromHexString(""));
|
||||
}
|
||||
|
||||
@@ -174,52 +176,52 @@ public class StringUtilsTest extends BrambleTestCase {
|
||||
assertEquals("", StringUtils.truncateUtf8("", 123));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testMacToBytesRejectsShortMac() {
|
||||
@Test(expected = FormatException.class)
|
||||
public void testMacToBytesRejectsShortMac() throws FormatException {
|
||||
StringUtils.macToBytes("00:00:00:00:00");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testMacToBytesRejectsLongMac() {
|
||||
@Test(expected = FormatException.class)
|
||||
public void testMacToBytesRejectsLongMac() throws FormatException {
|
||||
StringUtils.macToBytes("00:00:00:00:00:00:00");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testMacToBytesRejectsInvalidCharacter() {
|
||||
@Test(expected = FormatException.class)
|
||||
public void testMacToBytesRejectsInvalidCharacter() throws FormatException {
|
||||
StringUtils.macToBytes("00:00:00:00:00:0g");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testMacToBytesRejectsInvalidFormat() {
|
||||
@Test(expected = FormatException.class)
|
||||
public void testMacToBytesRejectsInvalidFormat() throws FormatException {
|
||||
StringUtils.macToBytes("0:000:00:00:00:00");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMacToBytesUpperCase() {
|
||||
public void testMacToBytesUpperCase() throws FormatException {
|
||||
byte[] expected = new byte[] {0x0A, 0x1B, 0x2C, 0x3D, 0x4E, 0x5F};
|
||||
String mac = "0A:1B:2C:3D:4E:5F";
|
||||
assertArrayEquals(expected, StringUtils.macToBytes(mac));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMacToBytesLowerCase() {
|
||||
public void testMacToBytesLowerCase() throws FormatException {
|
||||
byte[] expected = new byte[] {0x0A, 0x1B, 0x2C, 0x3D, 0x4E, 0x5F};
|
||||
String mac = "0a:1b:2c:3d:4e:5f";
|
||||
assertArrayEquals(expected, StringUtils.macToBytes(mac));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testMacToStringRejectsShortMac() {
|
||||
@Test(expected = FormatException.class)
|
||||
public void testMacToStringRejectsShortMac() throws FormatException {
|
||||
StringUtils.macToString(new byte[5]);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testMacToStringRejectsLongMac() {
|
||||
@Test(expected = FormatException.class)
|
||||
public void testMacToStringRejectsLongMac() throws FormatException {
|
||||
StringUtils.macToString(new byte[7]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMacToString() {
|
||||
public void testMacToString() throws FormatException {
|
||||
byte[] mac = new byte[] {0x0a, 0x1b, 0x2c, 0x3d, 0x4e, 0x5f};
|
||||
String expected = "0A:1B:2C:3D:4E:5F";
|
||||
assertEquals(expected, StringUtils.macToString(mac));
|
||||
|
||||
@@ -35,7 +35,7 @@ dependencyVerification {
|
||||
'org.apache-extras.beanshell:bsh:2.0b6:bsh-2.0b6.jar:a17955976070c0573235ee662f2794a78082758b61accffce8d3f8aedcd91047',
|
||||
'org.bitlet:weupnp:0.1.4:weupnp-0.1.4.jar:88df7e6504929d00bdb832863761385c68ab92af945b04f0770b126270a444fb',
|
||||
'org.bouncycastle:bcprov-jdk15to18:1.70:bcprov-jdk15to18-1.70.jar:7df4c54f29ce2dd616dc3b198ca4db3dfcc79e3cb397c084a0aff97b85c0bf38',
|
||||
'org.briarproject:jtorctl:0.4:jtorctl-0.4.jar:4e61f59dc9f3984438a7151c4df8d7c1f83d5fb3eb8c151acfc794a8fef85a36',
|
||||
'org.briarproject:jtorctl:0.5:jtorctl-0.5.jar:43f8c7d390169772b9a2c82ab806c8414c136a2a8636c555e22754bb7260793b',
|
||||
'org.checkerframework:checker-compat-qual:2.5.3:checker-compat-qual-2.5.3.jar:d76b9afea61c7c082908023f0cbc1427fab9abd2df915c8b8a3e7a509bccbc6d',
|
||||
'org.checkerframework:checker-qual:2.5.2:checker-qual-2.5.2.jar:64b02691c8b9d4e7700f8ee2e742dce7ea2c6e81e662b7522c9ee3bf568c040a',
|
||||
'org.codehaus.mojo.signature:java16:1.1:java16-1.1.signature:53799223a2c98dba2d0add810bed76315460df285c69e4f397ae6098f87dd619',
|
||||
|
||||
@@ -26,9 +26,10 @@ android {
|
||||
defaultConfig {
|
||||
minSdkVersion 16
|
||||
targetSdkVersion 30
|
||||
versionCode 10409
|
||||
versionName "1.4.9"
|
||||
versionCode 10410
|
||||
versionName "1.4.10"
|
||||
applicationId "org.briarproject.briar.android"
|
||||
buildConfigField "String", "TorVersion", "\"$tor_version\""
|
||||
|
||||
vectorDrawables.useSupportLibrary = true
|
||||
buildConfigField "String", "GitHash",
|
||||
|
||||
@@ -8,6 +8,7 @@ import android.os.StrictMode;
|
||||
import com.vanniktech.emoji.RecentEmoji;
|
||||
|
||||
import org.briarproject.bramble.api.FeatureFlags;
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.crypto.CryptoComponent;
|
||||
import org.briarproject.bramble.api.crypto.KeyStrengthener;
|
||||
import org.briarproject.bramble.api.crypto.PublicKey;
|
||||
@@ -242,7 +243,7 @@ public class AppModule {
|
||||
try {
|
||||
return crypto.getMessageKeyParser().parsePublicKey(
|
||||
StringUtils.fromHexString(DEV_PUBLIC_KEY_HEX));
|
||||
} catch (GeneralSecurityException e) {
|
||||
} catch (GeneralSecurityException | FormatException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,8 +156,11 @@ public class BriarService extends Service {
|
||||
if (result == SUCCESS) {
|
||||
started = true;
|
||||
} else if (result == ALREADY_RUNNING) {
|
||||
LOG.info("Already running");
|
||||
stopSelf();
|
||||
LOG.warning("Already running");
|
||||
// The core has outlived the original BriarService
|
||||
// instance. We don't know how to recover from this
|
||||
// unexpected state, so try to exit cleanly
|
||||
shutdownFromBackground();
|
||||
} else {
|
||||
if (LOG.isLoggable(WARNING))
|
||||
LOG.warning("Startup failed: " + result);
|
||||
|
||||
@@ -22,6 +22,7 @@ import android.widget.Toast;
|
||||
import com.google.android.material.snackbar.Snackbar;
|
||||
|
||||
import org.briarproject.bramble.api.FeatureFlags;
|
||||
import org.briarproject.bramble.api.FormatException;
|
||||
import org.briarproject.bramble.api.Pair;
|
||||
import org.briarproject.bramble.api.connection.ConnectionRegistry;
|
||||
import org.briarproject.bramble.api.contact.ContactId;
|
||||
@@ -519,8 +520,12 @@ public class ConversationActivity extends BriarActivity
|
||||
Selection<String> selection = tracker.getSelection();
|
||||
List<MessageId> messages = new ArrayList<>(selection.size());
|
||||
for (String str : selection) {
|
||||
MessageId id = new MessageId(fromHexString(str));
|
||||
messages.add(id);
|
||||
try {
|
||||
MessageId id = new MessageId(fromHexString(str));
|
||||
messages.add(id);
|
||||
} catch (FormatException e) {
|
||||
LOG.warning("Invalid message id");
|
||||
}
|
||||
}
|
||||
return messages;
|
||||
}
|
||||
|
||||
@@ -109,12 +109,18 @@ public class MailboxActivity extends BriarActivity {
|
||||
}
|
||||
|
||||
private void onShowDownload() {
|
||||
boolean needToShow = true;
|
||||
FragmentManager fm = getSupportFragmentManager();
|
||||
// if the fragment is already on the back stack, pop back to it
|
||||
// instead of adding it to the stack again
|
||||
if (fm.findFragmentByTag(SetupDownloadFragment.TAG) != null) {
|
||||
// if the fragment is already on the back stack, pop back to it
|
||||
// instead of adding it to the stack again
|
||||
fm.popBackStackImmediate(SetupDownloadFragment.TAG, 0);
|
||||
} else {
|
||||
// if the activity was previously destroyed, the fragment is still
|
||||
// found, but popping back to it won't work, so we need to handle
|
||||
// this case and show the fragment again anyway.
|
||||
needToShow =
|
||||
!fm.popBackStackImmediate(SetupDownloadFragment.TAG, 0);
|
||||
}
|
||||
if (needToShow) {
|
||||
showFragment(fm, new SetupDownloadFragment(),
|
||||
SetupDownloadFragment.TAG);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package org.briarproject.briar.android.settings;
|
||||
|
||||
import android.content.ActivityNotFoundException;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
|
||||
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
|
||||
import org.briarproject.briar.BuildConfig;
|
||||
import org.briarproject.briar.R;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.fragment.app.Fragment;
|
||||
|
||||
import static android.widget.Toast.LENGTH_LONG;
|
||||
import static java.util.logging.Level.WARNING;
|
||||
import static java.util.logging.Logger.getLogger;
|
||||
import static org.briarproject.bramble.util.LogUtils.logException;
|
||||
|
||||
@MethodsNotNullByDefault
|
||||
@ParametersNotNullByDefault
|
||||
public class AboutFragment extends Fragment {
|
||||
|
||||
final static String TAG = AboutFragment.class.getName();
|
||||
private static final Logger LOG = getLogger(TAG);
|
||||
|
||||
private TextView briarVersion;
|
||||
private TextView torVersion;
|
||||
private TextView briarWebsite;
|
||||
private TextView briarSourceCode;
|
||||
private TextView briarChangelog;
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public View onCreateView(@NonNull LayoutInflater inflater,
|
||||
@Nullable ViewGroup container,
|
||||
@Nullable Bundle savedInstanceState) {
|
||||
return inflater.inflate(R.layout.fragment_about, container,
|
||||
false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
requireActivity().setTitle(R.string.about_title);
|
||||
briarVersion = requireActivity().findViewById(R.id.BriarVersion);
|
||||
briarVersion.setText(
|
||||
getString(R.string.briar_version, BuildConfig.VERSION_NAME));
|
||||
torVersion = requireActivity().findViewById(R.id.TorVersion);
|
||||
torVersion.setText(
|
||||
getString(R.string.tor_version, BuildConfig.TorVersion));
|
||||
briarWebsite = requireActivity().findViewById(R.id.BriarWebsite);
|
||||
briarSourceCode = requireActivity().findViewById(R.id.BriarSourceCode);
|
||||
briarChangelog = requireActivity().findViewById(R.id.BriarChangelog);
|
||||
briarWebsite.setOnClickListener(View -> {
|
||||
String url = "https://briarproject.org/";
|
||||
goToUrl(url);
|
||||
});
|
||||
briarSourceCode.setOnClickListener(View -> {
|
||||
String url = "https://code.briarproject.org/briar/briar";
|
||||
goToUrl(url);
|
||||
});
|
||||
briarChangelog.setOnClickListener(View -> {
|
||||
String url =
|
||||
"https://code.briarproject.org/briar/briar/-/wikis/changelog";
|
||||
goToUrl(url);
|
||||
});
|
||||
}
|
||||
|
||||
private void goToUrl(String url) {
|
||||
Intent i = new Intent(Intent.ACTION_VIEW);
|
||||
i.setData(Uri.parse(url));
|
||||
try {
|
||||
startActivity(i);
|
||||
} catch (ActivityNotFoundException e) {
|
||||
logException(LOG, WARNING, e);
|
||||
Toast.makeText(requireContext(),
|
||||
R.string.error_start_activity, LENGTH_LONG).show();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
12
briar-android/src/main/res/drawable/ic_info_dark.xml
Normal file
12
briar-android/src/main/res/drawable/ic_info_dark.xml
Normal file
@@ -0,0 +1,12 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:tint="?android:attr/textColorPrimary"
|
||||
android:viewportWidth="24.0"
|
||||
android:viewportHeight="24.0"
|
||||
tools:ignore="NewApi">
|
||||
<path
|
||||
android:fillColor="#FF000000"
|
||||
android:pathData="M11,17h2v-6h-2v6zM12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM12,20c-4.41,0 -8,-3.59 -8,-8s3.59,-8 8,-8 8,3.59 8,8 -3.59,8 -8,8zM11,9h2L13,7h-2v2z" />
|
||||
</vector>
|
||||
73
briar-android/src/main/res/layout/fragment_about.xml
Normal file
73
briar-android/src/main/res/layout/fragment_about.xml
Normal file
@@ -0,0 +1,73 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:padding="16dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/BriarVersion"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/briar_version"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Body1"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toTopOf="parent" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/TorVersion"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/tor_version"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Body1"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toBottomOf="@+id/BriarVersion" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/LinksTitle"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:text="@string/links"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Body1"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toBottomOf="@+id/TorVersion" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/BriarWebsite"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/briar_website"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Body1"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toBottomOf="@+id/LinksTitle" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/BriarSourceCode"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/briar_source_code"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Body1"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toBottomOf="@+id/BriarWebsite" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/BriarChangelog"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/briar_changelog"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Body1"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toBottomOf="@+id/BriarSourceCode" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/TranslatorThanks"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:text="@string/translator_thanks"
|
||||
android:textAppearance="@style/TextAppearance.MaterialComponents.Body1"
|
||||
app:layout_constraintStart_toStartOf="parent"
|
||||
app:layout_constraintTop_toBottomOf="@+id/BriarChangelog" />
|
||||
|
||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||
@@ -26,6 +26,10 @@
|
||||
<string name="dnkm_xiaomi_button">Proteggi Briar</string>
|
||||
<string name="dnkm_xiaomi_help">Se Briar non è fissato nella lista di app recenti, non potrà funzionare in secondo piano.</string>
|
||||
<string name="dnkm_xiaomi_dialog_body_old">1. Apri la lista di app recenti (chiamata anche app switcher)\n\n2. Scorri fino alla schermata di Briar per mostrare l\'icona del lucchetto\n\n3. Se il lucchetto non è chiuso, toccalo per chiuderlo</string>
|
||||
<string name="dnkm_xiaomi_dialog_body_new">1. Apri la lista di app recenti (chiamata anche app switcher)\n\n2. Se Briar ha un piccolo lucchetto accanto al nome, allora non devi fare nulla\n\n3. Se non c\'è un lucchetto, tieni premuta la schermata di Briar finché non compare l\'icona del lucchetto, poi toccala</string>
|
||||
<string name="dnkm_xiaomi_lock_apps_text">Tocca il pulsante sottostante per aprire le impostazioni di sicurezza. Tocca \"Aumenta velocità\", poi \"Blocca le app\" e assicurati che Briar sia impostato su \"Bloccato\".</string>
|
||||
<string name="dnkm_xiaomi_lock_apps_help">Se Briar non è impostato su \"Bloccato\" nella schermata \"Blocca le app\", non riuscirà a funzionare in secondo piano.</string>
|
||||
<string name="dnkm_warning_dozed_1">Briar non è riuscito a funzionare in secondo piano</string>
|
||||
<!--Login-->
|
||||
<string name="enter_password">Password</string>
|
||||
<string name="try_again">Password sbagliata, riprova</string>
|
||||
@@ -238,6 +242,8 @@
|
||||
<string name="contact_added_toast">Contatto aggiunto: %s</string>
|
||||
<string name="contact_already_exists">Il contatto %s esiste già</string>
|
||||
<string name="qr_code_invalid">Il codice QR non è valido</string>
|
||||
<string name="qr_code_too_old_1">Il codice QR che hai scansionato proviene da una versione più vecchia di Briar.\n\nChiedi al tuo contatto di aggiornare all\'ultima versione e poi riprova.</string>
|
||||
<string name="qr_code_too_new_1">Il codice QR che hai scansionato proviene da una versione più recente di Briar.\n\nAggiorna all\'ultima versione e poi riprova.</string>
|
||||
<string name="camera_error">Errore fotocamera</string>
|
||||
<string name="connecting_to_device">Connessione al dispositivo\u2026</string>
|
||||
<string name="authenticating_with_device">Autenticazione con il dispositivo\u2026</string>
|
||||
@@ -613,6 +619,10 @@
|
||||
<string name="mailbox_status_connected_title">Casella postale in esecuzione</string>
|
||||
<string name="mailbox_status_problem_title">Briar sta avendo problemi a connettersi alla casella postale</string>
|
||||
<string name="mailbox_status_failure_title">Casella postale non disponibile</string>
|
||||
<string name="mailbox_status_app_too_old_title">Briar è troppo vecchio</string>
|
||||
<string name="mailbox_status_app_too_old_message">Aggiorna Briar all\'ultima versione e riprova.</string>
|
||||
<string name="mailbox_status_mailbox_too_old_title">La cassella postale è troppo vecchia</string>
|
||||
<string name="mailbox_status_mailbox_too_old_message">Aggiorna la casella postale all\'ultima versione e riprova.</string>
|
||||
<string name="mailbox_status_check_button">Controlla connessione</string>
|
||||
<!--Example for string substitution: Last connection: 3min ago-->
|
||||
<string name="mailbox_status_connected_info">Ultima connessione: %s</string>
|
||||
@@ -764,6 +774,9 @@
|
||||
<string name="hotspot_manual_site_address">Indirizzo (URL)</string>
|
||||
<string name="hotspot_qr_site">Il tuo telefono sta fornendo un hotspot Wi-Fi. Le persone connesse all\'hotspot possono scaricare Briar scansionando questo codice QR.</string>
|
||||
<!--e.g. Download Briar 1.2.20-->
|
||||
<string name="website_download_title_1">Scarica Briar %s</string>
|
||||
<string name="website_download_intro_1">Qualcuno nelle vicinanze ha condiviso Briar con te.</string>
|
||||
<string name="website_download_button">Scarica Briar</string>
|
||||
<string name="website_download_outro">Dopo il completamento del download, apri il file scaricato e installalo.</string>
|
||||
<string name="website_troubleshooting_title">Risoluzione dei problemi</string>
|
||||
<string name="website_troubleshooting_1">Se non puoi scaricare l\'app, prova con un browser web diverso.</string>
|
||||
|
||||
@@ -41,10 +41,10 @@
|
||||
<string name="dialog_message_lost_password">Contul dumneavoastră Briar este stocat în mod criptat pe dispozitivul dumneavoastră, nu în cloud, așa că nu vă putem reseta parola. Doriți să vă ștergeți contul și să o luați de la capăt?\n\nAtenție: Identitățile, contactele și mesajele dumneavoastră vor fi pierdute definitiv.</string>
|
||||
<string name="startup_failed_activity_title">Eroare de pornire Briar</string>
|
||||
<string name="startup_failed_clock_error">Briar nu a putut porni deoarece ceasul dispozitivului dvs. este greșit.\n\nVă rugăm să setați ceasul dispozitivului dvs. la ora corectă și să încercați din nou.</string>
|
||||
<string name="startup_failed_db_error">Briar nu a reușit să deschidă baza de date care conține contul dumneavoastră, contactele și mesajele dumneavoastră.\n\nVă rugăm să faceți upgrade la cea mai recentă versiune a app și să încercați din nou, sau să configurați un cont nou alegând \"Mi-am uitat parola\" la solicitarea parolei.</string>
|
||||
<string name="startup_failed_db_error">Briar nu a reușit să deschidă baza de date care conține contul dumneavoastră, contactele și mesajele dumneavoastră.\n\nVă rugăm să faceți upgrade la cea mai recentă versiune a aplicației și să încercați din nou, sau să configurați un cont nou alegând \"Mi-am uitat parola\" la solicitarea parolei.</string>
|
||||
<string name="startup_failed_data_too_old_error">Contul dvs. a fost creat cu o versiune veche a acestei aplicații și nu poate fi deschis cu această versiune.\n\nTrebuie fie să reinstalați versiunea veche, fie să creați un cont nou alegând \"Mi-am uitat parola\" la solicitarea de parolă.</string>
|
||||
<string name="startup_failed_data_too_new_error">Contul dvs. a fost creat cu o versiune mai nouă a acestei aplicații și nu poate fi deschis cu această versiune.\n\nVă rugăm să faceți upgrade la cea mai recentă versiune și să încercați din nou.</string>
|
||||
<string name="startup_failed_service_error">Briar nu a reușit să pornească o componentă necesară.\n\nVă rugăm să faceți upgrade la cea mai recentă versiune a acestui app și să încercați din nou.</string>
|
||||
<string name="startup_failed_service_error">Briar nu a reușit să pornească o componentă necesară.\n\nVă rugăm să faceți upgrade la cea mai recentă versiune a acestei aplicații și să încercați din nou.</string>
|
||||
<plurals name="expiry_warning">
|
||||
<item quantity="one">Aceasta este o versiune de test pentru Briar. Contul dumneavoastră va expira în %d zi și nu se poate reînnoi</item>
|
||||
<item quantity="few">Aceasta este o versiune de test pentru Briar. Contul dumneavoastră va expira în %d zile și nu se poate reînnoi.</item>
|
||||
@@ -554,12 +554,12 @@
|
||||
<string name="password_changed">Parola a fost schimbată.</string>
|
||||
<string name="panic_setting">Setare buton de panică</string>
|
||||
<string name="panic_setting_title">Buton de panică</string>
|
||||
<string name="panic_setting_hint">Configurați cum va reacționa Briar atunci când folosiți un app de buton de panică.</string>
|
||||
<string name="panic_app_setting_title">App buton de panică</string>
|
||||
<string name="unknown_app">app necunoscut</string>
|
||||
<string name="panic_app_setting_summary">Nu a fost setată nici un app</string>
|
||||
<string name="panic_setting_hint">Configurați cum va reacționa Briar atunci când folosiți o aplicație de buton de panică.</string>
|
||||
<string name="panic_app_setting_title">Aplicație buton de panică</string>
|
||||
<string name="unknown_app">aplicație necunoscută</string>
|
||||
<string name="panic_app_setting_summary">Nu a fost setată nici o aplicație</string>
|
||||
<string name="panic_app_setting_none">Nici una</string>
|
||||
<string name="dialog_title_connect_panic_app">Confirmare app de panică</string>
|
||||
<string name="dialog_title_connect_panic_app">Confirmare aplicație de panică</string>
|
||||
<string name="dialog_message_connect_panic_app">Sigur doriți să permiteți %1$s să declanșeze acțiuni destructive pentru butonul de panică?</string>
|
||||
<string name="panic_setting_destructive_action">Acțiuni distructive</string>
|
||||
<string name="panic_setting_signout_title">Ieșire</string>
|
||||
@@ -606,7 +606,7 @@
|
||||
<string name="mailbox_setup_io_error_title">Nu s-a putut conecta</string>
|
||||
<string name="mailbox_setup_io_error_description">Asigurați-vă că ambele dispozitive sunt conectate la Internet și încercați din nou.</string>
|
||||
<string name="mailbox_setup_assertion_error_title">Eroare de Cutie poștală</string>
|
||||
<string name="mailbox_setup_assertion_error_description">Vă rugăm să trimiteți feedback (cu date anonime) prin intermediul app-ului Briar dacă problema persistă.</string>
|
||||
<string name="mailbox_setup_assertion_error_description">Vă rugăm să trimiteți feedback (cu date anonime) prin intermediul aplicației Briar dacă problema persistă.</string>
|
||||
<string name="mailbox_setup_camera_error_description">Nu s-a putut accesa camera. Încercați din nou, poate după repornirea dispozitivului.</string>
|
||||
<string name="mailbox_setup_paired_title">Conectat</string>
|
||||
<string name="mailbox_setup_paired_description">Cutia dumneavoastră poștală a fost atașată cu succes la Briar.\n
|
||||
@@ -742,7 +742,7 @@ De asemenea, contactul dvs. poate modifica această setare pentru amândoi.</str
|
||||
<string name="transports_help_text">Briar se poate conecta la contactele dumneavoastră prin Internet, Wi-Fi sau Bluetooth.\n\nToate conexiunile la internet trec prin rețeaua Tor din motive de confidențialitate.\n\nDacă un contact poate fi accesat prin metode multiple, Briar le va folosi în mod paralel.</string>
|
||||
<!--Share app offline-->
|
||||
<string name="hotspot_title">Partajează această aplicație fără Internet</string>
|
||||
<string name="hotspot_intro">Împărtășiți acest app cu o persoană din apropiere fără conexiune la Internet, utilizând Wi-Fi-ul telefonului dumneavoastră.
|
||||
<string name="hotspot_intro">Împărtășiți această aplicație cu o persoană din apropiere fără conexiune la Internet, utilizând Wi-Fi-ul telefonului dumneavoastră.
|
||||
\n\nTelefonul dumneavoastră va porni un hotspot Wi-Fi. Persoanele din apropiere se pot conecta la hotspot și pot descărca aplicația Briar de pe telefonul vostru.</string>
|
||||
<string name="hotspot_button_start_sharing">Pornește hotspot</string>
|
||||
<string name="hotspot_button_stop_sharing">Oprește hotspot</string>
|
||||
@@ -793,7 +793,7 @@ De asemenea, contactul dvs. poate modifica această setare pentru amândoi.</str
|
||||
<string name="hotspot_help_site_4">Dacă puteți vizita siteul dar nu puteți descărca aplicația Briar, încercați cu un alt browser.</string>
|
||||
<string name="hotspot_help_fallback_title">Nimic nu funcționează?</string>
|
||||
<string name="hotspot_help_fallback_intro">Puteți încerca să salvați aplicația ca un fișier .APK pentru a-l partaja în alt mod. Odată fișierul transferat pe celălalt dispozitiv, poate fi folosit să se instaleze Briar.
|
||||
\n\nPont: Pentru a partaja prin Bluetooth s-ar putea sa fie necesar sa redenumiți fișierul ca să aivă terminația .ZIP.</string>
|
||||
\n\nPont: Pentru a partaja prin Bluetooth s-ar putea sa fie necesar sa redenumiți fișierul ca să aibă terminația .ZIP.</string>
|
||||
<string name="hotspot_help_fallback_button">Salvează aplicația</string>
|
||||
<!--error handling-->
|
||||
<string name="hotspot_error_intro">A apărut o problemă când s-a încercat partajarea aplicației prin Wi-Fi.</string>
|
||||
|
||||
@@ -314,6 +314,13 @@
|
||||
<string name="different_person_button">Different Person</string>
|
||||
<string name="duplicate_link_dialog_text_3">%1$s and %2$s sent you the same link.\n\nOne of them may be trying to discover who your contacts are.\n\nDon\'t tell them you received the same link from someone else.</string>
|
||||
<string name="pending_contact_updated_toast">Pending contact updated</string>
|
||||
|
||||
<!-- Peer trust levels -->
|
||||
|
||||
<string name="peer_trust_level_unverified">Unverified contact</string>
|
||||
<string name="peer_trust_level_verified">Verified contact</string>
|
||||
<string name="peer_trust_level_ourselves">Me</string>
|
||||
<string name="peer_trust_level_stranger">Stranger</string>
|
||||
|
||||
<!-- Introductions -->
|
||||
|
||||
@@ -684,6 +691,17 @@
|
||||
<string name="mailbox_error_wizard_info2">Please come back to this screen when you have access to the device.</string>
|
||||
<string name="mailbox_error_wizard_info3">Please unlink your mailbox using the button below.\n\nAfter unlinking your old Mailbox, you can set up a new Mailbox at any time.</string>
|
||||
|
||||
<!-- About -->
|
||||
<string name="about_title">About</string>
|
||||
<string name="briar_version">Briar version: %s</string>
|
||||
<string name="tor_version">Tor version: %s</string>
|
||||
<string name="links">Links</string>
|
||||
<string name="briar_website">\u2022 <a href="">Website</a></string>
|
||||
<string name="briar_source_code">\u2022 <a href="">Source code</a></string>
|
||||
<string name="briar_changelog">\u2022 <a href="">Changelog</a></string>
|
||||
<!-- Here translators can add their names or Transifex usernames(eg "Thanks to all the contributors at the Localization Lab, especially Tom, Matthew and Jerry") -->
|
||||
<string name="translator_thanks">Thanks to all the contributors at the Localization Lab</string>
|
||||
|
||||
<!-- Conversation Settings -->
|
||||
<string name="disappearing_messages_title">Disappearing messages</string>
|
||||
<string name="disappearing_messages_explanation_long">Turning on this setting will make new
|
||||
|
||||
@@ -29,6 +29,11 @@
|
||||
android:title="@string/mailbox_settings_title"
|
||||
app:icon="@drawable/ic_mailbox" />
|
||||
|
||||
<Preference
|
||||
android:title="@string/about_title"
|
||||
app:fragment="org.briarproject.briar.android.settings.AboutFragment"
|
||||
app:icon="@drawable/ic_info_dark" />
|
||||
|
||||
<PreferenceCategory
|
||||
android:key="pref_key_actions"
|
||||
android:layout="@layout/preferences_category"
|
||||
|
||||
Reference in New Issue
Block a user