-
-
Notifications
You must be signed in to change notification settings - Fork 6k
/
SignalServiceAccountManager.java
876 lines (758 loc) · 39.6 KB
/
SignalServiceAccountManager.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
/**
* Copyright (C) 2014-2016 Open Whisper Systems
*
* Licensed according to the LICENSE file in this repository.
*/
package org.whispersystems.signalservice.api;
import com.squareup.wire.FieldEncoding;
import org.signal.libsignal.protocol.IdentityKeyPair;
import org.signal.libsignal.protocol.InvalidKeyException;
import org.signal.libsignal.protocol.ecc.ECPublicKey;
import org.signal.libsignal.protocol.logging.Log;
import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
import org.signal.libsignal.usernames.BaseUsernameException;
import org.signal.libsignal.usernames.Username;
import org.signal.libsignal.usernames.Username.UsernameLink;
import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredential;
import org.signal.libsignal.zkgroup.profiles.ProfileKey;
import org.whispersystems.signalservice.api.account.AccountAttributes;
import org.whispersystems.signalservice.api.account.ChangePhoneNumberRequest;
import org.whispersystems.signalservice.api.account.PniKeyDistributionRequest;
import org.whispersystems.signalservice.api.account.PreKeyCollection;
import org.whispersystems.signalservice.api.account.PreKeyUpload;
import org.whispersystems.signalservice.api.archive.ArchiveApi;
import org.whispersystems.signalservice.api.crypto.ProfileCipher;
import org.whispersystems.signalservice.api.crypto.ProfileCipherOutputStream;
import org.whispersystems.signalservice.api.groupsv2.ClientZkOperations;
import org.whispersystems.signalservice.api.groupsv2.GroupsV2Api;
import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations;
import org.whispersystems.signalservice.api.kbs.MasterKey;
import org.whispersystems.signalservice.api.keys.KeysApi;
import org.whispersystems.signalservice.api.messages.calls.TurnServerInfo;
import org.whispersystems.signalservice.api.messages.multidevice.DeviceInfo;
import org.whispersystems.signalservice.api.payments.CurrencyConversions;
import org.whispersystems.signalservice.api.profiles.AvatarUploadParams;
import org.whispersystems.signalservice.api.profiles.ProfileAndCredential;
import org.whispersystems.signalservice.api.profiles.SignalServiceProfileWrite;
import org.whispersystems.signalservice.api.push.ServiceId;
import org.whispersystems.signalservice.api.push.ServiceId.ACI;
import org.whispersystems.signalservice.api.push.ServiceId.PNI;
import org.whispersystems.signalservice.api.push.ServiceIdType;
import org.whispersystems.signalservice.api.push.UsernameLinkComponents;
import org.whispersystems.signalservice.api.push.exceptions.NoContentException;
import org.whispersystems.signalservice.api.push.exceptions.NonSuccessfulResponseCodeException;
import org.whispersystems.signalservice.api.push.exceptions.NotFoundException;
import org.whispersystems.signalservice.api.push.exceptions.PushNetworkException;
import org.whispersystems.signalservice.api.services.CdsiV2Service;
import org.whispersystems.signalservice.api.storage.SignalStorageCipher;
import org.whispersystems.signalservice.api.storage.SignalStorageManifest;
import org.whispersystems.signalservice.api.storage.SignalStorageModels;
import org.whispersystems.signalservice.api.storage.SignalStorageRecord;
import org.whispersystems.signalservice.api.storage.StorageId;
import org.whispersystems.signalservice.api.storage.StorageKey;
import org.whispersystems.signalservice.api.storage.StorageManifestKey;
import org.whispersystems.signalservice.api.svr.SecureValueRecoveryV2;
import org.whispersystems.signalservice.api.util.CredentialsProvider;
import org.whispersystems.signalservice.api.util.Preconditions;
import org.whispersystems.signalservice.internal.ServiceResponse;
import org.whispersystems.signalservice.internal.configuration.SignalServiceConfiguration;
import org.whispersystems.signalservice.internal.crypto.PrimaryProvisioningCipher;
import org.whispersystems.signalservice.internal.push.AuthCredentials;
import org.whispersystems.signalservice.internal.push.BackupAuthCheckRequest;
import org.whispersystems.signalservice.internal.push.BackupAuthCheckResponse;
import org.whispersystems.signalservice.internal.push.CdsiAuthResponse;
import org.whispersystems.signalservice.internal.push.OneTimePreKeyCounts;
import org.whispersystems.signalservice.internal.push.PaymentAddress;
import org.whispersystems.signalservice.internal.push.ProfileAvatarData;
import org.whispersystems.signalservice.internal.push.ProvisionMessage;
import org.whispersystems.signalservice.internal.push.ProvisioningVersion;
import org.whispersystems.signalservice.internal.push.PushServiceSocket;
import org.whispersystems.signalservice.internal.push.RegistrationSessionMetadataResponse;
import org.whispersystems.signalservice.internal.push.RemoteConfigResponse;
import org.whispersystems.signalservice.internal.push.ReserveUsernameResponse;
import org.whispersystems.signalservice.internal.push.VerifyAccountResponse;
import org.whispersystems.signalservice.internal.push.WhoAmIResponse;
import org.whispersystems.signalservice.internal.push.http.ProfileCipherOutputStreamFactory;
import org.whispersystems.signalservice.internal.storage.protos.ManifestRecord;
import org.whispersystems.signalservice.internal.storage.protos.ReadOperation;
import org.whispersystems.signalservice.internal.storage.protos.StorageItem;
import org.whispersystems.signalservice.internal.storage.protos.StorageItems;
import org.whispersystems.signalservice.internal.storage.protos.StorageManifest;
import org.whispersystems.signalservice.internal.storage.protos.WriteOperation;
import org.whispersystems.signalservice.internal.util.StaticCredentialsProvider;
import org.whispersystems.signalservice.internal.util.Util;
import org.whispersystems.signalservice.internal.websocket.DefaultResponseMapper;
import org.signal.core.util.Base64;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import io.reactivex.rxjava3.core.Single;
import okio.ByteString;
/**
* The main interface for creating, registering, and
* managing a Signal Service account.
*
* @author Moxie Marlinspike
*/
public class SignalServiceAccountManager {
private static final String TAG = SignalServiceAccountManager.class.getSimpleName();
private static final int STORAGE_READ_MAX_ITEMS = 1000;
private final PushServiceSocket pushServiceSocket;
private final CredentialsProvider credentials;
private final String userAgent;
private final GroupsV2Operations groupsV2Operations;
private final SignalServiceConfiguration configuration;
/**
* Construct a SignalServiceAccountManager.
* @param configuration The URL for the Signal Service.
* @param aci The Signal Service ACI.
* @param pni The Signal Service PNI.
* @param e164 The Signal Service phone number.
* @param password A Signal Service password.
* @param signalAgent A string which identifies the client software.
*/
public SignalServiceAccountManager(SignalServiceConfiguration configuration,
ACI aci,
PNI pni,
String e164,
int deviceId,
String password,
String signalAgent,
boolean automaticNetworkRetry,
int maxGroupSize)
{
this(configuration,
new StaticCredentialsProvider(aci, pni, e164, deviceId, password),
signalAgent,
new GroupsV2Operations(ClientZkOperations.create(configuration), maxGroupSize),
automaticNetworkRetry);
}
public SignalServiceAccountManager(SignalServiceConfiguration configuration,
CredentialsProvider credentialsProvider,
String signalAgent,
GroupsV2Operations groupsV2Operations,
boolean automaticNetworkRetry)
{
this.groupsV2Operations = groupsV2Operations;
this.pushServiceSocket = new PushServiceSocket(configuration, credentialsProvider, signalAgent, groupsV2Operations.getProfileOperations(), automaticNetworkRetry);
this.credentials = credentialsProvider;
this.userAgent = signalAgent;
this.configuration = configuration;
}
public byte[] getSenderCertificate() throws IOException {
return this.pushServiceSocket.getSenderCertificate();
}
public byte[] getSenderCertificateForPhoneNumberPrivacy() throws IOException {
return this.pushServiceSocket.getUuidOnlySenderCertificate();
}
public SecureValueRecoveryV2 getSecureValueRecoveryV2(String mrEnclave) {
return new SecureValueRecoveryV2(configuration, mrEnclave, pushServiceSocket);
}
public WhoAmIResponse getWhoAmI() throws IOException {
return this.pushServiceSocket.getWhoAmI();
}
/**
* Register/Unregister a Google Cloud Messaging registration ID.
*
* @param gcmRegistrationId The GCM id to register. A call with an absent value will unregister.
* @throws IOException
*/
public void setGcmId(Optional<String> gcmRegistrationId) throws IOException {
if (gcmRegistrationId.isPresent()) {
this.pushServiceSocket.registerGcmId(gcmRegistrationId.get());
} else {
this.pushServiceSocket.unregisterGcmId();
}
}
public Single<ServiceResponse<BackupAuthCheckResponse>> checkBackupAuthCredentials(@Nonnull String e164, @Nonnull List<String> usernamePasswords) {
return pushServiceSocket.checkBackupAuthCredentials(new BackupAuthCheckRequest(e164, usernamePasswords), DefaultResponseMapper.getDefault(BackupAuthCheckResponse.class));
}
/**
* Request a push challenge. A number will be pushed to the GCM (FCM) id. This can then be used
* during SMS/call requests to bypass the CAPTCHA.
*
* @param gcmRegistrationId The GCM (FCM) id to use.
* @param sessionId The session to request a push for.
* @throws IOException
*/
public void requestRegistrationPushChallenge(String sessionId, String gcmRegistrationId) throws IOException {
pushServiceSocket.requestPushChallenge(sessionId, gcmRegistrationId);
}
public ServiceResponse<RegistrationSessionMetadataResponse> createRegistrationSession(@Nullable String fcmToken, @Nullable String mcc, @Nullable String mnc) {
try {
final RegistrationSessionMetadataResponse response = pushServiceSocket.createVerificationSession(fcmToken, mcc, mnc);
return ServiceResponse.forResult(response, 200, null);
} catch (IOException e) {
return ServiceResponse.forUnknownError(e);
}
}
public ServiceResponse<RegistrationSessionMetadataResponse> getRegistrationSession(String sessionId) {
try {
final RegistrationSessionMetadataResponse response = pushServiceSocket.getSessionStatus(sessionId);
return ServiceResponse.forResult(response, 200, null);
} catch (IOException e) {
return ServiceResponse.forUnknownError(e);
}
}
public ServiceResponse<RegistrationSessionMetadataResponse> submitPushChallengeToken(String sessionId, String pushChallengeToken) {
try {
final RegistrationSessionMetadataResponse response = pushServiceSocket.patchVerificationSession(sessionId, null, null, null, null, pushChallengeToken);
return ServiceResponse.forResult(response, 200, null);
} catch (IOException e) {
return ServiceResponse.forUnknownError(e);
}
}
public ServiceResponse<RegistrationSessionMetadataResponse> submitCaptchaToken(String sessionId, @Nullable String captchaToken) {
try {
final RegistrationSessionMetadataResponse response = pushServiceSocket.patchVerificationSession(sessionId, null, null, null, captchaToken, null);
return ServiceResponse.forResult(response, 200, null);
} catch (IOException e) {
return ServiceResponse.forUnknownError(e);
}
}
/**
* Request an SMS verification code. On success, the server will send
* an SMS verification code to this Signal user.
*
* @param androidSmsRetrieverSupported
*/
public ServiceResponse<RegistrationSessionMetadataResponse> requestSmsVerificationCode(String sessionId, Locale locale, boolean androidSmsRetrieverSupported) {
try {
final RegistrationSessionMetadataResponse response = pushServiceSocket.requestVerificationCode(sessionId, locale, androidSmsRetrieverSupported, PushServiceSocket.VerificationCodeTransport.SMS);
return ServiceResponse.forResult(response, 200, null);
} catch (IOException e) {
return ServiceResponse.forUnknownError(e);
}
}
/**
* Request a Voice verification code. On success, the server will
* make a voice call to this Signal user.
*
* @param locale
*/
public ServiceResponse<RegistrationSessionMetadataResponse> requestVoiceVerificationCode(String sessionId, Locale locale, boolean androidSmsRetrieverSupported) {
try {
final RegistrationSessionMetadataResponse response = pushServiceSocket.requestVerificationCode(sessionId, locale, androidSmsRetrieverSupported, PushServiceSocket.VerificationCodeTransport.VOICE);
return ServiceResponse.forResult(response, 200, null);
} catch (IOException e) {
return ServiceResponse.forUnknownError(e);
}
}
/**
* Verify a Signal Service account with a received SMS or voice verification code.
*
* @param verificationCode The verification code received via SMS or Voice
* (see {@link #requestSmsVerificationCode} and
* {@link #requestVoiceVerificationCode}).
* @param sessionId The ID of the current registration session.
* @return The UUID of the user that was registered.
* @throws IOException for various HTTP and networking errors
*/
public ServiceResponse<RegistrationSessionMetadataResponse> verifyAccount(@Nonnull String verificationCode, @Nonnull String sessionId) {
try {
RegistrationSessionMetadataResponse response = pushServiceSocket.submitVerificationCode(sessionId, verificationCode);
return ServiceResponse.forResult(response, 200, null);
} catch (IOException e) {
return ServiceResponse.forUnknownError(e);
}
}
public @Nonnull ServiceResponse<VerifyAccountResponse> registerAccount(@Nullable String sessionId, @Nullable String recoveryPassword, AccountAttributes attributes, PreKeyCollection aciPreKeys, PreKeyCollection pniPreKeys, String fcmToken, boolean skipDeviceTransfer) {
try {
VerifyAccountResponse response = pushServiceSocket.submitRegistrationRequest(sessionId, recoveryPassword, attributes, aciPreKeys, pniPreKeys, fcmToken, skipDeviceTransfer);
return ServiceResponse.forResult(response, 200, null);
} catch (IOException e) {
return ServiceResponse.forUnknownError(e);
}
}
public @Nonnull ServiceResponse<VerifyAccountResponse> changeNumber(@Nonnull ChangePhoneNumberRequest changePhoneNumberRequest) {
try {
VerifyAccountResponse response = this.pushServiceSocket.changeNumber(changePhoneNumberRequest);
return ServiceResponse.forResult(response, 200, null);
} catch (IOException e) {
return ServiceResponse.forUnknownError(e);
}
}
/**
* Refresh account attributes with server.
*
* @throws IOException
*/
public void setAccountAttributes(@Nonnull AccountAttributes accountAttributes)
throws IOException
{
this.pushServiceSocket.setAccountAttributes(accountAttributes);
}
/**
* Register an identity key, signed prekey, and list of one time prekeys
* with the server.
*
* @throws IOException
*/
public void setPreKeys(PreKeyUpload preKeyUpload)
throws IOException
{
this.pushServiceSocket.registerPreKeys(preKeyUpload);
}
/**
* @return The server's count of currently available (eg. unused) prekeys for this user.
* @throws IOException
*/
public OneTimePreKeyCounts getPreKeyCounts(ServiceIdType serviceIdType) throws IOException {
return this.pushServiceSocket.getAvailablePreKeys(serviceIdType);
}
/**
* @return True if the identifier corresponds to a registered user, otherwise false.
*/
public boolean isIdentifierRegistered(ServiceId identifier) throws IOException {
return pushServiceSocket.isIdentifierRegistered(identifier);
}
@SuppressWarnings("SameParameterValue")
public CdsiV2Service.Response getRegisteredUsersWithCdsi(Set<String> previousE164s,
Set<String> newE164s,
Map<ServiceId, ProfileKey> serviceIds,
Optional<byte[]> token,
String mrEnclave,
Long timeoutMs,
Consumer<byte[]> tokenSaver)
throws IOException
{
CdsiAuthResponse auth = pushServiceSocket.getCdsiAuth();
CdsiV2Service service = new CdsiV2Service(configuration, mrEnclave);
CdsiV2Service.Request request = new CdsiV2Service.Request(previousE164s, newE164s, serviceIds, token);
Single<ServiceResponse<CdsiV2Service.Response>> single = service.getRegisteredUsers(auth.getUsername(), auth.getPassword(), request, tokenSaver);
ServiceResponse<CdsiV2Service.Response> serviceResponse;
try {
if (timeoutMs == null) {
serviceResponse = single
.blockingGet();
} else {
serviceResponse = single
.timeout(timeoutMs, TimeUnit.MILLISECONDS)
.blockingGet();
}
} catch (RuntimeException e) {
Throwable cause = e.getCause();
if (cause instanceof InterruptedException) {
throw new IOException("Interrupted", cause);
} else if (cause instanceof TimeoutException) {
throw new IOException("Timed out");
} else {
throw e;
}
} catch (Exception e) {
throw new RuntimeException("Unexpected exception when retrieving registered users!", e);
}
if (serviceResponse.getResult().isPresent()) {
return serviceResponse.getResult().get();
} else if (serviceResponse.getApplicationError().isPresent()) {
if (serviceResponse.getApplicationError().get() instanceof IOException) {
throw (IOException) serviceResponse.getApplicationError().get();
} else {
throw new IOException(serviceResponse.getApplicationError().get());
}
} else if (serviceResponse.getExecutionError().isPresent()) {
throw new IOException(serviceResponse.getExecutionError().get());
} else {
throw new IOException("Missing result!");
}
}
public Optional<SignalStorageManifest> getStorageManifest(StorageKey storageKey) throws IOException {
try {
String authToken = this.pushServiceSocket.getStorageAuth();
StorageManifest storageManifest = this.pushServiceSocket.getStorageManifest(authToken);
return Optional.of(SignalStorageModels.remoteToLocalStorageManifest(storageManifest, storageKey));
} catch (InvalidKeyException | NotFoundException e) {
Log.w(TAG, "Error while fetching manifest.", e);
return Optional.empty();
}
}
public long getStorageManifestVersion() throws IOException {
try {
String authToken = this.pushServiceSocket.getStorageAuth();
StorageManifest storageManifest = this.pushServiceSocket.getStorageManifest(authToken);
return storageManifest.version;
} catch (NotFoundException e) {
return 0;
}
}
public Optional<SignalStorageManifest> getStorageManifestIfDifferentVersion(StorageKey storageKey, long manifestVersion) throws IOException, InvalidKeyException {
try {
String authToken = this.pushServiceSocket.getStorageAuth();
StorageManifest storageManifest = this.pushServiceSocket.getStorageManifestIfDifferentVersion(authToken, manifestVersion);
if (storageManifest.value_.size() == 0) {
Log.w(TAG, "Got an empty storage manifest!");
return Optional.empty();
}
return Optional.of(SignalStorageModels.remoteToLocalStorageManifest(storageManifest, storageKey));
} catch (NoContentException e) {
return Optional.empty();
}
}
public List<SignalStorageRecord> readStorageRecords(StorageKey storageKey, List<StorageId> storageKeys) throws IOException, InvalidKeyException {
if (storageKeys.isEmpty()) {
return Collections.emptyList();
}
List<SignalStorageRecord> result = new ArrayList<>();
Map<ByteString, Integer> typeMap = new HashMap<>();
List<ReadOperation> readOperations = new LinkedList<>();
List<ByteString> readKeys = new LinkedList<>();
for (StorageId key : storageKeys) {
typeMap.put(ByteString.of(key.getRaw()), key.getType());
if (readKeys.size() >= STORAGE_READ_MAX_ITEMS) {
Log.i(TAG, "Going over max read items. Starting a new read operation.");
readOperations.add(new ReadOperation.Builder().readKey(readKeys).build());
readKeys = new LinkedList<>();
}
if (StorageId.isKnownType(key.getType())) {
readKeys.add(ByteString.of(key.getRaw()));
} else {
result.add(SignalStorageRecord.forUnknown(key));
}
}
if (readKeys.size() > 0) {
readOperations.add(new ReadOperation.Builder().readKey(readKeys).build());
}
Log.i(TAG, "Reading " + storageKeys.size() + " items split over " + readOperations.size() + " page(s).");
String authToken = this.pushServiceSocket.getStorageAuth();
for (ReadOperation readOperation : readOperations) {
StorageItems items = this.pushServiceSocket.readStorageItems(authToken, readOperation);
for (StorageItem item : items.items) {
Integer type = typeMap.get(item.key);
if (type != null) {
result.add(SignalStorageModels.remoteToLocalStorageRecord(item, type, storageKey));
} else {
Log.w(TAG, "No type found! Skipping.");
}
}
}
return result;
}
/**
* @return If there was a conflict, the latest {@link SignalStorageManifest}. Otherwise absent.
*/
public Optional<SignalStorageManifest> resetStorageRecords(StorageKey storageKey,
SignalStorageManifest manifest,
List<SignalStorageRecord> allRecords)
throws IOException, InvalidKeyException
{
return writeStorageRecords(storageKey, manifest, allRecords, Collections.<byte[]>emptyList(), true);
}
/**
* @return If there was a conflict, the latest {@link SignalStorageManifest}. Otherwise absent.
*/
public Optional<SignalStorageManifest> writeStorageRecords(StorageKey storageKey,
SignalStorageManifest manifest,
List<SignalStorageRecord> inserts,
List<byte[]> deletes)
throws IOException, InvalidKeyException
{
return writeStorageRecords(storageKey, manifest, inserts, deletes, false);
}
/**
* Enables registration lock for this account.
*/
public void enableRegistrationLock(MasterKey masterKey) throws IOException {
pushServiceSocket.setRegistrationLockV2(masterKey.deriveRegistrationLock());
}
/**
* Disables registration lock for this account.
*/
public void disableRegistrationLock() throws IOException {
pushServiceSocket.disableRegistrationLockV2();
}
/**
* @return If there was a conflict, the latest {@link SignalStorageManifest}. Otherwise absent.
*/
private Optional<SignalStorageManifest> writeStorageRecords(StorageKey storageKey,
SignalStorageManifest manifest,
List<SignalStorageRecord> inserts,
List<byte[]> deletes,
boolean clearAll)
throws IOException, InvalidKeyException
{
ManifestRecord.Builder manifestRecordBuilder = new ManifestRecord.Builder()
.sourceDevice(manifest.getSourceDeviceId())
.version(manifest.getVersion());
manifestRecordBuilder.identifiers(
manifest.getStorageIds().stream()
.map(id -> {
ManifestRecord.Identifier.Builder builder = new ManifestRecord.Identifier.Builder()
.raw(ByteString.of(id.getRaw()));
if (!id.isUnknown()) {
builder.type(ManifestRecord.Identifier.Type.Companion.fromValue(id.getType()));
} else {
builder.type(ManifestRecord.Identifier.Type.UNKNOWN);
builder.addUnknownField(2, FieldEncoding.VARINT, id.getType());
}
return builder.build();
})
.collect(Collectors.toList())
);
String authToken = this.pushServiceSocket.getStorageAuth();
StorageManifestKey manifestKey = storageKey.deriveManifestKey(manifest.getVersion());
byte[] encryptedRecord = SignalStorageCipher.encrypt(manifestKey, manifestRecordBuilder.build().encode());
StorageManifest storageManifest = new StorageManifest.Builder()
.version(manifest.getVersion())
.value_(ByteString.of(encryptedRecord))
.build();
WriteOperation.Builder writeBuilder = new WriteOperation.Builder().manifest(storageManifest);
writeBuilder.insertItem(
inserts.stream()
.map(insert -> SignalStorageModels.localToRemoteStorageRecord(insert, storageKey))
.collect(Collectors.toList())
);
if (clearAll) {
writeBuilder.clearAll(true);
} else {
writeBuilder.deleteKey(
deletes.stream()
.map(delete -> ByteString.of(delete))
.collect(Collectors.toList())
);
}
Optional<StorageManifest> conflict = this.pushServiceSocket.writeStorageContacts(authToken, writeBuilder.build());
if (conflict.isPresent()) {
StorageManifestKey conflictKey = storageKey.deriveManifestKey(conflict.get().version);
byte[] rawManifestRecord = SignalStorageCipher.decrypt(conflictKey, conflict.get().value_.toByteArray());
ManifestRecord record = ManifestRecord.ADAPTER.decode(rawManifestRecord);
List<StorageId> ids = new ArrayList<>(record.identifiers.size());
for (ManifestRecord.Identifier id : record.identifiers) {
ids.add(StorageId.forType(id.raw.toByteArray(), id.type.getValue()));
}
SignalStorageManifest conflictManifest = new SignalStorageManifest(record.version, record.sourceDevice, ids);
return Optional.of(conflictManifest);
} else {
return Optional.empty();
}
}
public RemoteConfigResult getRemoteConfig() throws IOException {
RemoteConfigResponse response = this.pushServiceSocket.getRemoteConfig();
Map<String, Object> out = new HashMap<>();
for (RemoteConfigResponse.Config config : response.getConfig()) {
out.put(config.getName(), config.getValue() != null ? config.getValue() : config.isEnabled());
}
return new RemoteConfigResult(out, response.getServerEpochTime());
}
public String getAccountDataReport() throws IOException {
return pushServiceSocket.getAccountDataReport();
}
public String getNewDeviceVerificationCode() throws IOException {
return this.pushServiceSocket.getNewDeviceVerificationCode();
}
public void addDevice(String deviceIdentifier,
ECPublicKey deviceKey,
IdentityKeyPair aciIdentityKeyPair,
IdentityKeyPair pniIdentityKeyPair,
ProfileKey profileKey,
MasterKey masterKey,
String code)
throws InvalidKeyException, IOException
{
String e164 = credentials.getE164();
ACI aci = credentials.getAci();
PNI pni = credentials.getPni();
Preconditions.checkArgument(e164 != null, "Missing e164!");
Preconditions.checkArgument(aci != null, "Missing ACI!");
Preconditions.checkArgument(pni != null, "Missing PNI!");
PrimaryProvisioningCipher cipher = new PrimaryProvisioningCipher(deviceKey);
ProvisionMessage.Builder message = new ProvisionMessage.Builder()
.aciIdentityKeyPublic(ByteString.of(aciIdentityKeyPair.getPublicKey().serialize()))
.aciIdentityKeyPrivate(ByteString.of(aciIdentityKeyPair.getPrivateKey().serialize()))
.pniIdentityKeyPublic(ByteString.of(pniIdentityKeyPair.getPublicKey().serialize()))
.pniIdentityKeyPrivate(ByteString.of(pniIdentityKeyPair.getPrivateKey().serialize()))
.aci(aci.toString())
.pni(pni.toStringWithoutPrefix())
.number(e164)
.profileKey(ByteString.of(profileKey.serialize()))
.provisioningCode(code)
.provisioningVersion(ProvisioningVersion.CURRENT.getValue())
.masterKey(ByteString.of(masterKey.serialize()));
byte[] ciphertext = cipher.encrypt(message.build());
this.pushServiceSocket.sendProvisioningMessage(deviceIdentifier, ciphertext);
}
public ServiceResponse<VerifyAccountResponse> distributePniKeys(PniKeyDistributionRequest request) {
try {
VerifyAccountResponse response = this.pushServiceSocket.distributePniKeys(request);
return ServiceResponse.forResult(response, 200, null);
} catch (IOException e) {
return ServiceResponse.forUnknownError(e);
}
}
public List<DeviceInfo> getDevices() throws IOException {
return this.pushServiceSocket.getDevices();
}
public void removeDevice(long deviceId) throws IOException {
this.pushServiceSocket.removeDevice(deviceId);
}
public TurnServerInfo getTurnServerInfo() throws IOException {
return this.pushServiceSocket.getTurnServerInfo();
}
public void checkNetworkConnection() throws IOException {
this.pushServiceSocket.pingStorageService();
}
public CurrencyConversions getCurrencyConversions() throws IOException {
return this.pushServiceSocket.getCurrencyConversions();
}
public void reportSpam(ServiceId serviceId, String serverGuid, String reportingToken) throws IOException {
this.pushServiceSocket.reportSpam(serviceId, serverGuid, reportingToken);
}
/**
* @return The avatar URL path, if one was written.
*/
public Optional<String> setVersionedProfile(ACI aci,
ProfileKey profileKey,
String name,
String about,
String aboutEmoji,
Optional<PaymentAddress> paymentsAddress,
AvatarUploadParams avatar,
List<String> visibleBadgeIds,
boolean phoneNumberSharing)
throws IOException
{
if (name == null) name = "";
ProfileCipher profileCipher = new ProfileCipher(profileKey);
byte[] ciphertextName = profileCipher.encryptString(name, ProfileCipher.getTargetNameLength(name));
byte[] ciphertextAbout = profileCipher.encryptString(about, ProfileCipher.getTargetAboutLength(about));
byte[] ciphertextEmoji = profileCipher.encryptString(aboutEmoji, ProfileCipher.EMOJI_PADDED_LENGTH);
byte[] ciphertextMobileCoinAddress = paymentsAddress.map(address -> profileCipher.encryptWithLength(address.encode(), ProfileCipher.PAYMENTS_ADDRESS_CONTENT_SIZE)).orElse(null);
byte[] cipherTextPhoneNumberSharing = profileCipher.encryptBoolean(phoneNumberSharing);
ProfileAvatarData profileAvatarData = null;
if (avatar.stream != null && !avatar.keepTheSame) {
profileAvatarData = new ProfileAvatarData(avatar.stream.getStream(),
ProfileCipherOutputStream.getCiphertextLength(avatar.stream.getLength()),
avatar.stream.getContentType(),
new ProfileCipherOutputStreamFactory(profileKey));
}
return this.pushServiceSocket.writeProfile(new SignalServiceProfileWrite(profileKey.getProfileKeyVersion(aci.getLibSignalAci()).serialize(),
ciphertextName,
ciphertextAbout,
ciphertextEmoji,
ciphertextMobileCoinAddress,
cipherTextPhoneNumberSharing,
avatar.hasAvatar,
avatar.keepTheSame,
profileKey.getCommitment(aci.getLibSignalAci()).serialize(),
visibleBadgeIds),
profileAvatarData);
}
public Optional<ExpiringProfileKeyCredential> resolveProfileKeyCredential(ACI serviceId, ProfileKey profileKey, Locale locale)
throws NonSuccessfulResponseCodeException, PushNetworkException
{
try {
ProfileAndCredential credential = this.pushServiceSocket.retrieveVersionedProfileAndCredential(serviceId, profileKey, Optional.empty(), locale).get(10, TimeUnit.SECONDS);
return credential.getExpiringProfileKeyCredential();
} catch (InterruptedException | TimeoutException e) {
throw new PushNetworkException(e);
} catch (ExecutionException e) {
if (e.getCause() instanceof NonSuccessfulResponseCodeException) {
throw (NonSuccessfulResponseCodeException) e.getCause();
} else if (e.getCause() instanceof PushNetworkException) {
throw (PushNetworkException) e.getCause();
} else {
throw new PushNetworkException(e);
}
}
}
public ACI getAciByUsername(Username username) throws IOException {
return this.pushServiceSocket.getAciByUsernameHash(Base64.encodeUrlSafeWithoutPadding(username.getHash()));
}
public ReserveUsernameResponse reserveUsername(List<String> usernameHashes) throws IOException {
return this.pushServiceSocket.reserveUsername(usernameHashes);
}
public UsernameLinkComponents confirmUsernameAndCreateNewLink(Username username) throws IOException {
try {
UsernameLink link = username.generateLink();
UUID serverId = this.pushServiceSocket.confirmUsernameAndCreateNewLink(username, link);
return new UsernameLinkComponents(link.getEntropy(), serverId);
} catch (BaseUsernameException e) {
throw new AssertionError(e);
}
}
public UsernameLinkComponents reclaimUsernameAndLink(Username username, UsernameLinkComponents linkComponents) throws IOException {
try {
UsernameLink link = username.generateLink(linkComponents.getEntropy());
UUID serverId = this.pushServiceSocket.confirmUsernameAndCreateNewLink(username, link);
return new UsernameLinkComponents(link.getEntropy(), serverId);
} catch (BaseUsernameException e) {
throw new AssertionError(e);
}
}
public UsernameLinkComponents updateUsernameLink(UsernameLink newUsernameLink) throws IOException {
UUID serverId = this.pushServiceSocket.createUsernameLink(Base64.encodeUrlSafeWithoutPadding(newUsernameLink.getEncryptedUsername()), true);
return new UsernameLinkComponents(newUsernameLink.getEntropy(), serverId);
}
public void deleteUsername() throws IOException {
this.pushServiceSocket.deleteUsername();
}
public UsernameLinkComponents createUsernameLink(Username username) throws IOException {
try {
UsernameLink link = username.generateLink();
UUID serverId = this.pushServiceSocket.createUsernameLink(Base64.encodeUrlSafeWithPadding(link.getEncryptedUsername()), false);
return new UsernameLinkComponents(link.getEntropy(), serverId);
} catch (BaseUsernameException e) {
throw new AssertionError(e);
}
}
public void deleteUsernameLink() throws IOException {
this.pushServiceSocket.deleteUsernameLink();
}
public byte[] getEncryptedUsernameFromLinkServerId(UUID serverId) throws IOException {
return this.pushServiceSocket.getEncryptedUsernameFromLinkServerId(serverId);
}
public void deleteAccount() throws IOException {
this.pushServiceSocket.deleteAccount();
}
public void requestRateLimitPushChallenge() throws IOException {
this.pushServiceSocket.requestRateLimitPushChallenge();
}
public void submitRateLimitPushChallenge(String challenge) throws IOException {
this.pushServiceSocket.submitRateLimitPushChallenge(challenge);
}
public void submitRateLimitRecaptchaChallenge(String challenge, String recaptchaToken) throws IOException {
this.pushServiceSocket.submitRateLimitRecaptchaChallenge(challenge, recaptchaToken);
}
public void cancelInFlightRequests() {
this.pushServiceSocket.cancelInFlightRequests();
}
private String createDirectoryServerToken(String e164number, boolean urlSafe) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA1");
byte[] token = Util.trim(digest.digest(e164number.getBytes()), 10);
String encoded = Base64.encodeWithoutPadding(token);
if (urlSafe) return encoded.replace('+', '-').replace('/', '_');
else return encoded;
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
public GroupsV2Api getGroupsV2Api() {
return new GroupsV2Api(pushServiceSocket, groupsV2Operations);
}
public ArchiveApi getArchiveApi() {
return ArchiveApi.create(pushServiceSocket, configuration.getBackupServerPublicParams(), credentials.getAci());
}
public KeysApi getKeysApi() {
return KeysApi.create(pushServiceSocket);
}
public AuthCredentials getPaymentsAuthorization() throws IOException {
return pushServiceSocket.getPaymentsAuthorization();
}
}