This repository has been archived by the owner on Apr 12, 2022. It is now read-only.
/
MXCrypto.java
executable file
·1891 lines (1528 loc) · 73 KB
/
MXCrypto.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2016 OpenMarket Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.matrix.androidsdk.crypto;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.JsonElement;
import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.crypto.algorithms.IMXDecrypting;
import org.matrix.androidsdk.crypto.algorithms.IMXEncrypting;
import org.matrix.androidsdk.crypto.data.MXDeviceInfo;
import org.matrix.androidsdk.crypto.data.MXEncryptEventContentResult;
import org.matrix.androidsdk.crypto.data.MXKey;
import org.matrix.androidsdk.crypto.data.MXOlmSessionResult;
import org.matrix.androidsdk.crypto.data.MXUsersDevicesMap;
import org.matrix.androidsdk.data.cryptostore.IMXCryptoStore;
import org.matrix.androidsdk.data.Room;
import org.matrix.androidsdk.data.RoomState;
import org.matrix.androidsdk.listeners.IMXNetworkEventListener;
import org.matrix.androidsdk.listeners.MXEventListener;
import org.matrix.androidsdk.network.NetworkConnectivityReceiver;
import org.matrix.androidsdk.rest.callback.ApiCallback;
import org.matrix.androidsdk.rest.model.Event;
import org.matrix.androidsdk.rest.model.EventContent;
import org.matrix.androidsdk.rest.model.MatrixError;
import org.matrix.androidsdk.rest.model.NewDeviceContent;
import org.matrix.androidsdk.rest.model.RoomKeyContent;
import org.matrix.androidsdk.rest.model.RoomMember;
import org.matrix.androidsdk.rest.model.crypto.KeysQueryResponse;
import org.matrix.androidsdk.rest.model.crypto.KeysUploadResponse;
import org.matrix.androidsdk.util.JsonUtils;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
/**
* A `MXCrypto` class instance manages the end-to-end crypto for a MXSession instance.
*
* Messages posted by the user are automatically redirected to MXCrypto in order to be encrypted
* before sending.
* In the other hand, received events goes through MXCrypto for decrypting.
* MXCrypto maintains all necessary keys and their sharing with other devices required for the crypto.
* Specially, it tracks all room membership changes events in order to do keys updates.
*/
public class MXCrypto {
private static final String LOG_TAG = "MXCrypto";
private static final long UPLOAD_KEYS_DELAY_MS = 10 * 60 * 1000;
private static final int ONE_TIME_KEY_GENERATION_MAX_NUMBER = 5;
private class DoKeyDownloadForUsersResponse {
public final MXUsersDevicesMap<MXDeviceInfo> mUsersDevicesInfoMap;
public final ArrayList<String> mFailedUserIds;
public DoKeyDownloadForUsersResponse(MXUsersDevicesMap<MXDeviceInfo> usersDevicesInfoMap, ArrayList<String> failedUserIds) {
mUsersDevicesInfoMap = usersDevicesInfoMap;
mFailedUserIds = failedUserIds;
}
}
// The Matrix session.
private final MXSession mSession;
// the crypto store
public IMXCryptoStore mCryptoStore;
// MXEncrypting instance for each room.
private HashMap<String, IMXEncrypting> mRoomEncryptors;
// A map from algorithm to MXDecrypting instance, for each room
private HashMap<String, /* room id */
HashMap<String /* algorithm */, IMXDecrypting>> mRoomDecryptors;
// Our device keys
private MXDeviceInfo mMyDevice;
// The libolm wrapper.
private MXOlmDevice mOlmDevice;
private Map<String, Map<String, String>> mLastPublishedOneTimeKeys;
// the encryption is starting
private boolean mIsStarting;
// tell if the crypto is started
private boolean mIsStarted;
// Timer to periodically upload keys
private Timer mUploadKeysTimer;
// Users with new devices
private final HashSet<String> mPendingUsersWithNewDevices;
private final HashSet<String> mInProgressUsersWithNewDevices;
private NetworkConnectivityReceiver mNetworkConnectivityReceiver;
private final IMXNetworkEventListener mNetworkListener = new IMXNetworkEventListener() {
@Override
public void onNetworkConnectionUpdate(boolean isConnected) {
if (isConnected && !isIsStarted()) {
Log.d(LOG_TAG, "Start MXCrypto because a network connection has been retrieved ");
start(null);
}
}
};
private final MXEventListener mEventListener = new MXEventListener() {
@Override
public void onToDeviceEvent(Event event) {
MXCrypto.this.onToDeviceEvent(event);
}
@Override
public void onLiveEvent(Event event, RoomState roomState) {
if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE_ENCRYPTION)) {
onCryptoEvent(event);
} else if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_STATE_ROOM_MEMBER)) {
onRoomMembership(event);
}
}
};
// initialization callbacks
private final ArrayList<ApiCallback<Void>> mInitializationCallbacks = new ArrayList();
/**
* Constructor
* @param matrixSession the session
* @param cryptoStore the crypto store
*/
public MXCrypto(MXSession matrixSession, IMXCryptoStore cryptoStore) {
mSession = matrixSession;
mCryptoStore = cryptoStore;
mOlmDevice = new MXOlmDevice(mCryptoStore);
mRoomEncryptors = new HashMap<>();
mRoomDecryptors = new HashMap<>();
mPendingUsersWithNewDevices = new HashSet<>();
mInProgressUsersWithNewDevices = new HashSet<>();
String deviceId = mSession.getCredentials().deviceId;
if (TextUtils.isEmpty(deviceId)) {
// use the stored one
mSession.getCredentials().deviceId = deviceId = mCryptoStore.getDeviceId();
}
if (TextUtils.isEmpty(deviceId)) {
mSession.getCredentials().deviceId = deviceId = UUID.randomUUID().toString();
Log.d(LOG_TAG, "Warning: No device id in MXCredentials. An id was created. Think of storing it");
mCryptoStore.storeDeviceId(deviceId);
}
mMyDevice = new MXDeviceInfo(deviceId);
mMyDevice.userId = mSession.getMyUserId();
HashMap<String, String> keys = new HashMap<>();
if (!TextUtils.isEmpty(mOlmDevice.getDeviceEd25519Key())) {
keys.put("ed25519:" + mSession.getCredentials().deviceId, mOlmDevice.getDeviceEd25519Key());
}
if (!TextUtils.isEmpty(mOlmDevice.getDeviceCurve25519Key())) {
keys.put("curve25519:" + mSession.getCredentials().deviceId, mOlmDevice.getDeviceCurve25519Key());
}
mMyDevice.keys = keys;
mMyDevice.algorithms = MXCryptoAlgorithms.sharedAlgorithms().supportedAlgorithms();
mMyDevice.mVerified = MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED;
// Add our own deviceinfo to the store
Map<String, MXDeviceInfo> endToEndDevicesForUser = mCryptoStore.getUserDevices(mSession.getMyUserId());
HashMap<String, MXDeviceInfo> myDevices;
if (null != endToEndDevicesForUser) {
myDevices = new HashMap<>(endToEndDevicesForUser);
} else {
myDevices = new HashMap<>();
}
myDevices.put(mMyDevice.deviceId, mMyDevice);
mCryptoStore.storeUserDevices(mSession.getMyUserId(), myDevices);
mSession.getDataHandler().setCryptoEventsListener(mEventListener);
}
public void setNetworkConnectivityReceiver(NetworkConnectivityReceiver networkConnectivityReceiver) {
mNetworkConnectivityReceiver = networkConnectivityReceiver;
}
/**
* The MXSession is paused.
*/
public void pause() {
stopUploadKeysTimer();
}
/**
* The MXSession is resumed.
*/
public void resume() {
if (mIsStarted) {
startUploadKeysTimer(false);
}
}
/**
* Stop the upload keys timer
*/
private void stopUploadKeysTimer() {
if (null != mUploadKeysTimer) {
mUploadKeysTimer.cancel();
mUploadKeysTimer = null;
}
}
/**
* @return true if some saved data is corrupted
*/
public boolean isCorrupted() {
return mCryptoStore.isCorrupted();
}
/**
* @return true if this instance has been released
*/
public boolean hasBeenReleased() {
return (null == mOlmDevice);
}
/**
* @return my device info
*/
public MXDeviceInfo getMyDevice() {
return mMyDevice;
}
/**
* @return the crypto store
*/
public IMXCryptoStore getCryptoStore() {
return mCryptoStore;
}
/**
* Start the timer to periodically upload the keys
* @param delayed true when the keys upload must be delayed
*/
private void startUploadKeysTimer(boolean delayed) {
mUploadKeysTimer = new Timer();
mUploadKeysTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// check race conditions while logging out
if (null != mMyDevice) {
uploadKeys(ONE_TIME_KEY_GENERATION_MAX_NUMBER, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
Log.d(LOG_TAG, "## startUploadKeysTimer() : uploaded");
}
@Override
public void onNetworkError(Exception e) {
Log.e(LOG_TAG, "## startUploadKeysTimer() : failed " + e.getMessage());
}
@Override
public void onMatrixError(MatrixError e) {
Log.e(LOG_TAG, "## startUploadKeysTimer() : failed " + e.getMessage());
}
@Override
public void onUnexpectedError(Exception e) {
Log.e(LOG_TAG, "## startUploadKeysTimer() : failed " + e.getMessage());
}
});
}
}
}, delayed ? UPLOAD_KEYS_DELAY_MS : 0, UPLOAD_KEYS_DELAY_MS);
}
/**
* Tell if the MXCrypto is started
* @return true if the crypto is started
*/
public boolean isIsStarted() {
return mIsStarted;
}
/**
* Start the crypto module.
* Device keys will be uploaded, then one time keys if there are not enough on the homeserver
* and, then, if this is the first time, this new device will be announced to all other users
* devices.
* @param aCallback the asynchrous callback
*/
public void start(final ApiCallback<Void> aCallback) {
if ((null != aCallback) && (mInitializationCallbacks.indexOf(aCallback) < 0)) {
mInitializationCallbacks.add(aCallback);
}
if (mIsStarting) {
return;
}
// do not start if there is not network connection
if ((null != mNetworkConnectivityReceiver) && !mNetworkConnectivityReceiver.isConnected()) {
// wait that a valid network connection is retrieved
mNetworkConnectivityReceiver.removeEventListener(mNetworkListener);
mNetworkConnectivityReceiver.addEventListener(mNetworkListener);
return;
}
mIsStarting = true;
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
uploadKeys(5, new ApiCallback<Void>() {
private void onError() {
// wait 5s before restarting
(new Handler(Looper.getMainLooper())).postDelayed(new Runnable() {
@Override
public void run() {
start(null);
}
}, 5);
}
@Override
public void onSuccess(Void info) {
if (!hasBeenReleased()) {
Log.d(LOG_TAG, "###########################################################");
Log.d(LOG_TAG, "uploadKeys done for " + mSession.getMyUserId());
Log.d(LOG_TAG, " - device id : " + mSession.getCredentials().deviceId);
Log.d(LOG_TAG, " - ed25519 : " + mOlmDevice.getDeviceEd25519Key());
Log.d(LOG_TAG, " - curve25519 : " + mOlmDevice.getDeviceCurve25519Key());
Log.d(LOG_TAG, " - oneTimeKeys: " + mLastPublishedOneTimeKeys); // They are
Log.d(LOG_TAG, "");
checkDeviceAnnounced(new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
if (null != mNetworkConnectivityReceiver) {
mNetworkConnectivityReceiver.removeEventListener(mNetworkListener);
}
mIsStarting = false;
mIsStarted = true;
startUploadKeysTimer(true);
for (ApiCallback<Void> callback : mInitializationCallbacks) {
callback.onSuccess(null);
}
mInitializationCallbacks.clear();
}
@Override
public void onNetworkError(Exception e) {
Log.e(LOG_TAG, "## start failed : " + e.getMessage());
onError();
}
@Override
public void onMatrixError(MatrixError e) {
Log.e(LOG_TAG, "## start failed : " + e.getMessage());
onError();
}
@Override
public void onUnexpectedError(Exception e) {
Log.e(LOG_TAG, "## start failed : " + e.getMessage());
onError();
}
});
}
}
@Override
public void onNetworkError(Exception e) {
Log.e(LOG_TAG, "## start failed : " + e.getMessage());
onError();
}
@Override
public void onMatrixError(MatrixError e) {
Log.e(LOG_TAG, "## start failed : " + e.getMessage());
onError();
}
@Override
public void onUnexpectedError(Exception e) {
Log.e(LOG_TAG, "## start failed : " + e.getMessage());
onError();
}
});
return null;
}
}.execute();
}
/**
* Close the crypto
*/
public void close() {
mSession.getDataHandler().removeListener(mEventListener);
if (null != mOlmDevice) {
mOlmDevice.release();
mOlmDevice = null;
}
mRoomDecryptors = null;
mRoomEncryptors = null;
mMyDevice = null;
stopUploadKeysTimer();
mCryptoStore.close();
mCryptoStore = null;
}
/**
* @return teh olmdevice instance
*/
public MXOlmDevice getOlmDevice() {
return mOlmDevice;
}
/**
* Upload the device keys to the homeserver and ensure
* that the homeserver has enough one-time keys.
* @param maxKeys The maximum number of keys to generate.
* @param callback the asynchronous callback
*/
public void uploadKeys(final int maxKeys, final ApiCallback<Void> callback) {
uploadDeviceKeys(new ApiCallback<KeysUploadResponse>() {
@Override
public void onSuccess(KeysUploadResponse keysUploadResponse) {
if (!hasBeenReleased()) {
// We need to keep a pool of one time public keys on the server so that
// other devices can start conversations with us. But we can only store
// a finite number of private keys in the olm Account object.
// To complicate things further then can be a delay between a device
// claiming a public one time key from the server and it sending us a
// message. We need to keep the corresponding private key locally until
// we receive the message.
// But that message might never arrive leaving us stuck with duff
// private keys clogging up our local storage.
// So we need some kind of enginering compromise to balance all of
// these factors.
// We first find how many keys the server has for us.
int keyCount = keysUploadResponse.oneTimeKeyCountsForAlgorithm("signed_curve25519");
// We then check how many keys we can store in the Account object.
float maxOneTimeKeys = mOlmDevice.getMaxNumberOfOneTimeKeys();
// Try to keep at most half that number on the server. This leaves the
// rest of the slots free to hold keys that have been claimed from the
// server but we haven't recevied a message for.
// If we run out of slots when generating new keys then olm will
// discard the oldest private keys first. This will eventually clean
// out stale private keys that won't receive a message.
int keyLimit = (int) Math.floor(maxOneTimeKeys / 2.0);
// We work out how many new keys we need to create to top up the server
// If there are too many keys on the server then we don't need to
// create any more keys.
int numberToGenerate = Math.max(keyLimit - keyCount, 0);
if (maxKeys > 0) {
// Creating keys can be an expensive operation so we limit the
// number we generate in one go to avoid blocking the application
// for too long.
numberToGenerate = Math.min(numberToGenerate, maxKeys);
// Ask olm to generate new one time keys, then upload them to synapse.
mOlmDevice.generateOneTimeKeys(numberToGenerate);
uploadOneTimeKeys(new ApiCallback<KeysUploadResponse>() {
@Override
public void onSuccess(KeysUploadResponse info) {
if (null != callback) {
callback.onSuccess(null);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
} else {
// If we don't need to generate any keys then we are done.
if (null != callback) {
callback.onSuccess(null);
}
}
}
}
@Override
public void onNetworkError(Exception e) {
Log.e(LOG_TAG, "## uploadKeys() : onNetworkError " + e.getMessage());
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
Log.e(LOG_TAG, "## uploadKeys() : onMatrixError " + e.getLocalizedMessage());
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
Log.e(LOG_TAG, "## uploadKeys() : onUnexpectedError " + e.getMessage());
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
/**
* Download the device keys for a list of users and stores the keys in the MXStore.
* @param userIds The users to fetch.
* @param forceDownload Always download the keys even if cached.
* @param callback the asynchronous callback
*/
public void downloadKeys(List<String> userIds, boolean forceDownload, final ApiCallback<MXUsersDevicesMap<MXDeviceInfo>> callback) {
Log.d(LOG_TAG, "## downloadKeys() : forceDownload " + forceDownload + " : " + userIds);
// Map from userid -> deviceid -> DeviceInfo
final MXUsersDevicesMap<MXDeviceInfo> stored = new MXUsersDevicesMap<>();
// List of user ids we need to download keys for
final ArrayList<String> downloadUsers;
if (forceDownload) {
downloadUsers = (null == userIds) ? new ArrayList<String>() : new ArrayList<>(userIds);
} else {
downloadUsers = new ArrayList<>();
if (null != userIds) {
for (String userId : userIds) {
Map<String, MXDeviceInfo> devices = mCryptoStore.getUserDevices(userId);
if (null == devices) {
downloadUsers.add(userId);
} else {
// If we have some pending new devices for this user, force download their devices keys.
// The keys will be downloaded twice (in flushNewDeviceRequests and here)
// but this is better than no keys.
if (mPendingUsersWithNewDevices.contains(userId) ||
mInProgressUsersWithNewDevices.contains(userId)) {
downloadUsers.add(userId);
} else {
stored.setObjects(devices, userId);
}
}
}
}
}
if (0 == downloadUsers.size()) {
Log.d(LOG_TAG, "## doKeyDownloadForUsers() : no new user device");
if (null != callback) {
callback.onSuccess(stored);
}
} else {
Log.d(LOG_TAG, "## doKeyDownloadForUsers() : starts");
final long t0 = System.currentTimeMillis();
doKeyDownloadForUsers(downloadUsers, new ApiCallback<DoKeyDownloadForUsersResponse>() {
public void onSuccess(DoKeyDownloadForUsersResponse response) {
Log.d(LOG_TAG, "## downloadKeys() : doKeyDownloadForUsers succeeds after " + (System.currentTimeMillis() - t0) + " ms");
MXUsersDevicesMap<MXDeviceInfo> usersDevicesInfoMap = response.mUsersDevicesInfoMap;
ArrayList<String> failedUserIds = response.mFailedUserIds;
for (String failedUserId : failedUserIds) {
Log.e(LOG_TAG, "## downloadKeys() : Error downloading keys for user " + failedUserId);
}
usersDevicesInfoMap.addEntriesFromMap(stored);
if (null != callback) {
callback.onSuccess(usersDevicesInfoMap);
}
}
@Override
public void onNetworkError(Exception e) {
Log.e(LOG_TAG, "## downloadKeys() : doKeyDownloadForUsers onNetworkError " + e.getMessage());
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
Log.e(LOG_TAG, "## downloadKeys() : doKeyDownloadForUsers onMatrixError " + e.getLocalizedMessage());
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
Log.e(LOG_TAG, "## downloadKeys() : doKeyDownloadForUsers onUnexpectedError " + e.getMessage());
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
}
private void doKeyDownloadForUsers(final List<String> downloadUsers, final ApiCallback<DoKeyDownloadForUsersResponse> callback) {
Log.d(LOG_TAG, "## doKeyDownloadForUsers() : doKeyDownloadForUsers " + downloadUsers);
mSession.getCryptoRestClient().downloadKeysForUsers(downloadUsers, new ApiCallback<KeysQueryResponse>() {
@Override
public void onSuccess(final KeysQueryResponse keysQueryResponse) {
new AsyncTask<Void, Void, Void>() {
// private members
MXUsersDevicesMap<MXDeviceInfo> usersDevicesInfoMap = new MXUsersDevicesMap<>();
ArrayList<String> failedUserIds = new ArrayList<>();
@Override
protected Void doInBackground(Void... voids) {
try {
for (String userId : downloadUsers) {
Map<String, MXDeviceInfo> devices = keysQueryResponse.deviceKeys.get(userId);
Log.d(LOG_TAG, "## doKeyDownloadForUsers() : Got keys for " + userId + " : " + devices);
if (null == devices) {
// This can happen when the user hs can not reach the other users hses
// TODO: do something with keysQueryResponse.failures
failedUserIds.add(userId);
} else {
HashMap<String, MXDeviceInfo> mutabledevices = new HashMap<>(devices);
ArrayList<String> deviceIds = new ArrayList<>(mutabledevices.keySet());
for (String deviceId : deviceIds) {
// the user has been logged out
if (null == mCryptoStore) {
return null;
}
// Get the potential previously store device keys for this device
MXDeviceInfo previouslyStoredDeviceKeys = mCryptoStore.getUserDevice(deviceId, userId);
// Validate received keys
if (!validateDeviceKeys(mutabledevices.get(deviceId), userId, deviceId, previouslyStoredDeviceKeys)) {
// New device keys are not valid. Do not store them
mutabledevices.remove(deviceId);
if (null != previouslyStoredDeviceKeys) {
// But keep old validated ones if any
mutabledevices.put(deviceId, previouslyStoredDeviceKeys);
}
} else if (null != previouslyStoredDeviceKeys) {
// The verified status is not sync'ed with hs.
// This is a client side information, valid only for this client.
// So, transfer its previous value
mutabledevices.get(deviceId).mVerified = previouslyStoredDeviceKeys.mVerified;
}
}
// Update the store
// Note that devices which aren't in the response will be removed from the stores
mCryptoStore.storeUserDevices(userId, mutabledevices);
// And the response result
usersDevicesInfoMap.setObjects(mutabledevices, userId);
}
}
} catch (Exception e) {
Log.e(LOG_TAG, "## doKeyDownloadForUsers() : failed " + e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(Void anything) {
if (!hasBeenReleased()) {
if (null != callback) {
callback.onSuccess(new DoKeyDownloadForUsersResponse(usersDevicesInfoMap, failedUserIds));
}
}
}
}.execute();
}
@Override
public void onNetworkError(Exception e) {
Log.e(LOG_TAG, "##doKeyDownloadForUsers() : onNetworkError " + e.getMessage());
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
Log.e(LOG_TAG, "##doKeyDownloadForUsers() : onMatrixError " + e.getMessage());
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
Log.e(LOG_TAG, "##doKeyDownloadForUsers() : onUnexpectedError " + e.getMessage());
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
/**
* Get the stored device keys for a user.
* @param userId the user to list keys for.
* @return the list of devices.
*/
public List<MXDeviceInfo> storedDevicesForUser(String userId) {
Map<String, MXDeviceInfo> map = mCryptoStore.getUserDevices(userId);
if (null == map) {
return null;
} else {
return new ArrayList<>(map.values());
}
}
/**
* Find a device by curve25519 identity key
* @param userId the owner of the device.
* @param algorithm the encryption algorithm.
* @param senderKey the curve25519 key to match.
* @return the device info.
*/
public MXDeviceInfo deviceWithIdentityKey(String senderKey, String userId, String algorithm) {
if (!hasBeenReleased()) {
if (!TextUtils.equals(algorithm, MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_MEGOLM) && !TextUtils.equals(algorithm, MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM)) {
// We only deal in olm keys
return null;
}
if (!TextUtils.isEmpty(userId)) {
List<MXDeviceInfo> devices = storedDevicesForUser(userId);
if (null != devices) {
for (MXDeviceInfo device : devices) {
Set<String> keys = device.keys.keySet();
for (String keyId : keys) {
if (keyId.startsWith("curve25519:")) {
if (TextUtils.equals(senderKey, device.keys.get(keyId))) {
return device;
}
}
}
}
}
}
}
// Doesn't match a known device
return null;
}
/**
* Provides the device information for a device id and an user Id
* @param userId the user id
* @param deviceId the device id
* @return the device info if it exists
*/
public MXDeviceInfo getDeviceInfo(String userId, String deviceId) {
MXDeviceInfo di = null;
if (!TextUtils.isEmpty(userId) && !TextUtils.isEmpty(deviceId)) {
di = mCryptoStore.getUserDevice(deviceId, userId);
}
return di;
}
/**
* Update the blocked/verified state of the given device
* @param verificationStatus the new verification status.
* @param deviceId the unique identifier for the device.
* @param userId the owner of the device.
*/
public void setDeviceVerification(int verificationStatus, String deviceId, String userId) {
if (hasBeenReleased()) {
return;
}
MXDeviceInfo device = mCryptoStore.getUserDevice(deviceId, userId);
// Sanity check
if (null == device) {
Log.e(LOG_TAG, "## setDeviceVerification() : Unknown device " + userId + ":" + deviceId);
return;
}
if (device.mVerified != verificationStatus) {
int oldVerified = device.mVerified;
device.mVerified = verificationStatus;
mCryptoStore.storeUserDevice(userId, device);
Collection<Room> rooms = mSession.getDataHandler().getStore().getRooms();
for(Room room : rooms) {
if (room.isEncrypted()) {
RoomMember roomMember = room.getMember(userId);
// test if the user joins the room
if ((null != roomMember) && TextUtils.equals(roomMember.membership, RoomMember.MEMBERSHIP_JOIN)) {
IMXEncrypting alg = mRoomEncryptors.get(room.getRoomId());
if (null != alg) {
alg.onDeviceVerification(device, oldVerified);
}
}
}
}
}
}
/**
* Configure a room to use encryption.
* @param roomId the room id to enable encryption in.
* @param algorithm the encryption config for the room.
* @return true if the operation succeeds.
*/
private boolean setEncryptionInRoom(String roomId, String algorithm) {
if (hasBeenReleased()) {
return false;
}
// If we already have encryption in this room, we should ignore this event
// (for now at least. Maybe we should alert the user somehow?)
String existingAlgorithm = mCryptoStore.getRoomAlgorithm(roomId);
if (!TextUtils.isEmpty(existingAlgorithm) && !TextUtils.equals(existingAlgorithm, algorithm)) {
Log.e(LOG_TAG, "## setEncryptionInRoom() : Ignoring m.room.encryption event which requests a change of config in " + roomId);
return false;
}
Class<IMXEncrypting> encryptingClass = MXCryptoAlgorithms.sharedAlgorithms().encryptorClassForAlgorithm(algorithm);
if (null == encryptingClass) {
Log.e(LOG_TAG, "## setEncryptionInRoom() : Unable to encrypt with " + algorithm);
return false;
}
mCryptoStore.storeRoomAlgorithm(roomId, algorithm);
IMXEncrypting alg;
try {
Constructor<?> ctor = encryptingClass.getConstructors()[0];
alg = (IMXEncrypting)ctor.newInstance(new Object[]{});
} catch (Exception e) {
Log.e(LOG_TAG, "## setEncryptionInRoom() : fail to load the class");
return false;
}
alg.initWithMatrixSession(mSession, roomId);
mRoomEncryptors.put(roomId, alg);
return true;
}
/**
* Tells if a room is encrypted
* @param roomId the room id
* @return true if the room is encrypted
*/
public boolean isRoomEncrypted(String roomId) {
boolean res = false;
if (null != roomId) {
res = mRoomEncryptors.containsKey(roomId);
if (!res) {
Room room = mSession.getDataHandler().getRoom(roomId);
if (null != room) {
res = room.getLiveState().isEncrypted();
}
}
}
return res;
}
/**
* Try to make sure we have established olm sessions for the given users.
* @param users a list of user ids.
* @param callback the asynchronous callback
*/
public void ensureOlmSessionsForUsers(List<String> users, final ApiCallback<MXUsersDevicesMap<MXOlmSessionResult>> callback) {
Log.d(LOG_TAG, "## ensureOlmSessionsForUsers() : ensureOlmSessionsForUsers " + users);
HashMap<String /* userId */,ArrayList<MXDeviceInfo>> devicesByUser = new HashMap<>();
for(String userId : users) {
devicesByUser.put(userId, new ArrayList<MXDeviceInfo>());
List<MXDeviceInfo> devices = storedDevicesForUser(userId);
for (MXDeviceInfo device : devices){
String key = device.identityKey();
if (TextUtils.equals(key, mOlmDevice.getDeviceCurve25519Key())) {
// Don't bother setting up session to ourself
continue;
}
if (device.mVerified == MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED) {
// Don't bother setting up sessions with blocked users
continue;
}
devicesByUser.get(userId).add(device);
}
}
ensureOlmSessionsForDevices(devicesByUser, callback);
}