Compare commits

...

100 Commits

Author SHA1 Message Date
akwizgran
0e51ddb767 Bumped expiry date to 1 May 2017. 2017-02-27 09:29:24 +00:00
Torsten Grote
36f02b36d9 Update expiry and translations 2017-02-01 11:17:53 -02:00
akwizgran
2fb11fba2a Merge branch '877-save-invitation-outcome-to-invitation-message-and-make-available-to-ui' into 'master'
Store invitation outcome in metadata and make it available to the UI

This MR is based on !479 and should only be merged after that one has been merged as well.

It stores the invitation outcome in the message metadata  and includes it in the `canBeOpened()` calculation for private groups and sharables.

Closes #877

See merge request !480
2017-01-06 16:06:19 +00:00
akwizgran
1d11857e75 Merge branch '476-blog-sharing-protocol-modifies-state-external-to-session' into 'master'
Migrate blog sharing to new sharing client infrastructure

This MR contains a second small commit that fixes #816 and adds a test for it.

Closes #476, #701

See merge request !479
2017-01-06 16:04:17 +00:00
Torsten Grote
04508a7431 Store invitation outcome in metadata
and include in canBeOpened calculation for private groups and sharables.
2017-01-06 13:29:21 -02:00
Torsten Grote
5653c6d650 Address review comments 2017-01-06 13:25:13 -02:00
Torsten Grote
ab100ad19b Properly remove the blog when deleting a contact and inform all peers
Fixes #816
2017-01-06 13:01:37 -02:00
Torsten Grote
c13eafef14 Migrate blog sharing to new sharing client infrastructure 2017-01-06 13:01:34 -02:00
akwizgran
d5443e9651 Merge branch '889-select-navdrawer-item-when-coming-from-notification' into 'master'
Check the blog item in NavDrawer when opening a blog via notification

There are three scenarios where the selected item in the NavDrawer changes:
1. The user selects an item -> the item is checked automatically.
2. The user pressed back -> already handled in onBackPressed (needs to be extended with #606)
3. The user touched a notification -> handled by this commit.
   
Signed-off-by: goapunk <noobie@goapunks.net>

Closes #889

See merge request !481
2017-01-06 14:59:21 +00:00
akwizgran
d5f9a3280d Merge branch 'briar-recycler-view-log' into 'master'
Stop periodic list update only once

When testing the forum unread code, I noticed the recycler view is detaching twice. Once because the stop method is called and once because the view detaches from the window. Wouldn't it be safe to null the refresher when the updates are stopped?

See merge request !478
2017-01-06 14:15:48 +00:00
goapunk
09b2ecaecf Check the corresponding NavDrawer item when coming from a notification
Signed-off-by: goapunk <noobie@goapunks.net>
2017-01-06 15:12:40 +01:00
Torsten Grote
dc6a6f27ab Fix MessageTreeImplTest 2017-01-04 16:27:49 -02:00
Torsten Grote
8d9ddeeeee Stop periodic list update only once 2017-01-04 11:15:19 -02:00
Torsten Grote
baed2b8483 Merge branch '879-remove-thread-collapsing-unread-count' into 'master'
Remove code for collapsing threads and for reply count

Besides removing lots of code, this MR also improves the encapsulation between adapter and view holders.

Closes #478, #502, #526, #682,  #683,  #835,  #836

See merge request !477
2017-01-04 13:00:16 +00:00
Torsten Grote
b3d3230549 Remove code for collapsing threads and for reply count 2017-01-04 10:58:31 -02:00
akwizgran
deb8787668 Merge branch '879-threaded-unread-messages' into 'master'
Threaded Unread Handling

![unread](/uploads/457c3bc36c897d683ff8161b4f3a344c/unread.mp4)

This leaves in the collapsing code for now and just hides the UI element for collapsing. The code can be removed in a second pass to simplify the adapter.

Closes #879

See merge request !476
2017-01-04 11:12:24 +00:00
Torsten Grote
7034ea28f3 Merge branch '475-new-sharing-client' into 'master'
New Forum Sharing Client

This is very similar to how the private group invitations work and I am sure there's still some tiny bugs that I didn't catch.

All existing integration tests either pass or have been modified to pass.

Once this has been merged, the code should be usable for blog sharing as well.

Closes #475

See merge request !467
2017-01-03 19:30:48 +00:00
Torsten Grote
51b78cf9b1 Address review comments for new sharing client 2017-01-03 17:25:45 -02:00
Torsten Grote
b4c669243b Add UnreadMessageButton to threaded conversations 2017-01-03 13:25:31 -02:00
Torsten Grote
694e662028 New Forum Sharing Client 2017-01-03 11:23:02 -02:00
Torsten Grote
409e0fb5a5 ForumSharingValidator 2017-01-03 11:23:00 -02:00
Torsten Grote
279f4d668a Add new UnreadMessageButton class 2017-01-02 16:30:00 -02:00
akwizgran
d2608e28ac Merge branch '881-forumactivitytest-fails-due-to-custom-toolbar' into 'master'
Fix ForumActivityTest and get rid of redundant theme definition

Closes #881

See merge request !474
2017-01-02 14:22:27 +00:00
akwizgran
8cf02c5f0e Merge branch '851-refresher-memory-leak' into 'master'
Fix memory leaks caused by periodic view refreshing tasks

This branch implements @goapunk's suggested solution to #851. Credit goes to @ernir for finding the bug and the initial solution, and @goapunk for the improved solution - I just did a quick implementation so we can get this fixed as quickly as possible.

Closes #851

See merge request !473
2017-01-02 14:10:32 +00:00
Torsten Grote
c5df2100da Fix ForumActivityTest and get rid of redundant theme definition 2017-01-02 11:57:45 -02:00
akwizgran
a6999a8197 Merge branch '710-conversationactivity-uses-uninitialised-field-as-format-string-argument' into 'master'
Make sure contact name is initialized when needed

This uses a Listenable Future and unfortunately requires 4 basically identical methods to handle the incoming events. Any suggestions for improving that are welcome.

Closes #710

See merge request !472
2017-01-02 11:11:41 +00:00
akwizgran
da89f11419 Merge branch '882-feedmanagerimpl-logs-rss-feed-urls' into 'master'
Do not log information from RSS feeds

Closes #882

See merge request !475
2017-01-02 10:52:04 +00:00
Torsten Grote
a9663875f4 Update expiry date and translations 2016-12-30 12:13:43 -02:00
Torsten Grote
804966ede6 Do not log information from RSS feeds 2016-12-29 13:07:18 -02:00
Torsten Grote
f0f22b42e5 Make sure contact name is initialized when needed 2016-12-29 12:29:32 -02:00
akwizgran
59316ae3c4 Fix memory leaks caused by periodic view refreshing tasks. 2016-12-28 15:23:21 +00:00
Torsten Grote
460b524e4b Merge branch 'record-reading-tests' into 'master'
Unit tests for record readers

I thought we should have some tests for the new logic that skips unrecognised record types.

See merge request !471
2016-12-21 17:14:16 +00:00
akwizgran
48e949c9f8 Merge branch '742-use-unique-request-ids-across-the-app' into 'master'
Use unique request codes across the app

Closes #742

See merge request !470
2016-12-21 15:33:03 +00:00
Torsten Grote
924398c829 Use unique request codes across the app 2016-12-21 12:52:11 -02:00
akwizgran
8619b044ce Merge branch '469-handle-background-errors' into 'master'
Add a handleDbException() method to BaseActivity

This adds a `handleDbException()` method to BaseActivity and a corresponding method for fragments that calls through to the activity.
For now, the method just finishes the activity
and NavDrawerActivity overrides it to do nothing,
and all the error places marked with TODO that finish the activity call the method instead.

That gives us zero functional improvement over the status quo,
but it allows us to change the default behaviour easily,
and then we can start thinking about which cases should have non-default behaviour.

First part of #469

See merge request !469
2016-12-21 14:46:53 +00:00
akwizgran
3c3731a562 Merge branch '876-group-invitation-not-marked-unavailable' into 'master'
Mark invitation unavailable to answer when creator dissolved the group after the invitation.

Closes #876

See merge request !468
2016-12-21 14:43:38 +00:00
akwizgran
b54984b542 Unit tests for RecordReaderImpl. 2016-12-21 14:39:56 +00:00
akwizgran
2390f767f5 Unit tests for KeyAgreementTransport. 2016-12-21 14:08:21 +00:00
Torsten Grote
0a9840997f This adds a handleDbException() method to BaseActivity
and a corresponding method for fragments that calls through to the activity.
For now, the method just finishes the activity
and NavDrawerActivity overrides it to do nothing,
and all the error places marked with TODO that finish the activity call the method instead.

That gives us zero functional improvement over the status quo,
but it allows us to change the default behaviour easily,
and then we can start thinking about which cases should have non-default behaviour.
2016-12-21 12:06:20 -02:00
Torsten Grote
6a94785d9a Mark invitation unavailable to answer when creator dissolved the group
after the invitation.

Closes #876
2016-12-21 11:24:08 -02:00
akwizgran
79fc41477c Merge branch '628-bring-protocols-into-line-with-spec' into 'master'
Bring protocols in line with spec

Closes #628

See merge request !465
2016-12-21 12:52:43 +00:00
Torsten Grote
efb89adf41 Merge branch '793-show-open-button-after-accepting-invitations' into 'master'
Show open button in private conversation after accepting invitations

To keep the implementation simple, the Open button does appear where the Accept button had been previously.

In order to make the Open button functional, I had to make the `GroupId` of the invitation target available to the UI. Most code in this MR is due to that.

![device-2016-12-13-105228](/uploads/d0f27fc02f1411596458d9203a0810d2/device-2016-12-13-105228.png)

Closes #793

See merge request !457
2016-12-20 14:07:13 +00:00
Torsten Grote
c04580e321 Don't open unsubscribed shareables 2016-12-20 12:00:01 -02:00
Torsten Grote
2ef9b8f4b6 Show open button in private conversation after accepting invitations 2016-12-20 08:47:27 -02:00
akwizgran
d63d15329c Merge branch '814-enable-QrScanner-after-QrCode-was-created' into 'master'
Ignore QR code results until local QR code is created

* Make scanning only possible after we are "ready" (= our QrCode was created and set).

Signed-off-by: goapunk <noobie@goapunks.net>

Closes #814

See merge request !454
2016-12-19 19:28:14 +00:00
Torsten Grote
5345db0b6b Address review comments 2016-12-19 11:15:53 -02:00
Torsten Grote
501980d8fe Bring protocols in line with spec 2016-12-19 10:26:48 -02:00
akwizgran
cc5c000278 Merge branch '738-older-devices-show-overflow-icon-on-some-screens-but-not-others' into 'master'
Also show overflow icon on devices with menu key by using Toolbar

Closes #738

See merge request !463
2016-12-16 11:58:18 +00:00
akwizgran
3ce0131b8c Merge branch '828-update-briar-logo-in-app' into 'master'
Update all logos

The launcher icons are now in mipmap folders which is the recommended practice, because on a low-res device, the high res drawables are stripped from the app. This is bad when the user decides to show the app icons really big on the launcher and the high-res drawables are not available anymore.

The old launcher icon seemed to have some sort of 3D effect.
![device-2016-12-13-134037](/uploads/84db532df3821ad74ba57719f0763b7b/device-2016-12-13-134037.png)

Navigation Drawer Old:
![device-2016-12-13-124112](/uploads/465b817d2e0bbbd50b461ea32686c933/device-2016-12-13-124112.png)
Navigation Drawer New:
![device-2016-12-13-132428](/uploads/3c3530bfc515525dd8f66abfa52d1142/device-2016-12-13-132428.png)

Closes #828

See merge request !459
2016-12-15 23:25:40 +00:00
akwizgran
008e4f760a Merge branch '795-use-different-notification-icons-for-different-features' into 'master'
Use different notification icons for different features

![device-2016-12-13-151008](/uploads/2c9aa33c230738b5ea20a76ac5e3b214/device-2016-12-13-151008.png)
![device-2016-12-13-150954](/uploads/85acd46fc6afd3aebcc1fcd015b041d7/device-2016-12-13-150954.png)

Closes #795

See merge request !460
2016-12-15 23:16:36 +00:00
akwizgran
fc44268b22 Removed translations of unused strings. 2016-12-15 23:12:24 +00:00
akwizgran
de0a7c75ed Merge branch '697-include-commit-id-in-crash-reports-and-feedback' into 'master'
Include Commit ID in crash reports and feedback

Closes #697

See merge request !461
2016-12-15 23:06:24 +00:00
Torsten Grote
1c6be2fb78 Include Commit ID in crash reports and feedback 2016-12-15 15:40:52 -02:00
Torsten Grote
09b0a8b161 Use different notification icons for different features
and use the primary color for the notification.
2016-12-15 15:29:48 -02:00
Torsten Grote
a6d053a0ea Update all logos 2016-12-15 15:19:38 -02:00
akwizgran
e7a26c42a4 Merge branch '285-plugins-should-throw-exceptions-for-startup-errors' into 'master'
Plugins throw exceptions for startup errors

Please review carefully as I don't know much about the code I have touched here.

Closes #285

See merge request !462
2016-12-15 14:33:35 +00:00
akwizgran
bb5fc35e17 Removed translations of unused strings. 2016-12-15 10:56:04 +00:00
Torsten Grote
ea4e2f09c8 Revert dagger update 2016-12-14 16:52:38 -02:00
Torsten Grote
ffc9fdbb92 Plugins throw exceptions for startup errors 2016-12-14 16:35:23 -02:00
akwizgran
074f5c2faf Fix imports in HashTest. 2016-12-14 17:09:15 +00:00
goapunk
7666b210e4 Ignore results from the QrScanner if task is not ready
* Ignore results until the KeyAgreementTask is ready and returned the local payload

Signed-off-by: goapunk <noobie@goapunks.net>
2016-12-14 17:28:01 +01:00
akwizgran
ab3fcb6219 Merge branch 'add-crypto-hash-test' into 'master'
Add Unit tests for CryptoComponent#hash()

See merge request !464
2016-12-14 16:14:18 +00:00
akwizgran
b7e35ff780 Merge branch '778-move-unit-tests-into-their-respective-modules' into 'master'
Move all unit tests to their modules and remove briar-tests

There are now tests in these modules:
* bramble-api
* bramble-core
* bramble-j2se
* briar-core
* briar-android

In order to run all -core tests together, the following AS run configuration can be used:
![Screenshot_2016-12-12_16-37-53](/uploads/8c706406f015ecd9e2371ebc28e6b34c/Screenshot_2016-12-12_16-37-53.png)

Closes #778

See merge request !456
2016-12-14 15:57:45 +00:00
akwizgran
3c2428449d Moved test utility classes into test package. 2016-12-14 15:42:52 +00:00
Torsten Grote
25a4caec2a Add Unit tests for CryptoComponent#hash() 2016-12-14 13:15:44 -02:00
Torsten Grote
db71472501 Also show overflow icon on devices with menu key by using Toolbar 2016-12-14 11:17:04 -02:00
Torsten Grote
1081a08ea9 Move all unit tests to their modules and remove briar-tests 2016-12-13 17:22:24 -02:00
akwizgran
32be148c7a Merge branch '646-shared-with-subtitle-groups' into 'master'
Add sharing information to private group ActionBar subtitle

![device-2016-12-12-114533](/uploads/b31fc37643ef6e817a80a4ddd767fe98/device-2016-12-12-114533.png)

Closes #646

See merge request !455
2016-12-13 18:01:48 +00:00
Torsten Grote
78000375df Merge branch '155-notification-icon' into 'master'
Make notification icon less similar to superuser icon

Closes #155

See merge request !458
2016-12-13 17:24:05 +00:00
akwizgran
66f8978bb6 Make notification icon less similar to superuser icon. 2016-12-13 17:20:48 +00:00
Torsten Grote
45b5040254 Add sharing information to private group ActionBar subtitle 2016-12-12 13:55:35 -02:00
Torsten Grote
378a8f0a10 Merge branch '813-add-online-status-and-creator-information-to-group-memberlist' into 'master'
Add creator and online information to group member list

![device-2016-12-06-102258](/uploads/90e19a6ca31aaf91c6ebf3ea8e218b3f/device-2016-12-06-102258.png)
![device-2016-12-06-110113](/uploads/3fd62f7cdfe75419a07262356d27b952/device-2016-12-06-110113.png)

Closes #813

See merge request !448
2016-12-12 15:36:02 +00:00
Torsten Grote
562866494b Add creator and online information to group member list 2016-12-12 13:33:23 -02:00
akwizgran
c9cb085a0a Merge branch '777-move-integration-tests-into-their-respective-modules' into 'master'
Move integration tests to their proper packages

Closes #777

See merge request !453
2016-12-12 15:08:26 +00:00
Torsten Grote
97d4c68f43 Move integration tests to their proper packages 2016-12-12 10:27:41 -02:00
Torsten Grote
4226ba40c2 Merge branch '570-consistent-use-of-animations' into 'master'
Make animations more consistent

![animations6](/uploads/0ac694d3561515e04fbb9032d31f183c/animations6.mp4)

Closes #570, #621

See merge request !439
2016-12-09 16:49:26 +00:00
Torsten Grote
3df3d19a07 Address review comments 2016-12-09 14:40:20 -02:00
Torsten Grote
e3dcc62509 Use back transition when backing out of creating private group 2016-12-09 14:22:05 -02:00
Torsten Grote
db3c3eee44 Move OnBlogPostClickListener from activity to fragment 2016-12-09 14:22:03 -02:00
Torsten Grote
5a522d64df Don't show splash screen when signed in
This also removes the BriarFragmentActivity that was only really used by
the NavDrawerActivity.
2016-12-09 14:14:47 -02:00
Torsten Grote
68b216d580 Make animations more consistent 2016-12-09 14:13:18 -02:00
Torsten Grote
d5c6fcc85b Fix merge accident after renaming event 2016-12-09 14:12:27 -02:00
Torsten Grote
a099104d08 Merge branch '646-shared-with-subtitle-forums' into 'master'
Add sharing info to ForumActivity action bar subtitle

This indirectly does also most of the work for adding the same information to private groups. However, completing this is blocked by !448.

![device-2016-12-07-152915](/uploads/5bb42f2e78a87931b0307e7597ba72c5/device-2016-12-07-152915.png)

Second part of #646

See merge request !451
2016-12-09 16:06:21 +00:00
akwizgran
787b3399f7 Merge branch '646-shared-with-subtitle' into 'master'
Add blog sharing information to toolbar subtitle

This MR introduces a new `SharingController` which is supposed to be used in activities that show blogs, groups and forums. Feedback on this approach is welcome before this is used to add "Shared with" support to other parts of the UI.

The toolbar subtitle shows information about how many contacts the current shareable is shared with and how many of those are online.

So far this is implemented for blogs:

![device-2016-12-05-180207](/uploads/13afb4c7c5d10ad29c414865ee02670d/device-2016-12-05-180207.png)

One part of #646

See merge request !447
2016-12-09 16:04:04 +00:00
Torsten Grote
4e159bbb1f Add sharing info to ForumActivity action bar subtitle 2016-12-09 14:02:42 -02:00
Torsten Grote
7c6232db9d Address review comments (rename event, fix annotations, final field) 2016-12-09 13:54:39 -02:00
Torsten Grote
6cf1480d2d Merge branch '766-unit-tests-for-peer-protocol-engine' into 'master'
Add unit tests for PeerProtocolEngine

Although not all classes have unit tests, this

Closes #766

See merge request !450
2016-12-08 16:14:34 +00:00
Torsten Grote
2679e6932f Add unit tests for PeerProtocolEngine 2016-12-08 14:13:00 -02:00
akwizgran
17e149e517 Merge branch '766-unit-tests-for-invitee-protocol-engine' into 'master'
Add unit tests for InviteeProtocolEngine

Next part of #766

See merge request !444
2016-12-08 15:42:05 +00:00
Torsten Grote
d04dda1566 Add sharing information to toolbar subtitle of blogs
The toolbar subtitle shows information about how many contacts the
current blog is shared with and how many of those are online.
2016-12-07 15:16:44 -02:00
Torsten Grote
5588855667 Fix intent of some CreatorProtocolEngine unit tests 2016-12-07 15:07:01 -02:00
Torsten Grote
7df6abbcbe Merge branch '810-fix-sharing-status-screens' into 'master'
Fix Sharing Status screens

* Remove distinction between "shared with" and "shared by"
* Show all contacts a blog is shared with
* Show online status of contacts in sharing screen

![device-2016-12-05-142949](/uploads/703fbd2d52815374e57edd89f754bf6c/device-2016-12-05-142949.png)

Closes #810

See merge request !445
2016-12-07 16:52:29 +00:00
Torsten Grote
001f5faeaa Two small review details: comment and initializing boolean 2016-12-07 14:49:57 -02:00
Torsten Grote
ba1a19d236 Address review issues 2016-12-07 14:31:24 -02:00
Torsten Grote
b7ce7de42a Add unit tests for InviteeProtocolEngine 2016-12-07 14:31:23 -02:00
akwizgran
3f6a8f9341 Merge branch '808-introduction-client-logs-contact-names' into 'master'
Remove verbose logging from introduction client

Closes #808

See merge request !449
2016-12-07 15:49:14 +00:00
akwizgran
9495163016 Merge branch 'onboarding-dialog-style' into 'master'
Introduce Dialog Theme for Onboarding

Currently onboarding dialogs and confirmation dialogs look the same. This MR introduces a new dialog theme for onboarding dialogs that looks like the tap target onboarding, so that the user can immediately spot the purpose of the dialog.

![device-2016-12-06-085539](/uploads/6d75b17c0f20028bb7ffac65e6fba03a/device-2016-12-06-085539.png)

See merge request !446
2016-12-07 15:47:12 +00:00
Torsten Grote
7f5a5d40dc Remove verbose logging from introduction client 2016-12-06 15:36:54 -02:00
Torsten Grote
98dd8ec7f7 Fix Sharing Status screens
* Remove distinction between "shared with" and "shared by"
* Show all contacts a blog is shared with
* Show online status of contacts in sharing screen
2016-12-06 10:53:50 -02:00
Torsten Grote
81337fe7ad Introduce Dialog Theme for Onboarding 2016-12-05 14:54:39 -02:00
455 changed files with 9969 additions and 7017 deletions

View File

@@ -18,6 +18,7 @@ import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.bramble.api.plugin.Backoff;
import org.briarproject.bramble.api.plugin.PluginException;
import org.briarproject.bramble.api.plugin.TransportId;
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginCallback;
@@ -128,7 +129,7 @@ class DroidtoothPlugin implements DuplexPlugin {
}
@Override
public boolean start() throws IOException {
public void start() throws PluginException {
if (used.getAndSet(true)) throw new IllegalStateException();
// BluetoothAdapter.getDefaultAdapter() must be called on a thread
// with a message queue, so submit it to the AndroidExecutor
@@ -142,13 +143,14 @@ class DroidtoothPlugin implements DuplexPlugin {
}).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while getting BluetoothAdapter");
LOG.warning("Interrupted while getting BluetoothAdapter");
throw new PluginException(e);
} catch (ExecutionException e) {
throw new IOException(e);
throw new PluginException(e);
}
if (adapter == null) {
LOG.info("Bluetooth is not supported");
return false;
throw new PluginException();
}
running = true;
// Listen for changes to the Bluetooth state
@@ -170,7 +172,6 @@ class DroidtoothPlugin implements DuplexPlugin {
LOG.info("Not enabling Bluetooth");
}
}
return true;
}
private void bind() {

View File

@@ -39,14 +39,13 @@ class AndroidLanTcpPlugin extends LanTcpPlugin {
}
@Override
public boolean start() {
public void start() {
if (used.getAndSet(true)) throw new IllegalStateException();
running = true;
// Register to receive network status events
networkStateReceiver = new NetworkStateReceiver();
IntentFilter filter = new IntentFilter(CONNECTIVITY_ACTION);
appContext.registerReceiver(networkStateReceiver, filter);
return true;
}
@Override

View File

@@ -25,6 +25,7 @@ import org.briarproject.bramble.api.keyagreement.KeyAgreementListener;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.bramble.api.plugin.Backoff;
import org.briarproject.bramble.api.plugin.PluginException;
import org.briarproject.bramble.api.plugin.TorConstants;
import org.briarproject.bramble.api.plugin.TransportId;
import org.briarproject.bramble.api.plugin.duplex.DuplexPlugin;
@@ -162,14 +163,18 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
}
@Override
public boolean start() throws IOException {
public void start() throws PluginException {
if (used.getAndSet(true)) throw new IllegalStateException();
// Install or update the assets if necessary
if (!assetsAreUpToDate()) installAssets();
LOG.info("Starting Tor");
// Watch for the auth cookie file being updated
cookieFile.getParentFile().mkdirs();
cookieFile.createNewFile();
try {
cookieFile.getParentFile().mkdirs();
cookieFile.createNewFile();
} catch (IOException e) {
throw new PluginException(e);
}
CountDownLatch latch = new CountDownLatch(1);
FileObserver obs = new WriteObserver(cookieFile, latch);
obs.startWatching();
@@ -182,8 +187,8 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
Process torProcess;
try {
torProcess = Runtime.getRuntime().exec(cmd, env, torDirectory);
} catch (SecurityException e) {
throw new IOException(e);
} catch (SecurityException | IOException e) {
throw new PluginException(e);
}
// Log the process's standard output until it detaches
if (LOG.isLoggable(INFO)) {
@@ -197,35 +202,39 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
if (exit != 0) {
if (LOG.isLoggable(WARNING))
LOG.warning("Tor exited with value " + exit);
return false;
throw new PluginException();
}
// Wait for the auth cookie file to be created/updated
if (!latch.await(COOKIE_TIMEOUT, MILLISECONDS)) {
LOG.warning("Auth cookie not created");
if (LOG.isLoggable(INFO)) listFiles(torDirectory);
return false;
throw new PluginException();
}
} catch (InterruptedException e) {
LOG.warning("Interrupted while starting Tor");
Thread.currentThread().interrupt();
return false;
throw new PluginException();
}
// Open a control connection and authenticate using the cookie file
controlSocket = new Socket("127.0.0.1", CONTROL_PORT);
controlConnection = new TorControlConnection(controlSocket);
controlConnection.authenticate(read(cookieFile));
// Tell Tor to exit when the control connection is closed
controlConnection.takeOwnership();
controlConnection.resetConf(Collections.singletonList(OWNER));
running = true;
// Register to receive events from the Tor process
controlConnection.setEventHandler(this);
controlConnection.setEvents(Arrays.asList(EVENTS));
// Check whether Tor has already bootstrapped
String phase = controlConnection.getInfo("status/bootstrap-phase");
if (phase != null && phase.contains("PROGRESS=100")) {
LOG.info("Tor has already bootstrapped");
connectionStatus.setBootstrapped();
try {
// Open a control connection and authenticate using the cookie file
controlSocket = new Socket("127.0.0.1", CONTROL_PORT);
controlConnection = new TorControlConnection(controlSocket);
controlConnection.authenticate(read(cookieFile));
// Tell Tor to exit when the control connection is closed
controlConnection.takeOwnership();
controlConnection.resetConf(Collections.singletonList(OWNER));
running = true;
// Register to receive events from the Tor process
controlConnection.setEventHandler(this);
controlConnection.setEvents(Arrays.asList(EVENTS));
// Check whether Tor has already bootstrapped
String phase = controlConnection.getInfo("status/bootstrap-phase");
if (phase != null && phase.contains("PROGRESS=100")) {
LOG.info("Tor has already bootstrapped");
connectionStatus.setBootstrapped();
}
} catch (IOException e) {
throw new PluginException(e);
}
// Register to receive network status events
networkStateReceiver = new NetworkStateReceiver();
@@ -233,7 +242,6 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
appContext.registerReceiver(networkStateReceiver, filter);
// Bind a server socket to receive incoming hidden service connections
bind();
return true;
}
private boolean assetsAreUpToDate() {
@@ -246,7 +254,7 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
}
}
private void installAssets() throws IOException {
private void installAssets() throws PluginException {
InputStream in = null;
OutputStream out = null;
try {
@@ -269,7 +277,7 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
} catch (IOException e) {
tryToClose(in);
tryToClose(out);
throw e;
throw new PluginException(e);
}
}
@@ -476,7 +484,7 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
}
@Override
public void stop() throws IOException {
public void stop() throws PluginException {
running = false;
tryToClose(socket);
if (networkStateReceiver != null)

View File

@@ -8,15 +8,34 @@ dependencies {
compile "com.google.dagger:dagger:2.0.2"
compile 'com.google.dagger:dagger-compiler:2.0.2'
compile 'com.google.code.findbugs:jsr305:3.0.1'
testCompile 'junit:junit:4.12'
testCompile "org.jmock:jmock:2.8.1"
testCompile "org.jmock:jmock-junit4:2.8.1"
testCompile "org.jmock:jmock-legacy:2.8.1"
testCompile "org.hamcrest:hamcrest-library:1.3"
testCompile "org.hamcrest:hamcrest-core:1.3"
}
dependencyVerification {
verify = [
'com.google.dagger:dagger:84c0282ed8be73a29e0475d639da030b55dee72369e58dd35ae7d4fe6243dcf9',
'com.google.dagger:dagger-compiler:b74bc9de063dd4c6400b232231f2ef5056145b8fbecbf5382012007dd1c071b3',
'com.google.code.findbugs:jsr305:c885ce34249682bc0236b4a7d56efcc12048e6135a5baf7a9cde8ad8cda13fcd',
'javax.inject:javax.inject:91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff',
'com.google.dagger:dagger-producers:99ec15e8a0507ba569e7655bc1165ee5e5ca5aa914b3c8f7e2c2458f724edd6b',
'com.google.guava:guava:d664fbfc03d2e5ce9cab2a44fb01f1d0bf9dfebeccc1a473b1f9ea31f79f6f99',
'com.google.code.findbugs:jsr305:c885ce34249682bc0236b4a7d56efcc12048e6135a5baf7a9cde8ad8cda13fcd'
]
}
// needed to make test output available to bramble-core and briar-core
configurations {
testOutput.extendsFrom(testCompile)
}
task jarTest(type: Jar, dependsOn: testClasses) {
from sourceSets.test.output
classifier = 'test'
}
artifacts {
testOutput jarTest
}

View File

@@ -43,6 +43,24 @@ public interface ContactManager {
*/
Contact getContact(ContactId c) throws DbException;
/**
* Returns the contact with the given remoteAuthorId
* that was added by the LocalAuthor with the given localAuthorId
*
* @throws org.briarproject.bramble.api.db.NoSuchContactException
*/
Contact getContact(AuthorId remoteAuthorId, AuthorId localAuthorId)
throws DbException;
/**
* Returns the contact with the given remoteAuthorId
* that was added by the LocalAuthor with the given localAuthorId
*
* @throws org.briarproject.bramble.api.db.NoSuchContactException
*/
Contact getContact(Transaction txn, AuthorId remoteAuthorId,
AuthorId localAuthorId) throws DbException;
/**
* Returns all active contacts.
*/

View File

@@ -3,7 +3,6 @@ package org.briarproject.bramble.api.plugin;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.io.IOException;
import java.util.Collection;
@NotNullByDefault
@@ -25,14 +24,14 @@ public interface Plugin {
int getMaxIdleTime();
/**
* Starts the plugin and returns true if it started successfully.
* Starts the plugin.
*/
boolean start() throws IOException;
void start() throws PluginException;
/**
* Stops the plugin.
*/
void stop() throws IOException;
void stop() throws PluginException;
/**
* Returns true if the plugin is running.

View File

@@ -0,0 +1,15 @@
package org.briarproject.bramble.api.plugin;
/**
* An exception that indicates an error starting or stopping a {@link Plugin}.
*/
public class PluginException extends Exception {
public PluginException() {
super();
}
public PluginException(Throwable cause) {
super(cause);
}
}

View File

@@ -3,7 +3,7 @@ package org.briarproject.bramble.api.sync;
import java.util.Collection;
/**
* A packet acknowledging receipt of one or more {@link Message Messages}.
* A record acknowledging receipt of one or more {@link Message Messages}.
*/
public class Ack {

View File

@@ -1,5 +1,7 @@
package org.briarproject.bramble.api.sync;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_GROUP_DESCRIPTOR_LENGTH;
public class Group {
public enum Visibility {
@@ -13,6 +15,8 @@ public class Group {
private final byte[] descriptor;
public Group(GroupId id, ClientId clientId, byte[] descriptor) {
if (descriptor.length > MAX_GROUP_DESCRIPTOR_LENGTH)
throw new IllegalArgumentException();
this.id = id;
this.clientId = clientId;
this.descriptor = descriptor;

View File

@@ -3,7 +3,7 @@ package org.briarproject.bramble.api.sync;
import java.util.Collection;
/**
* A packet offering the recipient one or more {@link Message Messages}.
* A record offering the recipient one or more {@link Message Messages}.
*/
public class Offer {

View File

@@ -5,7 +5,7 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.io.IOException;
@NotNullByDefault
public interface PacketReader {
public interface RecordReader {
boolean eof() throws IOException;
@@ -24,4 +24,5 @@ public interface PacketReader {
boolean hasRequest() throws IOException;
Request readRequest() throws IOException;
}

View File

@@ -5,7 +5,7 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.io.InputStream;
@NotNullByDefault
public interface PacketReaderFactory {
public interface RecordReaderFactory {
PacketReader createPacketReader(InputStream in);
RecordReader createRecordReader(InputStream in);
}

View File

@@ -1,12 +1,13 @@
package org.briarproject.bramble.api.sync;
/**
* Packet types for the sync protocol.
* Record types for the sync protocol.
*/
public interface PacketTypes {
public interface RecordTypes {
byte ACK = 0;
byte MESSAGE = 1;
byte OFFER = 2;
byte REQUEST = 3;
}

View File

@@ -5,7 +5,7 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.io.IOException;
@NotNullByDefault
public interface PacketWriter {
public interface RecordWriter {
void writeAck(Ack a) throws IOException;

View File

@@ -5,7 +5,7 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.io.OutputStream;
@NotNullByDefault
public interface PacketWriterFactory {
public interface RecordWriterFactory {
PacketWriter createPacketWriter(OutputStream out);
RecordWriter createRecordWriter(OutputStream out);
}

View File

@@ -3,7 +3,7 @@ package org.briarproject.bramble.api.sync;
import java.util.Collection;
/**
* A packet requesting one or more {@link Message Messages} from the recipient.
* A record requesting one or more {@link Message Messages} from the recipient.
*/
public class Request {

View File

@@ -10,19 +10,17 @@ public interface SyncConstants {
byte PROTOCOL_VERSION = 0;
/**
* The length of the packet header in bytes.
* The length of the record header in bytes.
*/
int PACKET_HEADER_LENGTH = 4;
int RECORD_HEADER_LENGTH = 4;
/**
* The maximum length of the packet payload in bytes.
* The maximum length of the record payload in bytes.
*/
int MAX_PACKET_PAYLOAD_LENGTH = 32 * 1024; // 32 KiB
int MAX_RECORD_PAYLOAD_LENGTH = 48 * 1024; // 48 KiB
/**
* The maximum length of a message in bytes.
*/
int MAX_MESSAGE_LENGTH = MAX_PACKET_PAYLOAD_LENGTH - PACKET_HEADER_LENGTH;
/** The maximum length of a group descriptor in bytes. */
int MAX_GROUP_DESCRIPTOR_LENGTH = 16 * 1024; // 16 KiB
/**
* The length of the message header in bytes.
@@ -32,10 +30,15 @@ public interface SyncConstants {
/**
* The maximum length of a message body in bytes.
*/
int MAX_MESSAGE_BODY_LENGTH = MAX_MESSAGE_LENGTH - MESSAGE_HEADER_LENGTH;
int MAX_MESSAGE_BODY_LENGTH = 32 * 1024; // 32 KiB
/**
* The maximum number of message IDs in an ack, offer or request packet.
* The maximum length of a message in bytes.
*/
int MAX_MESSAGE_IDS = MAX_PACKET_PAYLOAD_LENGTH / UniqueId.LENGTH;
int MAX_MESSAGE_LENGTH = MESSAGE_HEADER_LENGTH + MAX_MESSAGE_BODY_LENGTH;
/**
* The maximum number of message IDs in an ack, offer or request record.
*/
int MAX_MESSAGE_IDS = MAX_RECORD_PAYLOAD_LENGTH / UniqueId.LENGTH;
}

View File

@@ -5,7 +5,7 @@ import java.io.IOException;
public interface SyncSession {
/**
* Runs the session. This method returns when there are no more packets to
* Runs the session. This method returns when there are no more records to
* send or receive, or when the {@link #interrupt()} method has been called.
*/
void run() throws IOException;

View File

@@ -1,9 +1,7 @@
package org.briarproject.bramble.data;
package org.briarproject.bramble.api.data;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.api.Bytes;
import org.briarproject.bramble.api.data.BdfDictionary;
import org.briarproject.bramble.api.data.BdfEntry;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import java.util.Collections;
@@ -15,7 +13,7 @@ import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class BdfDictionaryTest extends BriarTestCase {
public class BdfDictionaryTest extends BrambleTestCase {
@Test
public void testConstructors() {

View File

@@ -1,11 +1,8 @@
package org.briarproject.bramble.data;
package org.briarproject.bramble.api.data;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.api.Bytes;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.data.BdfDictionary;
import org.briarproject.bramble.api.data.BdfEntry;
import org.briarproject.bramble.api.data.BdfList;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import java.util.Arrays;
@@ -15,7 +12,7 @@ import static org.briarproject.bramble.api.data.BdfDictionary.NULL_VALUE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class BdfListTest extends BriarTestCase {
public class BdfListTest extends BrambleTestCase {
@Test
public void testConstructors() {

View File

@@ -1,9 +1,10 @@
package org.briarproject;
package org.briarproject.bramble.test;
import org.jmock.Mockery;
import org.junit.After;
public abstract class BriarMockTestCase extends BriarTestCase {
public abstract class BrambleMockTestCase extends
BrambleTestCase {
protected final Mockery context = new Mockery();

View File

@@ -1,12 +1,12 @@
package org.briarproject;
package org.briarproject.bramble.test;
import java.lang.Thread.UncaughtExceptionHandler;
import static org.junit.Assert.fail;
public abstract class BriarTestCase {
public abstract class BrambleTestCase {
public BriarTestCase() {
public BrambleTestCase() {
// Ensure exceptions thrown on worker threads cause tests to fail
UncaughtExceptionHandler fail = new UncaughtExceptionHandler() {
@Override

View File

@@ -1,19 +1,13 @@
package org.briarproject;
package org.briarproject.bramble.test;
import org.briarproject.bramble.api.UniqueId;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.sync.GroupId;
import org.briarproject.bramble.util.IoUtils;
import org.briarproject.briar.api.client.MessageTracker;
import org.briarproject.briar.api.client.MessageTracker.GroupCount;
import java.io.File;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
public class TestUtils {
private static final AtomicInteger nextTestDir =
@@ -51,19 +45,4 @@ public class TestUtils {
return new SecretKey(getRandomBytes(SecretKey.LENGTH));
}
public static void assertGroupCount(MessageTracker tracker, GroupId g,
long msgCount, long unreadCount, long latestMsgTime)
throws DbException {
GroupCount groupCount = tracker.getGroupCount(g);
assertEquals(msgCount, groupCount.getMsgCount());
assertEquals(unreadCount, groupCount.getUnreadCount());
assertEquals(latestMsgTime, groupCount.getLatestMsgTime());
}
public static void assertGroupCount(MessageTracker tracker, GroupId g,
long msgCount, long unreadCount) throws DbException {
GroupCount c1 = tracker.getGroupCount(g);
assertEquals(msgCount, c1.getMsgCount());
assertEquals(unreadCount, c1.getUnreadCount());
}
}

View File

@@ -1,3 +1,4 @@
bin
build
test.tmp
.settings

View File

@@ -1,4 +1,8 @@
apply plugin: 'java'
plugins {
id "java"
id "net.ltgt.apt" version "0.9"
id "idea"
}
sourceCompatibility = 1.6
targetCompatibility = 1.6
@@ -9,6 +13,8 @@ dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
compile 'com.madgag.spongycastle:core:1.54.0.0'
compile 'com.h2database:h2:1.4.190'
testCompile project(path: ':bramble-api', configuration: 'testOutput')
}
dependencyVerification {
@@ -17,3 +23,15 @@ dependencyVerification {
'com.h2database:h2:23ba495a07bbbb3bd6c3084d10a96dad7a23741b8b6d64b213459a784195a98c'
]
}
// needed to make test output available to bramble-j2se
configurations {
testOutput.extendsFrom(testCompile)
}
task jarTest(type: Jar, dependsOn: testClasses) {
from sourceSets.test.output
classifier = 'test'
}
artifacts {
testOutput jarTest
}

View File

@@ -6,6 +6,7 @@ import org.briarproject.bramble.api.contact.ContactManager;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DbException;
import org.briarproject.bramble.api.db.NoSuchContactException;
import org.briarproject.bramble.api.db.Transaction;
import org.briarproject.bramble.api.identity.Author;
import org.briarproject.bramble.api.identity.AuthorId;
@@ -88,6 +89,32 @@ class ContactManagerImpl implements ContactManager {
return contact;
}
@Override
public Contact getContact(AuthorId remoteAuthorId, AuthorId localAuthorId)
throws DbException {
Transaction txn = db.startTransaction(true);
try {
Contact c = getContact(txn, remoteAuthorId, localAuthorId);
db.commitTransaction(txn);
return c;
} finally {
db.endTransaction(txn);
}
}
@Override
public Contact getContact(Transaction txn, AuthorId remoteAuthorId,
AuthorId localAuthorId) throws DbException {
Collection<Contact> contacts =
db.getContactsByAuthorId(txn, remoteAuthorId);
for (Contact c : contacts) {
if (c.getLocalAuthorId().equals(localAuthorId)) {
return c;
}
}
throw new NoSuchContactException();
}
@Override
public Collection<Contact> getActiveContacts() throws DbException {
Collection<Contact> contacts;

View File

@@ -52,7 +52,7 @@ class KeyAgreementProtocol {
void connectionWaiting();
void initialPacketReceived();
void initialRecordReceived();
}
private final Callbacks callbacks;
@@ -117,7 +117,7 @@ class KeyAgreementProtocol {
private byte[] receiveKey() throws AbortException {
byte[] publicKey = transport.receiveKey();
callbacks.initialPacketReceived();
callbacks.initialRecordReceived();
byte[] expected = crypto.deriveKeyCommitment(publicKey);
if (!Arrays.equals(expected, theirPayload.getCommitment()))
throw new AbortException();

View File

@@ -129,7 +129,7 @@ class KeyAgreementTaskImpl extends Thread implements
}
@Override
public void initialPacketReceived() {
public void initialRecordReceived() {
// We send this here instead of when we create the protocol, so that
// if device A makes a connection after getting device B's payload and
// starts its protocol, device A's UI doesn't change to prevent device B

View File

@@ -95,20 +95,30 @@ class KeyAgreementTransport {
out.flush();
}
private byte[] readRecord(byte type) throws AbortException {
byte[] header = readHeader();
if (header[0] != PROTOCOL_VERSION)
throw new AbortException(); // TODO handle?
if (header[1] != type) {
// Unexpected packet
throw new AbortException(header[1] == ABORT);
}
int len = ByteUtils.readUint16(header,
RECORD_HEADER_PAYLOAD_LENGTH_OFFSET);
try {
return readData(len);
} catch (IOException e) {
throw new AbortException(e);
private byte[] readRecord(byte expectedType) throws AbortException {
while (true) {
byte[] header = readHeader();
byte version = header[0], type = header[1];
int len = ByteUtils.readUint16(header,
RECORD_HEADER_PAYLOAD_LENGTH_OFFSET);
// Reject unrecognised protocol version
if (version != PROTOCOL_VERSION) throw new AbortException(false);
if (type == ABORT) throw new AbortException(true);
if (type == expectedType) {
try {
return readData(len);
} catch (IOException e) {
throw new AbortException(e);
}
}
// Reject recognised but unexpected record type
if (type == KEY || type == CONFIRM) throw new AbortException(false);
// Skip unrecognised record type
try {
readData(len);
} catch (IOException e) {
throw new AbortException(e);
}
}
}

View File

@@ -11,6 +11,7 @@ import org.briarproject.bramble.api.plugin.ConnectionManager;
import org.briarproject.bramble.api.plugin.Plugin;
import org.briarproject.bramble.api.plugin.PluginCallback;
import org.briarproject.bramble.api.plugin.PluginConfig;
import org.briarproject.bramble.api.plugin.PluginException;
import org.briarproject.bramble.api.plugin.PluginManager;
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
@@ -30,7 +31,6 @@ import org.briarproject.bramble.api.settings.Settings;
import org.briarproject.bramble.api.settings.SettingsManager;
import org.briarproject.bramble.api.ui.UiCallback;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -193,24 +193,17 @@ class PluginManagerImpl implements PluginManager, Service {
@Override
public void run() {
try {
try {
long start = System.currentTimeMillis();
boolean started = plugin.start();
long duration = System.currentTimeMillis() - start;
if (started) {
if (LOG.isLoggable(INFO)) {
LOG.info("Starting plugin " + plugin.getId()
+ " took " + duration + " ms");
}
} else {
if (LOG.isLoggable(WARNING)) {
LOG.warning("Plugin" + plugin.getId()
+ " did not start");
}
}
} catch (IOException e) {
if (LOG.isLoggable(WARNING))
LOG.log(WARNING, e.toString(), e);
long start = System.currentTimeMillis();
plugin.start();
long duration = System.currentTimeMillis() - start;
if (LOG.isLoggable(INFO)) {
LOG.info("Starting plugin " + plugin.getId() + " took " +
duration + " ms");
}
} catch (PluginException e) {
if (LOG.isLoggable(WARNING)) {
LOG.warning("Plugin " + plugin.getId() + " did not start");
LOG.log(WARNING, e.toString(), e);
}
} finally {
startLatch.countDown();
@@ -246,10 +239,13 @@ class PluginManagerImpl implements PluginManager, Service {
+ " took " + duration + " ms");
}
} catch (InterruptedException e) {
LOG.warning("Interrupted while waiting for plugin to start");
LOG.warning("Interrupted while waiting for plugin to stop");
// This task runs on an executor, so don't reset the interrupt
} catch (IOException e) {
if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
} catch (PluginException e) {
if (LOG.isLoggable(WARNING)) {
LOG.warning("Plugin " + plugin.getId() + " did not stop");
LOG.log(WARNING, e.toString(), e);
}
} finally {
stopLatch.countDown();
}

View File

@@ -101,11 +101,10 @@ abstract class TcpPlugin implements DuplexPlugin {
}
@Override
public boolean start() {
public void start() {
if (used.getAndSet(true)) throw new IllegalStateException();
running = true;
bind();
return true;
}
protected void bind() {

View File

@@ -14,7 +14,7 @@ import org.briarproject.bramble.api.lifecycle.event.ShutdownEvent;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.Ack;
import org.briarproject.bramble.api.sync.Offer;
import org.briarproject.bramble.api.sync.PacketWriter;
import org.briarproject.bramble.api.sync.RecordWriter;
import org.briarproject.bramble.api.sync.Request;
import org.briarproject.bramble.api.sync.SyncSession;
import org.briarproject.bramble.api.sync.event.GroupVisibilityUpdatedEvent;
@@ -37,19 +37,19 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_IDS;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_PACKET_PAYLOAD_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_RECORD_PAYLOAD_LENGTH;
/**
* An outgoing {@link SyncSession} suitable for duplex transports. The session
* offers messages before sending them, keeps its output stream open when there
* are no packets to send, and reacts to events that make packets available to
* are no records to send, and reacts to events that make records available to
* send.
*/
@ThreadSafe
@NotNullByDefault
class DuplexOutgoingSession implements SyncSession, EventListener {
// Check for retransmittable packets once every 60 seconds
// Check for retransmittable records once every 60 seconds
private static final int RETX_QUERY_INTERVAL = 60 * 1000;
private static final Logger LOG =
Logger.getLogger(DuplexOutgoingSession.class.getName());
@@ -67,14 +67,14 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
private final Clock clock;
private final ContactId contactId;
private final int maxLatency, maxIdleTime;
private final PacketWriter packetWriter;
private final RecordWriter recordWriter;
private final BlockingQueue<ThrowingRunnable<IOException>> writerTasks;
private volatile boolean interrupted = false;
DuplexOutgoingSession(DatabaseComponent db, Executor dbExecutor,
EventBus eventBus, Clock clock, ContactId contactId, int maxLatency,
int maxIdleTime, PacketWriter packetWriter) {
int maxIdleTime, RecordWriter recordWriter) {
this.db = db;
this.dbExecutor = dbExecutor;
this.eventBus = eventBus;
@@ -82,7 +82,7 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
this.contactId = contactId;
this.maxLatency = maxLatency;
this.maxIdleTime = maxIdleTime;
this.packetWriter = packetWriter;
this.recordWriter = recordWriter;
writerTasks = new LinkedBlockingQueue<ThrowingRunnable<IOException>>();
}
@@ -91,7 +91,7 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
public void run() throws IOException {
eventBus.addListener(this);
try {
// Start a query for each type of packet
// Start a query for each type of record
dbExecutor.execute(new GenerateAck());
dbExecutor.execute(new GenerateBatch());
dbExecutor.execute(new GenerateOffer());
@@ -100,33 +100,33 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
long nextKeepalive = now + maxIdleTime;
long nextRetxQuery = now + RETX_QUERY_INTERVAL;
boolean dataToFlush = true;
// Write packets until interrupted
// Write records until interrupted
try {
while (!interrupted) {
// Work out how long we should wait for a packet
// Work out how long we should wait for a record
now = clock.currentTimeMillis();
long wait = Math.min(nextKeepalive, nextRetxQuery) - now;
if (wait < 0) wait = 0;
// Flush any unflushed data if we're going to wait
if (wait > 0 && dataToFlush && writerTasks.isEmpty()) {
packetWriter.flush();
recordWriter.flush();
dataToFlush = false;
nextKeepalive = now + maxIdleTime;
}
// Wait for a packet
// Wait for a record
ThrowingRunnable<IOException> task = writerTasks.poll(wait,
MILLISECONDS);
if (task == null) {
now = clock.currentTimeMillis();
if (now >= nextRetxQuery) {
// Check for retransmittable packets
// Check for retransmittable records
dbExecutor.execute(new GenerateBatch());
dbExecutor.execute(new GenerateOffer());
nextRetxQuery = now + RETX_QUERY_INTERVAL;
}
if (now >= nextKeepalive) {
// Flush the stream to keep it alive
packetWriter.flush();
recordWriter.flush();
dataToFlush = false;
nextKeepalive = now + maxIdleTime;
}
@@ -137,9 +137,9 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
dataToFlush = true;
}
}
if (dataToFlush) packetWriter.flush();
if (dataToFlush) recordWriter.flush();
} catch (InterruptedException e) {
LOG.info("Interrupted while waiting for a packet to write");
LOG.info("Interrupted while waiting for a record to write");
Thread.currentThread().interrupt();
}
} finally {
@@ -215,7 +215,7 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
@Override
public void run() throws IOException {
if (interrupted) return;
packetWriter.writeAck(ack);
recordWriter.writeAck(ack);
LOG.info("Sent ack");
dbExecutor.execute(new GenerateAck());
}
@@ -232,7 +232,7 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
Transaction txn = db.startTransaction(false);
try {
b = db.generateRequestedBatch(txn, contactId,
MAX_PACKET_PAYLOAD_LENGTH, maxLatency);
MAX_RECORD_PAYLOAD_LENGTH, maxLatency);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
@@ -259,7 +259,7 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
@Override
public void run() throws IOException {
if (interrupted) return;
for (byte[] raw : batch) packetWriter.writeMessage(raw);
for (byte[] raw : batch) recordWriter.writeMessage(raw);
LOG.info("Sent batch");
dbExecutor.execute(new GenerateBatch());
}
@@ -303,7 +303,7 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
@Override
public void run() throws IOException {
if (interrupted) return;
packetWriter.writeOffer(offer);
recordWriter.writeOffer(offer);
LOG.info("Sent offer");
dbExecutor.execute(new GenerateOffer());
}
@@ -346,7 +346,7 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
@Override
public void run() throws IOException {
if (interrupted) return;
packetWriter.writeRequest(request);
recordWriter.writeRequest(request);
LOG.info("Sent request");
dbExecutor.execute(new GenerateRequest());
}

View File

@@ -16,7 +16,7 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.Ack;
import org.briarproject.bramble.api.sync.Message;
import org.briarproject.bramble.api.sync.Offer;
import org.briarproject.bramble.api.sync.PacketReader;
import org.briarproject.bramble.api.sync.RecordReader;
import org.briarproject.bramble.api.sync.Request;
import org.briarproject.bramble.api.sync.SyncSession;
@@ -42,18 +42,18 @@ class IncomingSession implements SyncSession, EventListener {
private final Executor dbExecutor;
private final EventBus eventBus;
private final ContactId contactId;
private final PacketReader packetReader;
private final RecordReader recordReader;
private volatile boolean interrupted = false;
IncomingSession(DatabaseComponent db, Executor dbExecutor,
EventBus eventBus, ContactId contactId,
PacketReader packetReader) {
RecordReader recordReader) {
this.db = db;
this.dbExecutor = dbExecutor;
this.eventBus = eventBus;
this.contactId = contactId;
this.packetReader = packetReader;
this.recordReader = recordReader;
}
@IoExecutor
@@ -61,21 +61,22 @@ class IncomingSession implements SyncSession, EventListener {
public void run() throws IOException {
eventBus.addListener(this);
try {
// Read packets until interrupted or EOF
while (!interrupted && !packetReader.eof()) {
if (packetReader.hasAck()) {
Ack a = packetReader.readAck();
// Read records until interrupted or EOF
while (!interrupted && !recordReader.eof()) {
if (recordReader.hasAck()) {
Ack a = recordReader.readAck();
dbExecutor.execute(new ReceiveAck(a));
} else if (packetReader.hasMessage()) {
Message m = packetReader.readMessage();
} else if (recordReader.hasMessage()) {
Message m = recordReader.readMessage();
dbExecutor.execute(new ReceiveMessage(m));
} else if (packetReader.hasOffer()) {
Offer o = packetReader.readOffer();
} else if (recordReader.hasOffer()) {
Offer o = recordReader.readOffer();
dbExecutor.execute(new ReceiveOffer(o));
} else if (packetReader.hasRequest()) {
Request r = packetReader.readRequest();
} else if (recordReader.hasRequest()) {
Request r = recordReader.readRequest();
dbExecutor.execute(new ReceiveRequest(r));
} else {
// unknown records are ignored in RecordReader#eof()
throw new FormatException();
}
}

View File

@@ -30,11 +30,15 @@ class MessageFactoryImpl implements MessageFactory {
public Message createMessage(GroupId g, long timestamp, byte[] body) {
if (body.length > MAX_MESSAGE_BODY_LENGTH)
throw new IllegalArgumentException();
byte[] timeBytes = new byte[ByteUtils.INT_64_BYTES];
ByteUtils.writeUint64(timestamp, timeBytes, 0);
byte[] idHash =
crypto.hash(MessageId.LABEL, g.getBytes(), timeBytes, body);
MessageId id = new MessageId(idHash);
byte[] raw = new byte[MESSAGE_HEADER_LENGTH + body.length];
System.arraycopy(g.getBytes(), 0, raw, 0, UniqueId.LENGTH);
ByteUtils.writeUint64(timestamp, raw, UniqueId.LENGTH);
System.arraycopy(body, 0, raw, MESSAGE_HEADER_LENGTH, body.length);
MessageId id = new MessageId(crypto.hash(MessageId.LABEL, raw));
return new Message(id, g, timestamp, raw);
}

View File

@@ -1,28 +0,0 @@
package org.briarproject.bramble.sync;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.PacketReader;
import org.briarproject.bramble.api.sync.PacketReaderFactory;
import java.io.InputStream;
import javax.annotation.concurrent.Immutable;
import javax.inject.Inject;
@Immutable
@NotNullByDefault
class PacketReaderFactoryImpl implements PacketReaderFactory {
private final CryptoComponent crypto;
@Inject
PacketReaderFactoryImpl(CryptoComponent crypto) {
this.crypto = crypto;
}
@Override
public PacketReader createPacketReader(InputStream in) {
return new PacketReaderImpl(crypto, in);
}
}

View File

@@ -1,16 +0,0 @@
package org.briarproject.bramble.sync;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.PacketWriter;
import org.briarproject.bramble.api.sync.PacketWriterFactory;
import java.io.OutputStream;
@NotNullByDefault
class PacketWriterFactoryImpl implements PacketWriterFactory {
@Override
public PacketWriter createPacketWriter(OutputStream out) {
return new PacketWriterImpl(out);
}
}

View File

@@ -0,0 +1,28 @@
package org.briarproject.bramble.sync;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.MessageFactory;
import org.briarproject.bramble.api.sync.RecordReader;
import org.briarproject.bramble.api.sync.RecordReaderFactory;
import java.io.InputStream;
import javax.annotation.concurrent.Immutable;
import javax.inject.Inject;
@Immutable
@NotNullByDefault
class RecordReaderFactoryImpl implements RecordReaderFactory {
private final MessageFactory messageFactory;
@Inject
RecordReaderFactoryImpl(MessageFactory messageFactory) {
this.messageFactory = messageFactory;
}
@Override
public RecordReader createRecordReader(InputStream in) {
return new RecordReaderImpl(messageFactory, in);
}
}

View File

@@ -2,14 +2,14 @@ package org.briarproject.bramble.sync;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.UniqueId;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.Ack;
import org.briarproject.bramble.api.sync.GroupId;
import org.briarproject.bramble.api.sync.Message;
import org.briarproject.bramble.api.sync.MessageFactory;
import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.api.sync.Offer;
import org.briarproject.bramble.api.sync.PacketReader;
import org.briarproject.bramble.api.sync.RecordReader;
import org.briarproject.bramble.api.sync.Request;
import org.briarproject.bramble.util.ByteUtils;
@@ -20,66 +20,84 @@ import java.util.List;
import javax.annotation.concurrent.NotThreadSafe;
import static org.briarproject.bramble.api.sync.PacketTypes.ACK;
import static org.briarproject.bramble.api.sync.PacketTypes.MESSAGE;
import static org.briarproject.bramble.api.sync.PacketTypes.OFFER;
import static org.briarproject.bramble.api.sync.PacketTypes.REQUEST;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_PACKET_PAYLOAD_LENGTH;
import static org.briarproject.bramble.api.sync.RecordTypes.ACK;
import static org.briarproject.bramble.api.sync.RecordTypes.MESSAGE;
import static org.briarproject.bramble.api.sync.RecordTypes.OFFER;
import static org.briarproject.bramble.api.sync.RecordTypes.REQUEST;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_RECORD_PAYLOAD_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.MESSAGE_HEADER_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.PACKET_HEADER_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.api.sync.SyncConstants.RECORD_HEADER_LENGTH;
@NotThreadSafe
@NotNullByDefault
class PacketReaderImpl implements PacketReader {
class RecordReaderImpl implements RecordReader {
private enum State { BUFFER_EMPTY, BUFFER_FULL, EOF }
private enum State {BUFFER_EMPTY, BUFFER_FULL, EOF}
private final CryptoComponent crypto;
private final MessageFactory messageFactory;
private final InputStream in;
private final byte[] header, payload;
private State state = State.BUFFER_EMPTY;
private int payloadLength = 0;
PacketReaderImpl(CryptoComponent crypto, InputStream in) {
this.crypto = crypto;
RecordReaderImpl(MessageFactory messageFactory, InputStream in) {
this.messageFactory = messageFactory;
this.in = in;
header = new byte[PACKET_HEADER_LENGTH];
payload = new byte[MAX_PACKET_PAYLOAD_LENGTH];
header = new byte[RECORD_HEADER_LENGTH];
payload = new byte[MAX_RECORD_PAYLOAD_LENGTH];
}
private void readPacket() throws IOException {
private void readRecord() throws IOException {
if (state != State.BUFFER_EMPTY) throw new IllegalStateException();
// Read the header
int offset = 0;
while (offset < PACKET_HEADER_LENGTH) {
int read = in.read(header, offset, PACKET_HEADER_LENGTH - offset);
if (read == -1) {
if (offset > 0) throw new FormatException();
state = State.EOF;
while (true) {
// Read the header
int offset = 0;
while (offset < RECORD_HEADER_LENGTH) {
int read =
in.read(header, offset, RECORD_HEADER_LENGTH - offset);
if (read == -1) {
if (offset > 0) throw new FormatException();
state = State.EOF;
return;
}
offset += read;
}
byte version = header[0], type = header[1];
payloadLength = ByteUtils.readUint16(header, 2);
// Check the protocol version
if (version != PROTOCOL_VERSION) throw new FormatException();
// Check the payload length
if (payloadLength > MAX_RECORD_PAYLOAD_LENGTH)
throw new FormatException();
// Read the payload
offset = 0;
while (offset < payloadLength) {
int read = in.read(payload, offset, payloadLength - offset);
if (read == -1) throw new FormatException();
offset += read;
}
state = State.BUFFER_FULL;
// Return if this is a known record type, otherwise continue
if (type == ACK || type == MESSAGE || type == OFFER ||
type == REQUEST) {
return;
}
offset += read;
}
// Check the protocol version
if (header[0] != PROTOCOL_VERSION) throw new FormatException();
// Read the payload length
payloadLength = ByteUtils.readUint16(header, 2);
if (payloadLength > MAX_PACKET_PAYLOAD_LENGTH) throw new FormatException();
// Read the payload
offset = 0;
while (offset < payloadLength) {
int read = in.read(payload, offset, payloadLength - offset);
if (read == -1) throw new FormatException();
offset += read;
}
state = State.BUFFER_FULL;
}
/**
* Returns true if there's another record available or false if we've
* reached the end of the input stream.
* <p>
* If a record is available, it's been read into the buffer by the time
* eof() returns, so the method that called eof() can access the record
* from the buffer, for example to check its type or extract its payload.
*/
@Override
public boolean eof() throws IOException {
if (state == State.BUFFER_EMPTY) readPacket();
if (state == State.BUFFER_EMPTY) readRecord();
if (state == State.BUFFER_EMPTY) throw new IllegalStateException();
return state == State.EOF;
}
@@ -124,13 +142,12 @@ class PacketReaderImpl implements PacketReader {
// Timestamp
long timestamp = ByteUtils.readUint64(payload, UniqueId.LENGTH);
if (timestamp < 0) throw new FormatException();
// Raw message
byte[] raw = new byte[payloadLength];
System.arraycopy(payload, 0, raw, 0, payloadLength);
// Body
byte[] body = new byte[payloadLength - MESSAGE_HEADER_LENGTH];
System.arraycopy(payload, MESSAGE_HEADER_LENGTH, body, 0,
payloadLength - MESSAGE_HEADER_LENGTH);
state = State.BUFFER_EMPTY;
// Message ID
MessageId messageId = new MessageId(crypto.hash(MessageId.LABEL, raw));
return new Message(messageId, groupId, timestamp, raw);
return messageFactory.createMessage(groupId, timestamp, body);
}
@Override
@@ -154,4 +171,5 @@ class PacketReaderImpl implements PacketReader {
if (!hasRequest()) throw new FormatException();
return new Request(readMessageIds());
}
}

View File

@@ -0,0 +1,16 @@
package org.briarproject.bramble.sync;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.RecordWriter;
import org.briarproject.bramble.api.sync.RecordWriterFactory;
import java.io.OutputStream;
@NotNullByDefault
class RecordWriterFactoryImpl implements RecordWriterFactory {
@Override
public RecordWriter createRecordWriter(OutputStream out) {
return new RecordWriterImpl(out);
}
}

View File

@@ -4,8 +4,8 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.Ack;
import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.api.sync.Offer;
import org.briarproject.bramble.api.sync.PacketTypes;
import org.briarproject.bramble.api.sync.PacketWriter;
import org.briarproject.bramble.api.sync.RecordTypes;
import org.briarproject.bramble.api.sync.RecordWriter;
import org.briarproject.bramble.api.sync.Request;
import org.briarproject.bramble.util.ByteUtils;
@@ -15,30 +15,30 @@ import java.io.OutputStream;
import javax.annotation.concurrent.NotThreadSafe;
import static org.briarproject.bramble.api.sync.PacketTypes.ACK;
import static org.briarproject.bramble.api.sync.PacketTypes.OFFER;
import static org.briarproject.bramble.api.sync.PacketTypes.REQUEST;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_PACKET_PAYLOAD_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.PACKET_HEADER_LENGTH;
import static org.briarproject.bramble.api.sync.RecordTypes.ACK;
import static org.briarproject.bramble.api.sync.RecordTypes.OFFER;
import static org.briarproject.bramble.api.sync.RecordTypes.REQUEST;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_RECORD_PAYLOAD_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.RECORD_HEADER_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.PROTOCOL_VERSION;
@NotThreadSafe
@NotNullByDefault
class PacketWriterImpl implements PacketWriter {
class RecordWriterImpl implements RecordWriter {
private final OutputStream out;
private final byte[] header;
private final ByteArrayOutputStream payload;
PacketWriterImpl(OutputStream out) {
RecordWriterImpl(OutputStream out) {
this.out = out;
header = new byte[PACKET_HEADER_LENGTH];
header = new byte[RECORD_HEADER_LENGTH];
header[0] = PROTOCOL_VERSION;
payload = new ByteArrayOutputStream(MAX_PACKET_PAYLOAD_LENGTH);
payload = new ByteArrayOutputStream(MAX_RECORD_PAYLOAD_LENGTH);
}
private void writePacket(byte packetType) throws IOException {
header[1] = packetType;
private void writeRecord(byte recordType) throws IOException {
header[1] = recordType;
ByteUtils.writeUint16(payload.size(), header, 2);
out.write(header);
payload.writeTo(out);
@@ -49,12 +49,12 @@ class PacketWriterImpl implements PacketWriter {
public void writeAck(Ack a) throws IOException {
if (payload.size() != 0) throw new IllegalStateException();
for (MessageId m : a.getMessageIds()) payload.write(m.getBytes());
writePacket(ACK);
writeRecord(ACK);
}
@Override
public void writeMessage(byte[] raw) throws IOException {
header[1] = PacketTypes.MESSAGE;
header[1] = RecordTypes.MESSAGE;
ByteUtils.writeUint16(raw.length, header, 2);
out.write(header);
out.write(raw);
@@ -64,14 +64,14 @@ class PacketWriterImpl implements PacketWriter {
public void writeOffer(Offer o) throws IOException {
if (payload.size() != 0) throw new IllegalStateException();
for (MessageId m : o.getMessageIds()) payload.write(m.getBytes());
writePacket(OFFER);
writeRecord(OFFER);
}
@Override
public void writeRequest(Request r) throws IOException {
if (payload.size() != 0) throw new IllegalStateException();
for (MessageId m : r.getMessageIds()) payload.write(m.getBytes());
writePacket(REQUEST);
writeRecord(REQUEST);
}
@Override

View File

@@ -13,7 +13,7 @@ import org.briarproject.bramble.api.lifecycle.IoExecutor;
import org.briarproject.bramble.api.lifecycle.event.ShutdownEvent;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.Ack;
import org.briarproject.bramble.api.sync.PacketWriter;
import org.briarproject.bramble.api.sync.RecordWriter;
import org.briarproject.bramble.api.sync.SyncSession;
import java.io.IOException;
@@ -29,12 +29,12 @@ import javax.annotation.concurrent.ThreadSafe;
import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_IDS;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_PACKET_PAYLOAD_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_RECORD_PAYLOAD_LENGTH;
/**
* An outgoing {@link SyncSession} suitable for simplex transports. The session
* sends messages without offering them first, and closes its output stream
* when there are no more packets to send.
* when there are no more records to send.
*/
@ThreadSafe
@NotNullByDefault
@@ -55,7 +55,7 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
private final EventBus eventBus;
private final ContactId contactId;
private final int maxLatency;
private final PacketWriter packetWriter;
private final RecordWriter recordWriter;
private final AtomicInteger outstandingQueries;
private final BlockingQueue<ThrowingRunnable<IOException>> writerTasks;
@@ -63,14 +63,14 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
SimplexOutgoingSession(DatabaseComponent db, Executor dbExecutor,
EventBus eventBus, ContactId contactId,
int maxLatency, PacketWriter packetWriter) {
int maxLatency, RecordWriter recordWriter) {
this.db = db;
this.dbExecutor = dbExecutor;
this.eventBus = eventBus;
this.contactId = contactId;
this.maxLatency = maxLatency;
this.packetWriter = packetWriter;
outstandingQueries = new AtomicInteger(2); // One per type of packet
this.recordWriter = recordWriter;
outstandingQueries = new AtomicInteger(2); // One per type of record
writerTasks = new LinkedBlockingQueue<ThrowingRunnable<IOException>>();
}
@@ -79,19 +79,19 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
public void run() throws IOException {
eventBus.addListener(this);
try {
// Start a query for each type of packet
// Start a query for each type of record
dbExecutor.execute(new GenerateAck());
dbExecutor.execute(new GenerateBatch());
// Write packets until interrupted or no more packets to write
// Write records until interrupted or no more records to write
try {
while (!interrupted) {
ThrowingRunnable<IOException> task = writerTasks.take();
if (task == CLOSE) break;
task.run();
}
packetWriter.flush();
recordWriter.flush();
} catch (InterruptedException e) {
LOG.info("Interrupted while waiting for a packet to write");
LOG.info("Interrupted while waiting for a record to write");
Thread.currentThread().interrupt();
}
} finally {
@@ -157,7 +157,7 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
@Override
public void run() throws IOException {
if (interrupted) return;
packetWriter.writeAck(ack);
recordWriter.writeAck(ack);
LOG.info("Sent ack");
dbExecutor.execute(new GenerateAck());
}
@@ -174,7 +174,7 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
Transaction txn = db.startTransaction(false);
try {
b = db.generateBatch(txn, contactId,
MAX_PACKET_PAYLOAD_LENGTH, maxLatency);
MAX_RECORD_PAYLOAD_LENGTH, maxLatency);
db.commitTransaction(txn);
} finally {
db.endTransaction(txn);
@@ -202,7 +202,7 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
@Override
public void run() throws IOException {
if (interrupted) return;
for (byte[] raw : batch) packetWriter.writeMessage(raw);
for (byte[] raw : batch) recordWriter.writeMessage(raw);
LOG.info("Sent batch");
dbExecutor.execute(new GenerateBatch());
}

View File

@@ -7,8 +7,8 @@ import org.briarproject.bramble.api.event.EventBus;
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
import org.briarproject.bramble.api.sync.GroupFactory;
import org.briarproject.bramble.api.sync.MessageFactory;
import org.briarproject.bramble.api.sync.PacketReaderFactory;
import org.briarproject.bramble.api.sync.PacketWriterFactory;
import org.briarproject.bramble.api.sync.RecordReaderFactory;
import org.briarproject.bramble.api.sync.RecordWriterFactory;
import org.briarproject.bramble.api.sync.SyncSessionFactory;
import org.briarproject.bramble.api.sync.ValidationManager;
import org.briarproject.bramble.api.system.Clock;
@@ -40,23 +40,24 @@ public class SyncModule {
}
@Provides
PacketReaderFactory providePacketReaderFactory(CryptoComponent crypto) {
return new PacketReaderFactoryImpl(crypto);
RecordReaderFactory provideRecordReaderFactory(
RecordReaderFactoryImpl recordReaderFactory) {
return recordReaderFactory;
}
@Provides
PacketWriterFactory providePacketWriterFactory() {
return new PacketWriterFactoryImpl();
RecordWriterFactory provideRecordWriterFactory() {
return new RecordWriterFactoryImpl();
}
@Provides
@Singleton
SyncSessionFactory provideSyncSessionFactory(DatabaseComponent db,
@DatabaseExecutor Executor dbExecutor, EventBus eventBus,
Clock clock, PacketReaderFactory packetReaderFactory,
PacketWriterFactory packetWriterFactory) {
Clock clock, RecordReaderFactory recordReaderFactory,
RecordWriterFactory recordWriterFactory) {
return new SyncSessionFactoryImpl(db, dbExecutor, eventBus, clock,
packetReaderFactory, packetWriterFactory);
recordReaderFactory, recordWriterFactory);
}
@Provides

View File

@@ -5,10 +5,10 @@ import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.DatabaseExecutor;
import org.briarproject.bramble.api.event.EventBus;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.PacketReader;
import org.briarproject.bramble.api.sync.PacketReaderFactory;
import org.briarproject.bramble.api.sync.PacketWriter;
import org.briarproject.bramble.api.sync.PacketWriterFactory;
import org.briarproject.bramble.api.sync.RecordReader;
import org.briarproject.bramble.api.sync.RecordReaderFactory;
import org.briarproject.bramble.api.sync.RecordWriter;
import org.briarproject.bramble.api.sync.RecordWriterFactory;
import org.briarproject.bramble.api.sync.SyncSession;
import org.briarproject.bramble.api.sync.SyncSessionFactory;
import org.briarproject.bramble.api.system.Clock;
@@ -28,41 +28,41 @@ class SyncSessionFactoryImpl implements SyncSessionFactory {
private final Executor dbExecutor;
private final EventBus eventBus;
private final Clock clock;
private final PacketReaderFactory packetReaderFactory;
private final PacketWriterFactory packetWriterFactory;
private final RecordReaderFactory recordReaderFactory;
private final RecordWriterFactory recordWriterFactory;
@Inject
SyncSessionFactoryImpl(DatabaseComponent db,
@DatabaseExecutor Executor dbExecutor, EventBus eventBus,
Clock clock, PacketReaderFactory packetReaderFactory,
PacketWriterFactory packetWriterFactory) {
Clock clock, RecordReaderFactory recordReaderFactory,
RecordWriterFactory recordWriterFactory) {
this.db = db;
this.dbExecutor = dbExecutor;
this.eventBus = eventBus;
this.clock = clock;
this.packetReaderFactory = packetReaderFactory;
this.packetWriterFactory = packetWriterFactory;
this.recordReaderFactory = recordReaderFactory;
this.recordWriterFactory = recordWriterFactory;
}
@Override
public SyncSession createIncomingSession(ContactId c, InputStream in) {
PacketReader packetReader = packetReaderFactory.createPacketReader(in);
return new IncomingSession(db, dbExecutor, eventBus, c, packetReader);
RecordReader recordReader = recordReaderFactory.createRecordReader(in);
return new IncomingSession(db, dbExecutor, eventBus, c, recordReader);
}
@Override
public SyncSession createSimplexOutgoingSession(ContactId c,
int maxLatency, OutputStream out) {
PacketWriter packetWriter = packetWriterFactory.createPacketWriter(out);
RecordWriter recordWriter = recordWriterFactory.createRecordWriter(out);
return new SimplexOutgoingSession(db, dbExecutor, eventBus, c,
maxLatency, packetWriter);
maxLatency, recordWriter);
}
@Override
public SyncSession createDuplexOutgoingSession(ContactId c, int maxLatency,
int maxIdleTime, OutputStream out) {
PacketWriter packetWriter = packetWriterFactory.createPacketWriter(out);
RecordWriter recordWriter = recordWriterFactory.createRecordWriter(out);
return new DuplexOutgoingSession(db, dbExecutor, eventBus, clock, c,
maxLatency, maxIdleTime, packetWriter);
maxLatency, maxIdleTime, recordWriter);
}
}

View File

@@ -1,6 +1,5 @@
package org.briarproject.bramble.client;
import org.briarproject.ValidatorTestCase;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.client.BdfMessageContext;
import org.briarproject.bramble.api.client.BdfMessageValidator;
@@ -12,6 +11,7 @@ import org.briarproject.bramble.api.sync.Group;
import org.briarproject.bramble.api.sync.InvalidMessageException;
import org.briarproject.bramble.api.sync.Message;
import org.briarproject.bramble.api.sync.MessageContext;
import org.briarproject.bramble.test.ValidatorTestCase;
import org.jmock.Expectations;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;

View File

@@ -1,7 +1,5 @@
package org.briarproject.bramble.client;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.client.ClientHelper;
import org.briarproject.bramble.api.crypto.CryptoComponent;
@@ -21,6 +19,8 @@ import org.briarproject.bramble.api.sync.GroupId;
import org.briarproject.bramble.api.sync.Message;
import org.briarproject.bramble.api.sync.MessageFactory;
import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;
@@ -32,13 +32,13 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.briarproject.TestUtils.getRandomBytes;
import static org.briarproject.TestUtils.getRandomId;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.getRandomId;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class ClientHelperImplTest extends BriarTestCase {
public class ClientHelperImplTest extends BrambleTestCase {
private final Mockery context = new Mockery();
private final DatabaseComponent db = context.mock(DatabaseComponent.class);
@@ -165,7 +165,8 @@ public class ClientHelperImplTest extends BriarTestCase {
@Test
public void testGetMessageMetadataAsDictionaryMap() throws Exception {
final Map<MessageId, BdfDictionary> map = new HashMap<>();
final Map<MessageId, BdfDictionary> map =
new HashMap<MessageId, BdfDictionary>();
map.put(messageId, dictionary);
final Transaction txn = new Transaction(null, true);
@@ -187,7 +188,8 @@ public class ClientHelperImplTest extends BriarTestCase {
@Test
public void testGetMessageMetadataAsDictionaryQuery() throws Exception {
final Map<MessageId, BdfDictionary> map = new HashMap<>();
final Map<MessageId, BdfDictionary> map =
new HashMap<MessageId, BdfDictionary>();
map.put(messageId, dictionary);
final BdfDictionary query =
BdfDictionary.of(new BdfEntry("query", "me"));

View File

@@ -1,15 +1,16 @@
package org.briarproject.bramble.contact;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.api.contact.Contact;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.ContactManager;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.NoSuchContactException;
import org.briarproject.bramble.api.db.Transaction;
import org.briarproject.bramble.api.identity.Author;
import org.briarproject.bramble.api.identity.AuthorId;
import org.briarproject.bramble.api.transport.KeyManager;
import org.briarproject.bramble.test.BrambleMockTestCase;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;
@@ -18,13 +19,13 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import static org.briarproject.TestUtils.getRandomBytes;
import static org.briarproject.TestUtils.getRandomId;
import static org.briarproject.TestUtils.getSecretKey;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.test.TestUtils.getRandomId;
import static org.briarproject.bramble.test.TestUtils.getSecretKey;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ContactManagerImplTest extends BriarTestCase {
public class ContactManagerImplTest extends BrambleMockTestCase {
private final Mockery context = new Mockery();
private final DatabaseComponent db = context.mock(DatabaseComponent.class);
@@ -66,7 +67,6 @@ public class ContactManagerImplTest extends BriarTestCase {
assertEquals(contactId, contactManager
.addContact(remote, local, master, timestamp, alice, verified,
active));
context.assertIsSatisfied();
}
@Test
@@ -82,13 +82,58 @@ public class ContactManagerImplTest extends BriarTestCase {
}});
assertEquals(contact, contactManager.getContact(contactId));
context.assertIsSatisfied();
}
@Test
public void testGetContactByAuthor() throws Exception {
final Transaction txn = new Transaction(null, true);
final Collection<Contact> contacts = Collections.singleton(contact);
context.checking(new Expectations() {{
oneOf(db).startTransaction(true);
will(returnValue(txn));
oneOf(db).getContactsByAuthorId(txn, remote.getId());
will(returnValue(contacts));
oneOf(db).commitTransaction(txn);
oneOf(db).endTransaction(txn);
}});
assertEquals(contact, contactManager.getContact(remote.getId(), local));
}
@Test(expected = NoSuchContactException.class)
public void testGetContactByUnknownAuthor() throws Exception {
final Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{
oneOf(db).startTransaction(true);
will(returnValue(txn));
oneOf(db).getContactsByAuthorId(txn, remote.getId());
will(returnValue(Collections.emptyList()));
oneOf(db).endTransaction(txn);
}});
contactManager.getContact(remote.getId(), local);
}
@Test(expected = NoSuchContactException.class)
public void testGetContactByUnknownLocalAuthor() throws Exception {
final Transaction txn = new Transaction(null, true);
final Collection<Contact> contacts = Collections.singleton(contact);
context.checking(new Expectations() {{
oneOf(db).startTransaction(true);
will(returnValue(txn));
oneOf(db).getContactsByAuthorId(txn, remote.getId());
will(returnValue(contacts));
oneOf(db).endTransaction(txn);
}});
contactManager.getContact(remote.getId(), new AuthorId(getRandomId()));
}
@Test
public void testActiveContacts() throws Exception {
Collection<Contact> activeContacts = Collections.singletonList(contact);
final Collection<Contact> contacts = new ArrayList<>(activeContacts);
final Collection<Contact> contacts =
new ArrayList<Contact>(activeContacts);
contacts.add(new Contact(new ContactId(3), remote, local, true, false));
final Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{
@@ -101,7 +146,6 @@ public class ContactManagerImplTest extends BriarTestCase {
}});
assertEquals(activeContacts, contactManager.getActiveContacts());
context.assertIsSatisfied();
}
@Test
@@ -118,7 +162,6 @@ public class ContactManagerImplTest extends BriarTestCase {
}});
contactManager.removeContact(contactId);
context.assertIsSatisfied();
}
@Test
@@ -129,7 +172,6 @@ public class ContactManagerImplTest extends BriarTestCase {
}});
contactManager.setContactActive(txn, contactId, active);
context.assertIsSatisfied();
}
@Test
@@ -145,7 +187,6 @@ public class ContactManagerImplTest extends BriarTestCase {
}});
assertTrue(contactManager.contactExists(remote.getId(), local));
context.assertIsSatisfied();
}
}

View File

@@ -1,12 +1,12 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class AsciiArmourTest extends BriarTestCase {
public class AsciiArmourTest extends BrambleTestCase {
@Test
public void testWrapOnSingleLine() {

View File

@@ -1,6 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.util.StringUtils;
import org.junit.Test;
@@ -8,7 +8,7 @@ import java.util.Random;
import static org.junit.Assert.assertArrayEquals;
public class Blake2sDigestTest extends BriarTestCase {
public class Blake2sDigestTest extends BrambleTestCase {
// Vectors from BLAKE2 web site: https://blake2.net/blake2s-test.txt
private static final String[][] keyedTestVectors = {

View File

@@ -1,6 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import org.spongycastle.asn1.teletrust.TeleTrusTNamedCurves;
import org.spongycastle.asn1.x9.X9ECParameters;
@@ -20,7 +20,7 @@ import java.security.SecureRandom;
import static org.briarproject.bramble.crypto.EllipticCurveConstants.PARAMETERS;
import static org.junit.Assert.assertEquals;
public class EllipticCurveMultiplicationTest extends BriarTestCase {
public class EllipticCurveMultiplicationTest extends BrambleTestCase {
@Test
public void testMultiplierProducesSameResultsAsDefault() throws Exception {

View File

@@ -69,7 +69,7 @@ public class EllipticCurvePerformanceTest {
ECPublicKeyParameters public2 =
(ECPublicKeyParameters) keyPair2.getPublic();
// Time some ECDH key agreements
List<Long> samples = new ArrayList<>();
List<Long> samples = new ArrayList<Long>();
for (int i = 0; i < SAMPLES; i++) {
ECDHCBasicAgreement agreement = new ECDHCBasicAgreement();
long start = System.nanoTime();
@@ -79,7 +79,7 @@ public class EllipticCurvePerformanceTest {
}
long agreementMedian = median(samples);
// Time some signatures
List<byte[]> signatures = new ArrayList<>();
List<byte[]> signatures = new ArrayList<byte[]>();
samples.clear();
for (int i = 0; i < SAMPLES; i++) {
Digest digest = new Blake2sDigest();

View File

@@ -1,6 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import org.spongycastle.crypto.BlockCipher;
import org.spongycastle.crypto.engines.AESLightEngine;
@@ -9,7 +9,7 @@ import org.spongycastle.crypto.params.KeyParameter;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class FortunaGeneratorTest extends BriarTestCase {
public class FortunaGeneratorTest extends BrambleTestCase {
@Test
public void testCounterInitialisedToOne() {

View File

@@ -1,6 +1,6 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import org.spongycastle.crypto.BlockCipher;
import org.spongycastle.crypto.digests.SHA256Digest;
@@ -13,7 +13,7 @@ import static org.briarproject.bramble.crypto.FortunaSecureRandom.SELF_TEST_VECT
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;
public class FortunaSecureRandomTest extends BriarTestCase {
public class FortunaSecureRandomTest extends BrambleTestCase {
@Test
public void testClassPassesSelfTest() {

View File

@@ -0,0 +1,50 @@
package org.briarproject.bramble.crypto;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestSeedProvider;
import org.briarproject.bramble.test.TestUtils;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
public class HashTest extends BrambleTestCase {
private final CryptoComponent crypto;
private final String label = TestUtils.getRandomString(42);
private final byte[] inputBytes = TestUtils.getRandomBytes(123);
private final byte[] inputBytes1 = TestUtils.getRandomBytes(234);
private final byte[] inputBytes2 = new byte[0];
public HashTest() {
crypto = new CryptoComponentImpl(new TestSeedProvider());
}
@Test
public void testIdenticalInputsProduceIdenticalHashes() {
byte[] hash1 = crypto.hash(label, inputBytes, inputBytes1, inputBytes2);
byte[] hash2 = crypto.hash(label, inputBytes, inputBytes1, inputBytes2);
assertArrayEquals(hash1, hash2);
}
@Test
public void testDifferentInputsProduceDifferentHashes() {
byte[] hash1 = crypto.hash(label, inputBytes, inputBytes1, inputBytes2);
byte[] hash2 = crypto.hash(label, inputBytes2, inputBytes1, inputBytes);
assertFalse(Arrays.equals(hash1, hash2));
}
@Test
public void testDifferentLabelsProduceDifferentHashes() {
String label2 = TestUtils.getRandomString(42);
byte[] hash1 = crypto.hash(label, inputBytes, inputBytes1, inputBytes2);
byte[] hash2 =
crypto.hash(label2, inputBytes, inputBytes1, inputBytes2);
assertFalse(Arrays.equals(hash1, hash2));
}
}

View File

@@ -1,16 +1,16 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.TestSeedProvider;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.KeyPair;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.system.SeedProvider;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestSeedProvider;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class KeyAgreementTest extends BriarTestCase {
public class KeyAgreementTest extends BrambleTestCase {
@Test
public void testDeriveMasterSecret() throws Exception {

View File

@@ -1,12 +1,12 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.TestSeedProvider;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.plugin.TransportId;
import org.briarproject.bramble.api.transport.TransportKeys;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestSeedProvider;
import org.briarproject.bramble.test.TestUtils;
import org.junit.Test;
import java.util.ArrayList;
@@ -16,7 +16,7 @@ import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
public class KeyDerivationTest extends BriarTestCase {
public class KeyDerivationTest extends BrambleTestCase {
private final TransportId transportId = new TransportId("id");
private final CryptoComponent crypto;
@@ -141,7 +141,7 @@ public class KeyDerivationTest extends BriarTestCase {
}
private void assertAllDifferent(TransportKeys... transportKeys) {
List<SecretKey> secretKeys = new ArrayList<>();
List<SecretKey> secretKeys = new ArrayList<SecretKey>();
for (TransportKeys k : transportKeys) {
secretKeys.add(k.getPreviousIncomingKeys().getTagKey());
secretKeys.add(k.getPreviousIncomingKeys().getHeaderKey());

View File

@@ -1,12 +1,12 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.TestSeedProvider;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.crypto.KeyPair;
import org.briarproject.bramble.api.crypto.KeyParser;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestSeedProvider;
import org.briarproject.bramble.test.TestUtils;
import org.junit.Test;
import java.security.GeneralSecurityException;
@@ -16,7 +16,7 @@ import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_SIGNATUR
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;
public class KeyEncodingAndParsingTest extends BriarTestCase {
public class KeyEncodingAndParsingTest extends BrambleTestCase {
private final CryptoComponentImpl crypto =
new CryptoComponentImpl(new TestSeedProvider());

View File

@@ -1,10 +1,10 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.TestSeedProvider;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestSeedProvider;
import org.briarproject.bramble.test.TestUtils;
import org.junit.Test;
import java.util.Arrays;
@@ -12,7 +12,7 @@ import java.util.Arrays;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
public class MacTest extends BriarTestCase {
public class MacTest extends BrambleTestCase {
private final CryptoComponent crypto;

View File

@@ -1,9 +1,9 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.api.crypto.KeyPair;
import org.briarproject.bramble.api.crypto.PrivateKey;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import org.spongycastle.crypto.CryptoException;
@@ -11,7 +11,7 @@ import java.security.SecureRandom;
import static org.junit.Assert.assertArrayEquals;
public class MessageEncrypterTest extends BriarTestCase {
public class MessageEncrypterTest extends BrambleTestCase {
private final SecureRandom random = new SecureRandom();

View File

@@ -1,8 +1,8 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.TestSeedProvider;
import org.briarproject.TestUtils;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestSeedProvider;
import org.briarproject.bramble.test.TestUtils;
import org.junit.Test;
import java.util.Random;
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class PasswordBasedKdfTest extends BriarTestCase {
public class PasswordBasedKdfTest extends BrambleTestCase {
private final CryptoComponentImpl crypto =
new CryptoComponentImpl(new TestSeedProvider());

View File

@@ -1,13 +1,13 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.api.crypto.PasswordStrengthEstimator;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import static org.briarproject.bramble.api.crypto.PasswordStrengthEstimator.QUITE_STRONG;
import static org.junit.Assert.assertTrue;
public class PasswordStrengthEstimatorImplTest extends BriarTestCase {
public class PasswordStrengthEstimatorImplTest extends BrambleTestCase {
@Test
public void testWeakPasswords() {

View File

@@ -1,10 +1,10 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.TestSeedProvider;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.KeyPair;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestSeedProvider;
import org.briarproject.bramble.test.TestUtils;
import org.junit.Test;
import java.util.Arrays;
@@ -13,7 +13,7 @@ import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SignatureTest extends BriarTestCase {
public class SignatureTest extends BrambleTestCase {
private final CryptoComponent crypto;

View File

@@ -1,8 +1,8 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.ByteUtils;
import org.junit.Test;
@@ -18,7 +18,7 @@ import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_H
import static org.briarproject.bramble.util.ByteUtils.INT_16_BYTES;
import static org.junit.Assert.assertArrayEquals;
public class StreamDecrypterImplTest extends BriarTestCase {
public class StreamDecrypterImplTest extends BrambleTestCase {
private final AuthenticatedCipher cipher;
private final SecretKey streamHeaderKey, frameKey;

View File

@@ -1,8 +1,8 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
@@ -13,7 +13,7 @@ import static org.briarproject.bramble.api.transport.TransportConstants.STREAM_H
import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH;
import static org.junit.Assert.assertArrayEquals;
public class StreamEncrypterImplTest extends BriarTestCase {
public class StreamEncrypterImplTest extends BrambleTestCase {
private final AuthenticatedCipher cipher;
private final SecretKey streamHeaderKey, frameKey;

View File

@@ -1,7 +1,7 @@
package org.briarproject.bramble.crypto;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.util.StringUtils;
import org.junit.Test;
@@ -11,7 +11,7 @@ import java.util.Random;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class XSalsa20Poly1305AuthenticatedCipherTest extends BriarTestCase {
public class XSalsa20Poly1305AuthenticatedCipherTest extends BrambleTestCase {
// Test vectors from the NaCl paper
// http://cr.yp.to/highspeed/naclcrypto-20090310.pdf

View File

@@ -1,10 +1,10 @@
package org.briarproject.bramble.data;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.data.BdfDictionary;
import org.briarproject.bramble.api.data.BdfList;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.StringUtils;
import org.junit.Test;
@@ -17,7 +17,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BdfReaderImplTest extends BriarTestCase {
public class BdfReaderImplTest extends BrambleTestCase {
private BdfReaderImpl r = null;

View File

@@ -1,7 +1,7 @@
package org.briarproject.bramble.data;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.StringUtils;
import org.junit.Before;
import org.junit.Test;
@@ -16,7 +16,7 @@ import java.util.Map;
import static org.briarproject.bramble.api.data.BdfDictionary.NULL_VALUE;
import static org.junit.Assert.assertArrayEquals;
public class BdfWriterImplTest extends BriarTestCase {
public class BdfWriterImplTest extends BrambleTestCase {
private ByteArrayOutputStream out = null;
private BdfWriterImpl w = null;
@@ -155,7 +155,7 @@ public class BdfWriterImplTest extends BriarTestCase {
@Test
public void testWriteList() throws IOException {
List<Object> l = new ArrayList<>();
List<Object> l = new ArrayList<Object>();
for (int i = 0; i < 3; i++) l.add(i);
w.writeList(l);
// LIST tag, elements as integers, END tag
@@ -164,7 +164,7 @@ public class BdfWriterImplTest extends BriarTestCase {
@Test
public void testListCanContainNull() throws IOException {
List<Object> l = new ArrayList<>();
List<Object> l = new ArrayList<Object>();
l.add(1);
l.add(null);
l.add(NULL_VALUE);
@@ -177,7 +177,7 @@ public class BdfWriterImplTest extends BriarTestCase {
@Test
public void testWriteDictionary() throws IOException {
// Use LinkedHashMap to get predictable iteration order
Map<String, Object> m = new LinkedHashMap<>();
Map<String, Object> m = new LinkedHashMap<String, Object>();
for (int i = 0; i < 4; i++) m.put(String.valueOf(i), i);
w.writeDictionary(m);
// DICTIONARY tag, keys as strings and values as integers, END tag
@@ -216,12 +216,12 @@ public class BdfWriterImplTest extends BriarTestCase {
@Test
public void testWriteNestedDictionariesAndLists() throws IOException {
Map<String, Object> inner = new LinkedHashMap<>();
Map<String, Object> inner = new LinkedHashMap<String, Object>();
inner.put("bar", new byte[0]);
List<Object> list = new ArrayList<>();
List<Object> list = new ArrayList<Object>();
list.add(1);
list.add(inner);
Map<String, Object> outer = new LinkedHashMap<>();
Map<String, Object> outer = new LinkedHashMap<String, Object>();
outer.put("foo", list);
w.writeDictionary(outer);
// DICTIONARY tag, "foo" as string, LIST tag, 1 as integer,

View File

@@ -1,9 +1,9 @@
package org.briarproject.bramble.data;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.data.BdfDictionary;
import org.briarproject.bramble.api.db.Metadata;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Before;
import org.junit.Test;
@@ -15,7 +15,7 @@ import java.util.Map;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class MetadataEncoderParserIntegrationTest extends BriarTestCase {
public class MetadataEncoderParserIntegrationTest extends BrambleTestCase {
private MetadataEncoderImpl e;
private MetadataParserImpl p;
@@ -99,7 +99,7 @@ public class MetadataEncoderParserIntegrationTest extends BriarTestCase {
@Test
public void testList() throws FormatException {
List<Long> l = new ArrayList<>(4);
List<Long> l = new ArrayList<Long>(4);
l.add(42L);
l.add(1337L);
l.add(Long.MIN_VALUE);
@@ -114,7 +114,7 @@ public class MetadataEncoderParserIntegrationTest extends BriarTestCase {
@Test
public void testDictionary() throws FormatException {
Map<String, Boolean> m = new HashMap<>();
Map<String, Boolean> m = new HashMap<String, Boolean>();
m.put("1", true);
m.put("2", false);
@@ -130,19 +130,19 @@ public class MetadataEncoderParserIntegrationTest extends BriarTestCase {
@Test
public void testComplexDictionary() throws FormatException {
Map<String, List> m = new HashMap<>();
List<String> one = new ArrayList<>(3);
Map<String, List> m = new HashMap<String, List>();
List<String> one = new ArrayList<String>(3);
one.add("\uFDD0");
one.add("\uFDD1");
one.add("\uFDD2");
m.put("One", one);
List<String> two = new ArrayList<>(2);
List<String> two = new ArrayList<String>(2);
two.add("\u0080");
two.add("\uD800\uDC00");
m.put("Two", two);
d.put("test", m);
Map<String, Boolean> m2 = new HashMap<>();
Map<String, Boolean> m2 = new HashMap<String, Boolean>();
m2.put("should be true", true);
d.put("another test", m2);

View File

@@ -1,7 +1,7 @@
package org.briarproject.bramble.db;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -23,7 +23,7 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class BasicH2Test extends BriarTestCase {
public class BasicH2Test extends BrambleTestCase {
private static final String CREATE_TABLE =
"CREATE TABLE foo (uniqueId BINARY(32), name VARCHAR NOT NULL)";
@@ -322,7 +322,7 @@ public class BasicH2Test extends BriarTestCase {
private List<String> getNames() throws SQLException {
String sql = "SELECT name FROM foo ORDER BY uniqueId";
List<String> names = new ArrayList<>();
List<String> names = new ArrayList<String>();
try {
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();

View File

@@ -1,7 +1,5 @@
package org.briarproject.bramble.db;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.contact.Contact;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.event.ContactAddedEvent;
@@ -49,6 +47,8 @@ import org.briarproject.bramble.api.sync.event.MessagesSentEvent;
import org.briarproject.bramble.api.transport.IncomingKeys;
import org.briarproject.bramble.api.transport.OutgoingKeys;
import org.briarproject.bramble.api.transport.TransportKeys;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;
@@ -63,6 +63,7 @@ import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_PUBLIC_K
import static org.briarproject.bramble.api.sync.Group.Visibility.INVISIBLE;
import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED;
import static org.briarproject.bramble.api.sync.Group.Visibility.VISIBLE;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_GROUP_DESCRIPTOR_LENGTH;
import static org.briarproject.bramble.api.sync.ValidationManager.State.DELIVERED;
import static org.briarproject.bramble.api.sync.ValidationManager.State.UNKNOWN;
import static org.briarproject.bramble.api.transport.TransportConstants.REORDERING_WINDOW_SIZE;
@@ -72,7 +73,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
public class DatabaseComponentImplTest extends BriarTestCase {
public class DatabaseComponentImplTest extends BrambleTestCase {
private final Object txn = new Object();
private final ClientId clientId;
@@ -95,7 +96,7 @@ public class DatabaseComponentImplTest extends BriarTestCase {
public DatabaseComponentImplTest() {
clientId = new ClientId(TestUtils.getRandomString(5));
groupId = new GroupId(TestUtils.getRandomId());
byte[] descriptor = new byte[0];
byte[] descriptor = new byte[MAX_GROUP_DESCRIPTOR_LENGTH];
group = new Group(groupId, clientId, descriptor);
authorId = new AuthorId(TestUtils.getRandomId());
author = new Author(authorId, "Alice", new byte[MAX_PUBLIC_KEY_LENGTH]);
@@ -118,8 +119,8 @@ public class DatabaseComponentImplTest extends BriarTestCase {
private DatabaseComponent createDatabaseComponent(Database<Object> database,
EventBus eventBus, ShutdownManager shutdown) {
return new DatabaseComponentImpl<>(database, Object.class, eventBus,
shutdown);
return new DatabaseComponentImpl<Object>(database, Object.class,
eventBus, shutdown);
}
@Test
@@ -1701,7 +1702,7 @@ public class DatabaseComponentImplTest extends BriarTestCase {
Transaction transaction = db.startTransaction(false);
try {
db.addLocalMessage(transaction, message, metadata, true);
Collection<MessageId> dependencies = new ArrayList<>(2);
Collection<MessageId> dependencies = new ArrayList<MessageId>(2);
dependencies.add(messageId1);
dependencies.add(messageId2);
db.addMessageDependencies(transaction, message, dependencies);

View File

@@ -1,11 +1,11 @@
package org.briarproject.bramble.db;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ExponentialBackoffTest extends BriarTestCase {
public class ExponentialBackoffTest extends BrambleTestCase {
private static final int ONE_HOUR = 60 * 60 * 1000;

View File

@@ -1,8 +1,5 @@
package org.briarproject.bramble.db;
import org.briarproject.BriarTestCase;
import org.briarproject.TestDatabaseConfig;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.contact.Contact;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.crypto.SecretKey;
@@ -24,6 +21,9 @@ import org.briarproject.bramble.api.transport.IncomingKeys;
import org.briarproject.bramble.api.transport.OutgoingKeys;
import org.briarproject.bramble.api.transport.TransportKeys;
import org.briarproject.bramble.system.SystemClock;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestDatabaseConfig;
import org.briarproject.bramble.test.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -47,6 +47,7 @@ import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_PUBLIC_K
import static org.briarproject.bramble.api.sync.Group.Visibility.INVISIBLE;
import static org.briarproject.bramble.api.sync.Group.Visibility.SHARED;
import static org.briarproject.bramble.api.sync.Group.Visibility.VISIBLE;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_GROUP_DESCRIPTOR_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_LENGTH;
import static org.briarproject.bramble.api.sync.ValidationManager.State.DELIVERED;
import static org.briarproject.bramble.api.sync.ValidationManager.State.INVALID;
@@ -61,7 +62,7 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class H2DatabaseTest extends BriarTestCase {
public class H2DatabaseTest extends BrambleTestCase {
private static final int ONE_MEGABYTE = 1024 * 1024;
private static final int MAX_SIZE = 5 * ONE_MEGABYTE;
@@ -84,7 +85,7 @@ public class H2DatabaseTest extends BriarTestCase {
public H2DatabaseTest() throws Exception {
groupId = new GroupId(TestUtils.getRandomId());
clientId = new ClientId(TestUtils.getRandomString(5));
byte[] descriptor = new byte[0];
byte[] descriptor = new byte[MAX_GROUP_DESCRIPTOR_LENGTH];
group = new Group(groupId, clientId, descriptor);
AuthorId authorId = new AuthorId(TestUtils.getRandomId());
author = new Author(authorId, "Alice", new byte[MAX_PUBLIC_KEY_LENGTH]);
@@ -868,7 +869,7 @@ public class H2DatabaseTest extends BriarTestCase {
assertEquals(0, db.countOfferedMessages(txn, contactId));
// Add some offered messages and count them
List<MessageId> ids = new ArrayList<>();
List<MessageId> ids = new ArrayList<MessageId>();
for (int i = 0; i < 10; i++) {
MessageId m = new MessageId(TestUtils.getRandomId());
db.addOfferedMessage(txn, contactId, m);
@@ -1316,7 +1317,7 @@ public class H2DatabaseTest extends BriarTestCase {
// Add a second group
GroupId groupId1 = new GroupId(TestUtils.getRandomId());
Group group1 = new Group(groupId1, clientId,
TestUtils.getRandomBytes(42));
TestUtils.getRandomBytes(MAX_GROUP_DESCRIPTOR_LENGTH));
db.addGroup(txn, group1);
// Add a message to the second group

View File

@@ -1,6 +1,6 @@
package org.briarproject.bramble.db;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class LockFairnessTest extends BriarTestCase {
public class LockFairnessTest extends BrambleTestCase {
@Test
public void testReadersCanShareTheLock() throws Exception {

View File

@@ -1,7 +1,7 @@
package org.briarproject.bramble.db;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class TransactionIsolationTest extends BriarTestCase {
public class TransactionIsolationTest extends BrambleTestCase {
private static final String DROP_TABLE = "DROP TABLE foo IF EXISTS";
private static final String CREATE_TABLE = "CREATE TABLE foo"

View File

@@ -1,7 +1,5 @@
package org.briarproject.bramble.identity;
import org.briarproject.BriarMockTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.contact.Contact;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.DatabaseComponent;
@@ -11,6 +9,8 @@ import org.briarproject.bramble.api.identity.Author;
import org.briarproject.bramble.api.identity.AuthorId;
import org.briarproject.bramble.api.identity.IdentityManager;
import org.briarproject.bramble.api.identity.LocalAuthor;
import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.jmock.Expectations;
import org.junit.Test;
@@ -24,7 +24,7 @@ import static org.briarproject.bramble.api.identity.Author.Status.UNVERIFIED;
import static org.briarproject.bramble.api.identity.Author.Status.VERIFIED;
import static org.junit.Assert.assertEquals;
public class IdentityManagerImplTest extends BriarMockTestCase {
public class IdentityManagerImplTest extends BrambleMockTestCase {
private final IdentityManager identityManager;
private final DatabaseComponent db = context.mock(DatabaseComponent.class);
@@ -79,7 +79,7 @@ public class IdentityManagerImplTest extends BriarMockTestCase {
@Test
public void testGetAuthorStatus() throws DbException {
final AuthorId authorId = new AuthorId(TestUtils.getRandomId());
final Collection<Contact> contacts = new ArrayList<>();
final Collection<Contact> contacts = new ArrayList<Contact>();
context.checking(new Expectations() {{
oneOf(db).startTransaction(true);

View File

@@ -1,13 +1,13 @@
package org.briarproject.bramble.keyagreement;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.crypto.KeyPair;
import org.briarproject.bramble.api.crypto.PublicKey;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.keyagreement.Payload;
import org.briarproject.bramble.api.keyagreement.PayloadEncoder;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.jmock.Expectations;
import org.jmock.auto.Mock;
import org.jmock.integration.junit4.JUnitRuleMockery;
@@ -20,7 +20,7 @@ import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class KeyAgreementProtocolTest extends BriarTestCase {
public class KeyAgreementProtocolTest extends BrambleTestCase {
@Rule
public JUnitRuleMockery context = new JUnitRuleMockery() {{
@@ -92,7 +92,7 @@ public class KeyAgreementProtocolTest extends BriarTestCase {
oneOf(callbacks).connectionWaiting();
oneOf(transport).receiveKey();
will(returnValue(BOB_PUBKEY));
oneOf(callbacks).initialPacketReceived();
oneOf(callbacks).initialRecordReceived();
// Alice verifies Bob's public key
oneOf(crypto).deriveKeyCommitment(BOB_PUBKEY);
@@ -152,7 +152,7 @@ public class KeyAgreementProtocolTest extends BriarTestCase {
// Bob receives Alice's public key
oneOf(transport).receiveKey();
will(returnValue(ALICE_PUBKEY));
oneOf(callbacks).initialPacketReceived();
oneOf(callbacks).initialRecordReceived();
// Bob verifies Alice's public key
oneOf(crypto).deriveKeyCommitment(ALICE_PUBKEY);
@@ -213,7 +213,7 @@ public class KeyAgreementProtocolTest extends BriarTestCase {
oneOf(callbacks).connectionWaiting();
oneOf(transport).receiveKey();
will(returnValue(BAD_PUBKEY));
oneOf(callbacks).initialPacketReceived();
oneOf(callbacks).initialRecordReceived();
// Alice verifies Bob's public key
oneOf(crypto).deriveKeyCommitment(BAD_PUBKEY);
@@ -250,7 +250,7 @@ public class KeyAgreementProtocolTest extends BriarTestCase {
// Bob receives a bad public key
oneOf(transport).receiveKey();
will(returnValue(BAD_PUBKEY));
oneOf(callbacks).initialPacketReceived();
oneOf(callbacks).initialRecordReceived();
// Bob verifies Alice's public key
oneOf(crypto).deriveKeyCommitment(BAD_PUBKEY);
@@ -296,7 +296,7 @@ public class KeyAgreementProtocolTest extends BriarTestCase {
oneOf(callbacks).connectionWaiting();
oneOf(transport).receiveKey();
will(returnValue(BOB_PUBKEY));
oneOf(callbacks).initialPacketReceived();
oneOf(callbacks).initialRecordReceived();
// Alice verifies Bob's public key
oneOf(crypto).deriveKeyCommitment(BOB_PUBKEY);
@@ -357,7 +357,7 @@ public class KeyAgreementProtocolTest extends BriarTestCase {
// Bob receives Alice's public key
oneOf(transport).receiveKey();
will(returnValue(ALICE_PUBKEY));
oneOf(callbacks).initialPacketReceived();
oneOf(callbacks).initialRecordReceived();
// Bob verifies Alice's public key
oneOf(crypto).deriveKeyCommitment(ALICE_PUBKEY);

View File

@@ -0,0 +1,251 @@
package org.briarproject.bramble.keyagreement;
import org.briarproject.bramble.api.keyagreement.KeyAgreementConnection;
import org.briarproject.bramble.api.plugin.TransportConnectionReader;
import org.briarproject.bramble.api.plugin.TransportConnectionWriter;
import org.briarproject.bramble.api.plugin.TransportId;
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.ByteUtils;
import org.jmock.Expectations;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.api.keyagreement.KeyAgreementConstants.RECORD_HEADER_LENGTH;
import static org.briarproject.bramble.api.keyagreement.RecordTypes.ABORT;
import static org.briarproject.bramble.api.keyagreement.RecordTypes.CONFIRM;
import static org.briarproject.bramble.api.keyagreement.RecordTypes.KEY;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class KeyAgreementTransportTest extends BrambleMockTestCase {
private final DuplexTransportConnection duplexTransportConnection =
context.mock(DuplexTransportConnection.class);
private final TransportConnectionReader transportConnectionReader =
context.mock(TransportConnectionReader.class);
private final TransportConnectionWriter transportConnectionWriter =
context.mock(TransportConnectionWriter.class);
private final TransportId transportId = new TransportId("test");
private final KeyAgreementConnection keyAgreementConnection =
new KeyAgreementConnection(duplexTransportConnection, transportId);
private ByteArrayInputStream inputStream;
private ByteArrayOutputStream outputStream;
private KeyAgreementTransport kat;
@Test
public void testSendKey() throws Exception {
setup(new byte[0]);
byte[] key = TestUtils.getRandomBytes(123);
kat.sendKey(key);
assertRecordSent(KEY, key);
}
@Test
public void testSendConfirm() throws Exception {
setup(new byte[0]);
byte[] confirm = TestUtils.getRandomBytes(123);
kat.sendConfirm(confirm);
assertRecordSent(CONFIRM, confirm);
}
@Test
public void testSendAbortWithException() throws Exception {
setup(new byte[0]);
context.checking(new Expectations() {{
oneOf(transportConnectionReader).dispose(true, true);
oneOf(transportConnectionWriter).dispose(true);
}});
kat.sendAbort(true);
assertRecordSent(ABORT, new byte[0]);
}
@Test
public void testSendAbortWithoutException() throws Exception {
setup(new byte[0]);
context.checking(new Expectations() {{
oneOf(transportConnectionReader).dispose(false, true);
oneOf(transportConnectionWriter).dispose(false);
}});
kat.sendAbort(false);
assertRecordSent(ABORT, new byte[0]);
}
@Test(expected = AbortException.class)
public void testReceiveKeyThrowsExceptionIfAtEndOfStream()
throws Exception {
setup(new byte[0]);
kat.receiveKey();
}
@Test(expected = AbortException.class)
public void testReceiveKeyThrowsExceptionIfHeaderIsTooShort()
throws Exception {
byte[] input = new byte[RECORD_HEADER_LENGTH - 1];
input[0] = PROTOCOL_VERSION;
input[1] = KEY;
setup(input);
kat.receiveKey();
}
@Test(expected = AbortException.class)
public void testReceiveKeyThrowsExceptionIfPayloadIsTooShort()
throws Exception {
int payloadLength = 123;
byte[] input = new byte[RECORD_HEADER_LENGTH + payloadLength - 1];
input[0] = PROTOCOL_VERSION;
input[1] = KEY;
ByteUtils.writeUint16(payloadLength, input, 2);
setup(input);
kat.receiveKey();
}
@Test(expected = AbortException.class)
public void testReceiveKeyThrowsExceptionIfProtocolVersionIsUnrecognised()
throws Exception {
setup(createRecord((byte) (PROTOCOL_VERSION + 1), KEY, new byte[123]));
kat.receiveKey();
}
@Test(expected = AbortException.class)
public void testReceiveKeyThrowsExceptionIfAbortIsReceived()
throws Exception {
setup(createRecord(PROTOCOL_VERSION, ABORT, new byte[0]));
kat.receiveKey();
}
@Test(expected = AbortException.class)
public void testReceiveKeyThrowsExceptionIfConfirmIsReceived()
throws Exception {
setup(createRecord(PROTOCOL_VERSION, CONFIRM, new byte[123]));
kat.receiveKey();
}
@Test
public void testReceiveKeySkipsUnrecognisedRecordTypes() throws Exception {
byte[] skip1 = createRecord(PROTOCOL_VERSION, (byte) (ABORT + 1),
new byte[123]);
byte[] skip2 = createRecord(PROTOCOL_VERSION, (byte) (ABORT + 2),
new byte[0]);
byte[] payload = TestUtils.getRandomBytes(123);
byte[] key = createRecord(PROTOCOL_VERSION, KEY, payload);
ByteArrayOutputStream input = new ByteArrayOutputStream();
input.write(skip1);
input.write(skip2);
input.write(key);
setup(input.toByteArray());
assertArrayEquals(payload, kat.receiveKey());
}
@Test(expected = AbortException.class)
public void testReceiveConfirmThrowsExceptionIfAtEndOfStream()
throws Exception {
setup(new byte[0]);
kat.receiveConfirm();
}
@Test(expected = AbortException.class)
public void testReceiveConfirmThrowsExceptionIfHeaderIsTooShort()
throws Exception {
byte[] input = new byte[RECORD_HEADER_LENGTH - 1];
input[0] = PROTOCOL_VERSION;
input[1] = CONFIRM;
setup(input);
kat.receiveConfirm();
}
@Test(expected = AbortException.class)
public void testReceiveConfirmThrowsExceptionIfPayloadIsTooShort()
throws Exception {
int payloadLength = 123;
byte[] input = new byte[RECORD_HEADER_LENGTH + payloadLength - 1];
input[0] = PROTOCOL_VERSION;
input[1] = CONFIRM;
ByteUtils.writeUint16(payloadLength, input, 2);
setup(input);
kat.receiveConfirm();
}
@Test(expected = AbortException.class)
public void testReceiveConfirmThrowsExceptionIfProtocolVersionIsUnrecognised()
throws Exception {
setup(createRecord((byte) (PROTOCOL_VERSION + 1), CONFIRM,
new byte[123]));
kat.receiveConfirm();
}
@Test(expected = AbortException.class)
public void testReceiveConfirmThrowsExceptionIfAbortIsReceived()
throws Exception {
setup(createRecord(PROTOCOL_VERSION, ABORT, new byte[0]));
kat.receiveConfirm();
}
@Test(expected = AbortException.class)
public void testReceiveKeyThrowsExceptionIfKeyIsReceived()
throws Exception {
setup(createRecord(PROTOCOL_VERSION, KEY, new byte[123]));
kat.receiveConfirm();
}
@Test
public void testReceiveConfirmSkipsUnrecognisedRecordTypes()
throws Exception {
byte[] skip1 = createRecord(PROTOCOL_VERSION, (byte) (ABORT + 1),
new byte[123]);
byte[] skip2 = createRecord(PROTOCOL_VERSION, (byte) (ABORT + 2),
new byte[0]);
byte[] payload = TestUtils.getRandomBytes(123);
byte[] confirm = createRecord(PROTOCOL_VERSION, CONFIRM, payload);
ByteArrayOutputStream input = new ByteArrayOutputStream();
input.write(skip1);
input.write(skip2);
input.write(confirm);
setup(input.toByteArray());
assertArrayEquals(payload, kat.receiveConfirm());
}
private void setup(byte[] input) throws Exception {
inputStream = new ByteArrayInputStream(input);
outputStream = new ByteArrayOutputStream();
context.checking(new Expectations() {{
allowing(duplexTransportConnection).getReader();
will(returnValue(transportConnectionReader));
allowing(transportConnectionReader).getInputStream();
will(returnValue(inputStream));
allowing(duplexTransportConnection).getWriter();
will(returnValue(transportConnectionWriter));
allowing(transportConnectionWriter).getOutputStream();
will(returnValue(outputStream));
}});
kat = new KeyAgreementTransport(keyAgreementConnection);
}
private void assertRecordSent(byte expectedType, byte[] expectedPayload) {
byte[] output = outputStream.toByteArray();
assertEquals(RECORD_HEADER_LENGTH + expectedPayload.length,
output.length);
assertEquals(PROTOCOL_VERSION, output[0]);
assertEquals(expectedType, output[1]);
assertEquals(expectedPayload.length, ByteUtils.readUint16(output, 2));
byte[] payload = new byte[output.length - RECORD_HEADER_LENGTH];
System.arraycopy(output, RECORD_HEADER_LENGTH, payload, 0,
payload.length);
assertArrayEquals(expectedPayload, payload);
}
private byte[] createRecord(byte version, byte type, byte[] payload) {
byte[] b = new byte[RECORD_HEADER_LENGTH + payload.length];
b[0] = version;
b[1] = type;
ByteUtils.writeUint16(payload.length, b, 2);
System.arraycopy(payload, 0, b, RECORD_HEADER_LENGTH, payload.length);
return b;
}
}

View File

@@ -1,7 +1,7 @@
package org.briarproject.bramble.lifecycle;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.api.lifecycle.ShutdownManager;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import java.util.HashSet;
@@ -10,12 +10,12 @@ import java.util.Set;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ShutdownManagerImplTest extends BriarTestCase {
public class ShutdownManagerImplTest extends BrambleTestCase {
@Test
public void testAddAndRemove() {
ShutdownManager s = createShutdownManager();
Set<Integer> handles = new HashSet<>();
Set<Integer> handles = new HashSet<Integer>();
for (int i = 0; i < 100; i++) {
int handle = s.addShutdownHook(new Runnable() {
@Override

View File

@@ -1,12 +1,12 @@
package org.briarproject.bramble.plugin;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class BackoffImplTest extends BriarTestCase {
public class BackoffImplTest extends BrambleTestCase {
private static final int MIN_INTERVAL = 60 * 1000;
private static final int MAX_INTERVAL = 60 * 60 * 1000;

View File

@@ -1,6 +1,5 @@
package org.briarproject.bramble.plugin;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.event.EventBus;
import org.briarproject.bramble.api.plugin.ConnectionRegistry;
@@ -9,6 +8,7 @@ import org.briarproject.bramble.api.plugin.event.ConnectionClosedEvent;
import org.briarproject.bramble.api.plugin.event.ConnectionOpenedEvent;
import org.briarproject.bramble.api.plugin.event.ContactConnectedEvent;
import org.briarproject.bramble.api.plugin.event.ContactDisconnectedEvent;
import org.briarproject.bramble.test.BrambleTestCase;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ConnectionRegistryImplTest extends BriarTestCase {
public class ConnectionRegistryImplTest extends BrambleTestCase {
private final ContactId contactId, contactId1;
private final TransportId transportId, transportId1;

View File

@@ -1,6 +1,5 @@
package org.briarproject.bramble.plugin;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.api.event.EventBus;
import org.briarproject.bramble.api.plugin.ConnectionManager;
import org.briarproject.bramble.api.plugin.PluginConfig;
@@ -14,6 +13,7 @@ import org.briarproject.bramble.api.plugin.simplex.SimplexPluginFactory;
import org.briarproject.bramble.api.properties.TransportPropertyManager;
import org.briarproject.bramble.api.settings.SettingsManager;
import org.briarproject.bramble.api.ui.UiCallback;
import org.briarproject.bramble.test.BrambleTestCase;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.concurrent.Synchroniser;
@@ -23,7 +23,7 @@ import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class PluginManagerImplTest extends BriarTestCase {
public class PluginManagerImplTest extends BrambleTestCase {
@Test
public void testStartAndStop() throws Exception {

View File

@@ -1,8 +1,5 @@
package org.briarproject.bramble.plugin;
import org.briarproject.BriarTestCase;
import org.briarproject.ImmediateExecutor;
import org.briarproject.RunAction;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.contact.event.ContactStatusChangedEvent;
import org.briarproject.bramble.api.plugin.ConnectionManager;
@@ -18,6 +15,9 @@ import org.briarproject.bramble.api.plugin.event.ConnectionOpenedEvent;
import org.briarproject.bramble.api.plugin.event.TransportEnabledEvent;
import org.briarproject.bramble.api.plugin.simplex.SimplexPlugin;
import org.briarproject.bramble.api.system.Clock;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.ImmediateExecutor;
import org.briarproject.bramble.test.RunAction;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
@@ -32,7 +32,7 @@ import java.util.concurrent.ScheduledExecutorService;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class PollerTest extends BriarTestCase {
public class PollerTest extends BrambleTestCase {
private final ContactId contactId = new ContactId(234);
private final int pollingInterval = 60 * 1000;

View File

@@ -1,6 +1,5 @@
package org.briarproject.bramble.plugin.tcp;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.data.BdfList;
import org.briarproject.bramble.api.keyagreement.KeyAgreementConnection;
@@ -12,6 +11,7 @@ import org.briarproject.bramble.api.plugin.duplex.DuplexPluginCallback;
import org.briarproject.bramble.api.plugin.duplex.DuplexTransportConnection;
import org.briarproject.bramble.api.properties.TransportProperties;
import org.briarproject.bramble.api.settings.Settings;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import java.io.IOException;
@@ -39,7 +39,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class LanTcpPluginTest extends BriarTestCase {
public class LanTcpPluginTest extends BrambleTestCase {
private final ContactId contactId = new ContactId(234);
private final Backoff backoff = new TestBackoff();
@@ -194,7 +194,8 @@ public class LanTcpPluginTest extends BriarTestCase {
plugin.createKeyAgreementListener(new byte[COMMIT_LENGTH]);
assertNotNull(kal);
Callable<KeyAgreementConnection> c = kal.listen();
FutureTask<KeyAgreementConnection> f = new FutureTask<>(c);
FutureTask<KeyAgreementConnection> f =
new FutureTask<KeyAgreementConnection>(c);
new Thread(f).start();
// The plugin should have bound a socket and stored the port number
BdfList descriptor = kal.getDescriptor();
@@ -290,7 +291,7 @@ public class LanTcpPluginTest extends BriarTestCase {
private static class Callback implements DuplexPluginCallback {
private final Map<ContactId, TransportProperties> remote =
new Hashtable<>();
new Hashtable<ContactId, TransportProperties>();
private final CountDownLatch propertiesLatch = new CountDownLatch(1);
private final CountDownLatch connectionsLatch = new CountDownLatch(1);
private final TransportProperties local = new TransportProperties();

View File

@@ -1,11 +1,11 @@
package org.briarproject.bramble.properties;
import org.briarproject.BriarTestCase;
import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test;
import static org.junit.Assert.fail;
public class TransportPropertyManagerImplTest extends BriarTestCase {
public class TransportPropertyManagerImplTest extends BrambleTestCase {
@Test
public void testUnitTestsExist() {

View File

@@ -1,7 +1,5 @@
package org.briarproject.bramble.properties;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.client.ClientHelper;
import org.briarproject.bramble.api.data.BdfDictionary;
@@ -14,6 +12,8 @@ import org.briarproject.bramble.api.sync.GroupId;
import org.briarproject.bramble.api.sync.Message;
import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.api.system.Clock;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.jmock.Mockery;
import org.junit.Test;
@@ -23,7 +23,7 @@ import static org.briarproject.bramble.api.plugin.TransportId.MAX_TRANSPORT_ID_L
import static org.briarproject.bramble.api.properties.TransportPropertyConstants.MAX_PROPERTIES_PER_TRANSPORT;
import static org.junit.Assert.assertEquals;
public class TransportPropertyValidatorTest extends BriarTestCase {
public class TransportPropertyValidatorTest extends BrambleTestCase {
private final TransportId transportId;
private final BdfDictionary bdfDictionary;

View File

@@ -0,0 +1,219 @@
package org.briarproject.bramble.sync;
import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.api.UniqueId;
import org.briarproject.bramble.api.sync.Ack;
import org.briarproject.bramble.api.sync.MessageFactory;
import org.briarproject.bramble.test.BrambleMockTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.ByteUtils;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import static org.briarproject.bramble.api.sync.RecordTypes.ACK;
import static org.briarproject.bramble.api.sync.RecordTypes.OFFER;
import static org.briarproject.bramble.api.sync.RecordTypes.REQUEST;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_IDS;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_RECORD_PAYLOAD_LENGTH;
import static org.briarproject.bramble.api.sync.SyncConstants.PROTOCOL_VERSION;
import static org.briarproject.bramble.api.sync.SyncConstants.RECORD_HEADER_LENGTH;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class RecordReaderImplTest extends BrambleMockTestCase {
private final MessageFactory messageFactory =
context.mock(MessageFactory.class);
@Test(expected = FormatException.class)
public void testFormatExceptionIfAckIsTooLarge() throws Exception {
byte[] b = createAck(true);
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.readAck();
}
@Test
public void testNoFormatExceptionIfAckIsMaximumSize() throws Exception {
byte[] b = createAck(false);
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.readAck();
}
@Test(expected = FormatException.class)
public void testFormatExceptionIfAckIsEmpty() throws Exception {
byte[] b = createEmptyAck();
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.readAck();
}
@Test(expected = FormatException.class)
public void testFormatExceptionIfOfferIsTooLarge() throws Exception {
byte[] b = createOffer(true);
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.readOffer();
}
@Test
public void testNoFormatExceptionIfOfferIsMaximumSize() throws Exception {
byte[] b = createOffer(false);
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.readOffer();
}
@Test(expected = FormatException.class)
public void testFormatExceptionIfOfferIsEmpty() throws Exception {
byte[] b = createEmptyOffer();
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.readOffer();
}
@Test(expected = FormatException.class)
public void testFormatExceptionIfRequestIsTooLarge() throws Exception {
byte[] b = createRequest(true);
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.readRequest();
}
@Test
public void testNoFormatExceptionIfRequestIsMaximumSize() throws Exception {
byte[] b = createRequest(false);
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.readRequest();
}
@Test(expected = FormatException.class)
public void testFormatExceptionIfRequestIsEmpty() throws Exception {
byte[] b = createEmptyRequest();
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.readRequest();
}
@Test
public void testEofReturnsTrueWhenAtEndOfStream() throws Exception {
ByteArrayInputStream in = new ByteArrayInputStream(new byte[0]);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
assertTrue(reader.eof());
}
@Test
public void testEofReturnsFalseWhenNotAtEndOfStream() throws Exception {
byte[] b = createAck(false);
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
assertFalse(reader.eof());
}
@Test(expected = FormatException.class)
public void testThrowsExceptionIfHeaderIsTooShort() throws Exception {
byte[] b = new byte[RECORD_HEADER_LENGTH - 1];
b[0] = PROTOCOL_VERSION;
b[1] = ACK;
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.eof();
}
@Test(expected = FormatException.class)
public void testThrowsExceptionIfPayloadIsTooShort() throws Exception {
int payloadLength = 123;
byte[] b = new byte[RECORD_HEADER_LENGTH + payloadLength - 1];
b[0] = PROTOCOL_VERSION;
b[1] = ACK;
ByteUtils.writeUint16(payloadLength, b, 2);
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.eof();
}
@Test(expected = FormatException.class)
public void testThrowsExceptionIfProtocolVersionIsUnrecognised()
throws Exception {
byte version = (byte) (PROTOCOL_VERSION + 1);
byte[] b = createRecord(version, ACK, new byte[0]);
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.eof();
}
@Test(expected = FormatException.class)
public void testThrowsExceptionIfPayloadIsTooLong() throws Exception {
byte[] payload = new byte[MAX_RECORD_PAYLOAD_LENGTH + 1];
byte[] b = createRecord(PROTOCOL_VERSION, ACK, payload);
ByteArrayInputStream in = new ByteArrayInputStream(b);
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
reader.eof();
}
@Test
public void testSkipsUnrecognisedRecordTypes() throws Exception {
byte[] skip1 = createRecord(PROTOCOL_VERSION, (byte) (REQUEST + 1),
new byte[123]);
byte[] skip2 = createRecord(PROTOCOL_VERSION, (byte) (REQUEST + 2),
new byte[0]);
byte[] ack = createAck(false);
ByteArrayOutputStream input = new ByteArrayOutputStream();
input.write(skip1);
input.write(skip2);
input.write(ack);
ByteArrayInputStream in = new ByteArrayInputStream(input.toByteArray());
RecordReaderImpl reader = new RecordReaderImpl(messageFactory, in);
assertTrue(reader.hasAck());
Ack a = reader.readAck();
assertEquals(MAX_MESSAGE_IDS, a.getMessageIds().size());
}
private byte[] createAck(boolean tooBig) throws Exception {
return createRecord(PROTOCOL_VERSION, ACK, createPayload(tooBig));
}
private byte[] createEmptyAck() throws Exception {
return createRecord(PROTOCOL_VERSION, ACK, new byte[0]);
}
private byte[] createOffer(boolean tooBig) throws Exception {
return createRecord(PROTOCOL_VERSION, OFFER, createPayload(tooBig));
}
private byte[] createEmptyOffer() throws Exception {
return createRecord(PROTOCOL_VERSION, OFFER, new byte[0]);
}
private byte[] createRequest(boolean tooBig) throws Exception {
return createRecord(PROTOCOL_VERSION, REQUEST, createPayload(tooBig));
}
private byte[] createEmptyRequest() throws Exception {
return createRecord(PROTOCOL_VERSION, REQUEST, new byte[0]);
}
private byte[] createRecord(byte version, byte type, byte[] payload) {
byte[] b = new byte[RECORD_HEADER_LENGTH + payload.length];
b[0] = version;
b[1] = type;
ByteUtils.writeUint16(payload.length, b, 2);
System.arraycopy(payload, 0, b, RECORD_HEADER_LENGTH, payload.length);
return b;
}
private byte[] createPayload(boolean tooBig) throws Exception {
ByteArrayOutputStream payload = new ByteArrayOutputStream();
while (payload.size() + UniqueId.LENGTH <= MAX_RECORD_PAYLOAD_LENGTH) {
payload.write(TestUtils.getRandomId());
}
if (tooBig) payload.write(TestUtils.getRandomId());
assertEquals(tooBig, payload.size() > MAX_RECORD_PAYLOAD_LENGTH);
return payload.toByteArray();
}
}

View File

@@ -1,15 +1,15 @@
package org.briarproject.bramble.sync;
import org.briarproject.BriarTestCase;
import org.briarproject.ImmediateExecutor;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.DatabaseComponent;
import org.briarproject.bramble.api.db.Transaction;
import org.briarproject.bramble.api.event.EventBus;
import org.briarproject.bramble.api.sync.Ack;
import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.api.sync.PacketWriter;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.ImmediateExecutor;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.api.sync.RecordWriter;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;
@@ -20,7 +20,7 @@ import java.util.concurrent.Executor;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_MESSAGE_IDS;
public class SimplexOutgoingSessionTest extends BriarTestCase {
public class SimplexOutgoingSessionTest extends BrambleTestCase {
private final Mockery context;
private final DatabaseComponent db;
@@ -29,14 +29,14 @@ public class SimplexOutgoingSessionTest extends BriarTestCase {
private final ContactId contactId;
private final MessageId messageId;
private final int maxLatency;
private final PacketWriter packetWriter;
private final RecordWriter recordWriter;
public SimplexOutgoingSessionTest() {
context = new Mockery();
db = context.mock(DatabaseComponent.class);
dbExecutor = new ImmediateExecutor();
eventBus = context.mock(EventBus.class);
packetWriter = context.mock(PacketWriter.class);
recordWriter = context.mock(RecordWriter.class);
contactId = new ContactId(234);
messageId = new MessageId(TestUtils.getRandomId());
maxLatency = Integer.MAX_VALUE;
@@ -45,7 +45,7 @@ public class SimplexOutgoingSessionTest extends BriarTestCase {
@Test
public void testNothingToSend() throws Exception {
final SimplexOutgoingSession session = new SimplexOutgoingSession(db,
dbExecutor, eventBus, contactId, maxLatency, packetWriter);
dbExecutor, eventBus, contactId, maxLatency, recordWriter);
final Transaction noAckTxn = new Transaction(null, false);
final Transaction noMsgTxn = new Transaction(null, false);
@@ -68,7 +68,7 @@ public class SimplexOutgoingSessionTest extends BriarTestCase {
oneOf(db).commitTransaction(noMsgTxn);
oneOf(db).endTransaction(noMsgTxn);
// Flush the output stream
oneOf(packetWriter).flush();
oneOf(recordWriter).flush();
// Remove listener
oneOf(eventBus).removeListener(session);
}});
@@ -83,7 +83,7 @@ public class SimplexOutgoingSessionTest extends BriarTestCase {
final Ack ack = new Ack(Collections.singletonList(messageId));
final byte[] raw = new byte[1234];
final SimplexOutgoingSession session = new SimplexOutgoingSession(db,
dbExecutor, eventBus, contactId, maxLatency, packetWriter);
dbExecutor, eventBus, contactId, maxLatency, recordWriter);
final Transaction ackTxn = new Transaction(null, false);
final Transaction noAckTxn = new Transaction(null, false);
final Transaction msgTxn = new Transaction(null, false);
@@ -99,7 +99,7 @@ public class SimplexOutgoingSessionTest extends BriarTestCase {
will(returnValue(ack));
oneOf(db).commitTransaction(ackTxn);
oneOf(db).endTransaction(ackTxn);
oneOf(packetWriter).writeAck(ack);
oneOf(recordWriter).writeAck(ack);
// One message to send
oneOf(db).startTransaction(false);
will(returnValue(msgTxn));
@@ -108,7 +108,7 @@ public class SimplexOutgoingSessionTest extends BriarTestCase {
will(returnValue(Arrays.asList(raw)));
oneOf(db).commitTransaction(msgTxn);
oneOf(db).endTransaction(msgTxn);
oneOf(packetWriter).writeMessage(raw);
oneOf(recordWriter).writeMessage(raw);
// No more acks
oneOf(db).startTransaction(false);
will(returnValue(noAckTxn));
@@ -125,7 +125,7 @@ public class SimplexOutgoingSessionTest extends BriarTestCase {
oneOf(db).commitTransaction(noMsgTxn);
oneOf(db).endTransaction(noMsgTxn);
// Flush the output stream
oneOf(packetWriter).flush();
oneOf(recordWriter).flush();
// Remove listener
oneOf(eventBus).removeListener(session);
}});

View File

@@ -1,4 +1,4 @@
package org.briarproject;
package org.briarproject.bramble.sync;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.crypto.CryptoComponent;
@@ -12,14 +12,16 @@ import org.briarproject.bramble.api.sync.Message;
import org.briarproject.bramble.api.sync.MessageFactory;
import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.api.sync.Offer;
import org.briarproject.bramble.api.sync.PacketReader;
import org.briarproject.bramble.api.sync.PacketReaderFactory;
import org.briarproject.bramble.api.sync.PacketWriter;
import org.briarproject.bramble.api.sync.PacketWriterFactory;
import org.briarproject.bramble.api.sync.RecordReader;
import org.briarproject.bramble.api.sync.RecordReaderFactory;
import org.briarproject.bramble.api.sync.RecordWriter;
import org.briarproject.bramble.api.sync.RecordWriterFactory;
import org.briarproject.bramble.api.sync.Request;
import org.briarproject.bramble.api.transport.StreamContext;
import org.briarproject.bramble.api.transport.StreamReaderFactory;
import org.briarproject.bramble.api.transport.StreamWriterFactory;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.junit.Test;
import java.io.ByteArrayInputStream;
@@ -31,13 +33,14 @@ import java.util.Collection;
import javax.inject.Inject;
import static org.briarproject.bramble.api.sync.SyncConstants.MAX_GROUP_DESCRIPTOR_LENGTH;
import static org.briarproject.bramble.api.transport.TransportConstants.TAG_LENGTH;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SyncIntegrationTest extends BriarTestCase {
public class SyncIntegrationTest extends BrambleTestCase {
@Inject
GroupFactory groupFactory;
@@ -48,9 +51,9 @@ public class SyncIntegrationTest extends BriarTestCase {
@Inject
StreamWriterFactory streamWriterFactory;
@Inject
PacketReaderFactory packetReaderFactory;
RecordReaderFactory recordReaderFactory;
@Inject
PacketWriterFactory packetWriterFactory;
RecordWriterFactory recordWriterFactory;
@Inject
CryptoComponent crypto;
@@ -75,7 +78,7 @@ public class SyncIntegrationTest extends BriarTestCase {
streamNumber = 123;
// Create a group
ClientId clientId = new ClientId(TestUtils.getRandomString(5));
byte[] descriptor = new byte[0];
byte[] descriptor = new byte[MAX_GROUP_DESCRIPTOR_LENGTH];
Group group = groupFactory.createGroup(clientId, descriptor);
// Add two messages to the group
long timestamp = System.currentTimeMillis();
@@ -96,14 +99,14 @@ public class SyncIntegrationTest extends BriarTestCase {
headerKey, streamNumber);
OutputStream streamWriter = streamWriterFactory.createStreamWriter(out,
ctx);
PacketWriter packetWriter = packetWriterFactory.createPacketWriter(
RecordWriter recordWriter = recordWriterFactory.createRecordWriter(
streamWriter);
packetWriter.writeAck(new Ack(messageIds));
packetWriter.writeMessage(message.getRaw());
packetWriter.writeMessage(message1.getRaw());
packetWriter.writeOffer(new Offer(messageIds));
packetWriter.writeRequest(new Request(messageIds));
recordWriter.writeAck(new Ack(messageIds));
recordWriter.writeMessage(message.getRaw());
recordWriter.writeMessage(message1.getRaw());
recordWriter.writeOffer(new Offer(messageIds));
recordWriter.writeRequest(new Request(messageIds));
streamWriter.flush();
return out.toByteArray();
@@ -125,31 +128,31 @@ public class SyncIntegrationTest extends BriarTestCase {
headerKey, streamNumber);
InputStream streamReader = streamReaderFactory.createStreamReader(in,
ctx);
PacketReader packetReader = packetReaderFactory.createPacketReader(
RecordReader recordReader = recordReaderFactory.createRecordReader(
streamReader);
// Read the ack
assertTrue(packetReader.hasAck());
Ack a = packetReader.readAck();
assertTrue(recordReader.hasAck());
Ack a = recordReader.readAck();
assertEquals(messageIds, a.getMessageIds());
// Read the messages
assertTrue(packetReader.hasMessage());
Message m = packetReader.readMessage();
assertTrue(recordReader.hasMessage());
Message m = recordReader.readMessage();
checkMessageEquality(message, m);
assertTrue(packetReader.hasMessage());
m = packetReader.readMessage();
assertTrue(recordReader.hasMessage());
m = recordReader.readMessage();
checkMessageEquality(message1, m);
assertFalse(packetReader.hasMessage());
assertFalse(recordReader.hasMessage());
// Read the offer
assertTrue(packetReader.hasOffer());
Offer o = packetReader.readOffer();
assertTrue(recordReader.hasOffer());
Offer o = recordReader.readOffer();
assertEquals(messageIds, o.getMessageIds());
// Read the request
assertTrue(packetReader.hasRequest());
Request req = packetReader.readRequest();
assertTrue(recordReader.hasRequest());
Request req = recordReader.readRequest();
assertEquals(messageIds, req.getMessageIds());
in.close();

View File

@@ -1,7 +1,7 @@
package org.briarproject;
package org.briarproject.bramble.sync;
import org.briarproject.bramble.crypto.CryptoModule;
import org.briarproject.bramble.sync.SyncModule;
import org.briarproject.bramble.test.TestSeedProviderModule;
import org.briarproject.bramble.transport.TransportModule;
import javax.inject.Singleton;

View File

@@ -1,8 +1,5 @@
package org.briarproject.bramble.sync;
import org.briarproject.BriarTestCase;
import org.briarproject.ImmediateExecutor;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.UniqueId;
import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.DatabaseComponent;
@@ -22,6 +19,9 @@ import org.briarproject.bramble.api.sync.ValidationManager.IncomingMessageHook;
import org.briarproject.bramble.api.sync.ValidationManager.MessageValidator;
import org.briarproject.bramble.api.sync.ValidationManager.State;
import org.briarproject.bramble.api.sync.event.MessageAddedEvent;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.ImmediateExecutor;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.ByteUtils;
import org.jmock.Expectations;
import org.jmock.Mockery;
@@ -38,7 +38,7 @@ import static org.briarproject.bramble.api.sync.ValidationManager.State.INVALID;
import static org.briarproject.bramble.api.sync.ValidationManager.State.PENDING;
import static org.briarproject.bramble.api.sync.ValidationManager.State.UNKNOWN;
public class ValidationManagerImplTest extends BriarTestCase {
public class ValidationManagerImplTest extends BrambleTestCase {
private final ClientId clientId =
new ClientId(TestUtils.getRandomString(5));
@@ -831,7 +831,8 @@ public class ValidationManagerImplTest extends BriarTestCase {
context.mock(IncomingMessageHook.class);
final MessageId messageId3 = new MessageId(TestUtils.getRandomId());
final MessageId messageId4 = new MessageId(TestUtils.getRandomId());
final Map<MessageId, State> twoDependents = new LinkedHashMap<>();
final Map<MessageId, State> twoDependents =
new LinkedHashMap<MessageId, State>();
twoDependents.put(messageId1, PENDING);
twoDependents.put(messageId2, PENDING);
final Transaction txn = new Transaction(null, true);
@@ -952,10 +953,12 @@ public class ValidationManagerImplTest extends BriarTestCase {
raw);
final Message message4 = new Message(messageId4, groupId, timestamp,
raw);
final Map<MessageId, State> twoDependents = new LinkedHashMap<>();
final Map<MessageId, State> twoDependents =
new LinkedHashMap<MessageId, State>();
twoDependents.put(messageId1, PENDING);
twoDependents.put(messageId2, PENDING);
final Map<MessageId, State> twoDependencies = new LinkedHashMap<>();
final Map<MessageId, State> twoDependencies =
new LinkedHashMap<MessageId, State>();
twoDependencies.put(messageId1, DELIVERED);
twoDependencies.put(messageId2, DELIVERED);
final Transaction txn = new Transaction(null, true);
@@ -1117,7 +1120,8 @@ public class ValidationManagerImplTest extends BriarTestCase {
final MessageValidator validator = context.mock(MessageValidator.class);
final IncomingMessageHook hook =
context.mock(IncomingMessageHook.class);
final Map<MessageId, State> twoDependencies = new LinkedHashMap<>();
final Map<MessageId, State> twoDependencies =
new LinkedHashMap<MessageId, State>();
twoDependencies.put(messageId, DELIVERED);
twoDependencies.put(messageId2, UNKNOWN);
final Transaction txn = new Transaction(null, true);

View File

@@ -1,8 +1,8 @@
package org.briarproject.bramble.system;
import org.briarproject.BriarTestCase;
import org.briarproject.TestUtils;
import org.briarproject.bramble.api.Bytes;
import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.util.OsUtils;
import org.junit.After;
import org.junit.Before;
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class LinuxSeedProviderTest extends BriarTestCase {
public class LinuxSeedProviderTest extends BrambleTestCase {
private final File testDir = TestUtils.getTestDirectory();
@@ -33,7 +33,7 @@ public class LinuxSeedProviderTest extends BriarTestCase {
System.err.println("WARNING: Skipping test, can't run on this OS");
return;
}
Set<Bytes> seeds = new HashSet<>();
Set<Bytes> seeds = new HashSet<Bytes>();
LinuxSeedProvider p = new LinuxSeedProvider();
for (int i = 0; i < 1000; i++) {
byte[] seed = p.getSeed();

View File

@@ -1,4 +1,4 @@
package org.briarproject;
package org.briarproject.bramble.test;
import org.hamcrest.Description;
import org.jmock.api.Action;

View File

@@ -1,4 +1,4 @@
package org.briarproject;
package org.briarproject.bramble.test;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;

View File

@@ -1,4 +1,4 @@
package org.briarproject;
package org.briarproject.bramble.test;
import org.hamcrest.Description;
import org.jmock.api.Action;

View File

@@ -1,4 +1,4 @@
package org.briarproject;
package org.briarproject.bramble.test;
import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.db.DatabaseConfig;

View File

@@ -1,4 +1,4 @@
package org.briarproject;
package org.briarproject.bramble.test;
import org.briarproject.bramble.api.db.DatabaseConfig;
import org.briarproject.bramble.api.db.DatabaseExecutor;

View File

@@ -1,4 +1,4 @@
package org.briarproject;
package org.briarproject.bramble.test;
import org.briarproject.bramble.api.lifecycle.IoExecutor;
import org.briarproject.bramble.api.lifecycle.LifecycleManager;
@@ -18,7 +18,7 @@ import dagger.Module;
import dagger.Provides;
@Module
class TestLifecycleModule {
public class TestLifecycleModule {
@Provides
LifecycleManager provideLifecycleManager() {

View File

@@ -1,4 +1,4 @@
package org.briarproject;
package org.briarproject.bramble.test;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.plugin.PluginConfig;

View File

@@ -1,4 +1,4 @@
package org.briarproject;
package org.briarproject.bramble.test;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.system.SeedProvider;

View File

@@ -1,4 +1,4 @@
package org.briarproject;
package org.briarproject.bramble.test;
import org.briarproject.bramble.api.system.SeedProvider;

Some files were not shown because too many files have changed in this diff Show More