]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/Manager.java
Renew session if message decryption fails with ProtocolInvalidMessageException
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / Manager.java
1 /*
2 Copyright (C) 2015-2021 AsamK and contributors
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package org.asamk.signal.manager;
18
19 import org.asamk.signal.manager.config.ServiceConfig;
20 import org.asamk.signal.manager.config.ServiceEnvironment;
21 import org.asamk.signal.manager.config.ServiceEnvironmentConfig;
22 import org.asamk.signal.manager.groups.GroupId;
23 import org.asamk.signal.manager.groups.GroupIdV1;
24 import org.asamk.signal.manager.groups.GroupInviteLinkUrl;
25 import org.asamk.signal.manager.groups.GroupNotFoundException;
26 import org.asamk.signal.manager.groups.GroupUtils;
27 import org.asamk.signal.manager.groups.NotAGroupMemberException;
28 import org.asamk.signal.manager.helper.GroupHelper;
29 import org.asamk.signal.manager.helper.PinHelper;
30 import org.asamk.signal.manager.helper.ProfileHelper;
31 import org.asamk.signal.manager.helper.UnidentifiedAccessHelper;
32 import org.asamk.signal.manager.storage.SignalAccount;
33 import org.asamk.signal.manager.storage.groups.GroupInfo;
34 import org.asamk.signal.manager.storage.groups.GroupInfoV1;
35 import org.asamk.signal.manager.storage.groups.GroupInfoV2;
36 import org.asamk.signal.manager.storage.identities.IdentityInfo;
37 import org.asamk.signal.manager.storage.messageCache.CachedMessage;
38 import org.asamk.signal.manager.storage.recipients.Contact;
39 import org.asamk.signal.manager.storage.recipients.Profile;
40 import org.asamk.signal.manager.storage.recipients.RecipientId;
41 import org.asamk.signal.manager.storage.stickers.Sticker;
42 import org.asamk.signal.manager.storage.stickers.StickerPackId;
43 import org.asamk.signal.manager.util.AttachmentUtils;
44 import org.asamk.signal.manager.util.IOUtils;
45 import org.asamk.signal.manager.util.KeyUtils;
46 import org.asamk.signal.manager.util.ProfileUtils;
47 import org.asamk.signal.manager.util.StickerUtils;
48 import org.asamk.signal.manager.util.Utils;
49 import org.signal.libsignal.metadata.InvalidMetadataMessageException;
50 import org.signal.libsignal.metadata.InvalidMetadataVersionException;
51 import org.signal.libsignal.metadata.ProtocolDuplicateMessageException;
52 import org.signal.libsignal.metadata.ProtocolInvalidKeyException;
53 import org.signal.libsignal.metadata.ProtocolInvalidKeyIdException;
54 import org.signal.libsignal.metadata.ProtocolInvalidMessageException;
55 import org.signal.libsignal.metadata.ProtocolInvalidVersionException;
56 import org.signal.libsignal.metadata.ProtocolLegacyMessageException;
57 import org.signal.libsignal.metadata.ProtocolNoSessionException;
58 import org.signal.libsignal.metadata.ProtocolUntrustedIdentityException;
59 import org.signal.libsignal.metadata.SelfSendException;
60 import org.signal.libsignal.metadata.certificate.CertificateValidator;
61 import org.signal.storageservice.protos.groups.GroupChange;
62 import org.signal.storageservice.protos.groups.local.DecryptedGroup;
63 import org.signal.zkgroup.InvalidInputException;
64 import org.signal.zkgroup.VerificationFailedException;
65 import org.signal.zkgroup.groups.GroupMasterKey;
66 import org.signal.zkgroup.groups.GroupSecretParams;
67 import org.signal.zkgroup.profiles.ClientZkProfileOperations;
68 import org.signal.zkgroup.profiles.ProfileKey;
69 import org.signal.zkgroup.profiles.ProfileKeyCredential;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import org.whispersystems.libsignal.IdentityKey;
73 import org.whispersystems.libsignal.IdentityKeyPair;
74 import org.whispersystems.libsignal.InvalidKeyException;
75 import org.whispersystems.libsignal.InvalidMessageException;
76 import org.whispersystems.libsignal.ecc.ECPublicKey;
77 import org.whispersystems.libsignal.state.PreKeyRecord;
78 import org.whispersystems.libsignal.state.SignedPreKeyRecord;
79 import org.whispersystems.libsignal.util.Pair;
80 import org.whispersystems.libsignal.util.guava.Optional;
81 import org.whispersystems.signalservice.api.SignalServiceAccountManager;
82 import org.whispersystems.signalservice.api.SignalServiceMessagePipe;
83 import org.whispersystems.signalservice.api.SignalServiceMessageReceiver;
84 import org.whispersystems.signalservice.api.SignalServiceMessageSender;
85 import org.whispersystems.signalservice.api.crypto.SignalServiceCipher;
86 import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
87 import org.whispersystems.signalservice.api.groupsv2.ClientZkOperations;
88 import org.whispersystems.signalservice.api.groupsv2.GroupLinkNotActiveException;
89 import org.whispersystems.signalservice.api.groupsv2.GroupsV2Api;
90 import org.whispersystems.signalservice.api.groupsv2.GroupsV2AuthorizationString;
91 import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations;
92 import org.whispersystems.signalservice.api.messages.SendMessageResult;
93 import org.whispersystems.signalservice.api.messages.SignalServiceAttachment;
94 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentPointer;
95 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentRemoteId;
96 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentStream;
97 import org.whispersystems.signalservice.api.messages.SignalServiceContent;
98 import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
99 import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
100 import org.whispersystems.signalservice.api.messages.SignalServiceGroup;
101 import org.whispersystems.signalservice.api.messages.SignalServiceGroupV2;
102 import org.whispersystems.signalservice.api.messages.SignalServiceReceiptMessage;
103 import org.whispersystems.signalservice.api.messages.multidevice.BlockedListMessage;
104 import org.whispersystems.signalservice.api.messages.multidevice.ContactsMessage;
105 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContact;
106 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsInputStream;
107 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsOutputStream;
108 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroup;
109 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroupsInputStream;
110 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroupsOutputStream;
111 import org.whispersystems.signalservice.api.messages.multidevice.DeviceInfo;
112 import org.whispersystems.signalservice.api.messages.multidevice.RequestMessage;
113 import org.whispersystems.signalservice.api.messages.multidevice.SentTranscriptMessage;
114 import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage;
115 import org.whispersystems.signalservice.api.messages.multidevice.StickerPackOperationMessage;
116 import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage;
117 import org.whispersystems.signalservice.api.profiles.ProfileAndCredential;
118 import org.whispersystems.signalservice.api.profiles.SignalServiceProfile;
119 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
120 import org.whispersystems.signalservice.api.push.exceptions.MissingConfigurationException;
121 import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
122 import org.whispersystems.signalservice.api.util.InvalidNumberException;
123 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
124 import org.whispersystems.signalservice.api.util.SleepTimer;
125 import org.whispersystems.signalservice.api.util.UptimeSleepTimer;
126 import org.whispersystems.signalservice.api.util.UuidUtil;
127 import org.whispersystems.signalservice.internal.contacts.crypto.Quote;
128 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedQuoteException;
129 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedResponseException;
130 import org.whispersystems.signalservice.internal.push.SignalServiceProtos;
131 import org.whispersystems.signalservice.internal.push.UnsupportedDataMessageException;
132 import org.whispersystems.signalservice.internal.util.DynamicCredentialsProvider;
133 import org.whispersystems.signalservice.internal.util.Hex;
134 import org.whispersystems.signalservice.internal.util.Util;
135
136 import java.io.Closeable;
137 import java.io.File;
138 import java.io.FileInputStream;
139 import java.io.FileOutputStream;
140 import java.io.IOException;
141 import java.io.InputStream;
142 import java.io.OutputStream;
143 import java.net.URI;
144 import java.net.URISyntaxException;
145 import java.net.URLEncoder;
146 import java.nio.charset.StandardCharsets;
147 import java.nio.file.Files;
148 import java.security.SignatureException;
149 import java.util.ArrayList;
150 import java.util.Arrays;
151 import java.util.Base64;
152 import java.util.Collection;
153 import java.util.Date;
154 import java.util.HashSet;
155 import java.util.List;
156 import java.util.Map;
157 import java.util.Set;
158 import java.util.UUID;
159 import java.util.concurrent.ExecutorService;
160 import java.util.concurrent.Executors;
161 import java.util.concurrent.TimeUnit;
162 import java.util.concurrent.TimeoutException;
163 import java.util.function.Function;
164 import java.util.stream.Collectors;
165
166 import static org.asamk.signal.manager.config.ServiceConfig.capabilities;
167
168 public class Manager implements Closeable {
169
170 private final static Logger logger = LoggerFactory.getLogger(Manager.class);
171
172 private final CertificateValidator certificateValidator;
173
174 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
175 private final String userAgent;
176
177 private SignalAccount account;
178 private final SignalServiceAccountManager accountManager;
179 private final GroupsV2Api groupsV2Api;
180 private final GroupsV2Operations groupsV2Operations;
181 private final SignalServiceMessageReceiver messageReceiver;
182 private final ClientZkProfileOperations clientZkProfileOperations;
183
184 private final ExecutorService executor = Executors.newCachedThreadPool();
185
186 private SignalServiceMessagePipe messagePipe = null;
187 private SignalServiceMessagePipe unidentifiedMessagePipe = null;
188
189 private final UnidentifiedAccessHelper unidentifiedAccessHelper;
190 private final ProfileHelper profileHelper;
191 private final GroupHelper groupHelper;
192 private final PinHelper pinHelper;
193 private final AvatarStore avatarStore;
194 private final AttachmentStore attachmentStore;
195
196 Manager(
197 SignalAccount account,
198 PathConfig pathConfig,
199 ServiceEnvironmentConfig serviceEnvironmentConfig,
200 String userAgent
201 ) {
202 this.account = account;
203 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
204 this.certificateValidator = new CertificateValidator(serviceEnvironmentConfig.getUnidentifiedSenderTrustRoot());
205 this.userAgent = userAgent;
206 this.groupsV2Operations = capabilities.isGv2() ? new GroupsV2Operations(ClientZkOperations.create(
207 serviceEnvironmentConfig.getSignalServiceConfiguration())) : null;
208 final SleepTimer timer = new UptimeSleepTimer();
209 this.accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.getSignalServiceConfiguration(),
210 new DynamicCredentialsProvider(account.getUuid(),
211 account.getUsername(),
212 account.getPassword(),
213 account.getDeviceId()),
214 userAgent,
215 groupsV2Operations,
216 ServiceConfig.AUTOMATIC_NETWORK_RETRY,
217 timer);
218 this.groupsV2Api = accountManager.getGroupsV2Api();
219 final var keyBackupService = accountManager.getKeyBackupService(ServiceConfig.getIasKeyStore(),
220 serviceEnvironmentConfig.getKeyBackupConfig().getEnclaveName(),
221 serviceEnvironmentConfig.getKeyBackupConfig().getServiceId(),
222 serviceEnvironmentConfig.getKeyBackupConfig().getMrenclave(),
223 10);
224
225 this.pinHelper = new PinHelper(keyBackupService);
226 this.clientZkProfileOperations = capabilities.isGv2()
227 ? ClientZkOperations.create(serviceEnvironmentConfig.getSignalServiceConfiguration())
228 .getProfileOperations()
229 : null;
230 this.messageReceiver = new SignalServiceMessageReceiver(serviceEnvironmentConfig.getSignalServiceConfiguration(),
231 account.getUuid(),
232 account.getUsername(),
233 account.getPassword(),
234 account.getDeviceId(),
235 userAgent,
236 null,
237 timer,
238 clientZkProfileOperations,
239 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
240
241 this.unidentifiedAccessHelper = new UnidentifiedAccessHelper(account::getProfileKey,
242 account.getProfileStore()::getProfileKey,
243 this::getRecipientProfile,
244 this::getSenderCertificate);
245 this.profileHelper = new ProfileHelper(account.getProfileStore()::getProfileKey,
246 unidentifiedAccessHelper::getAccessFor,
247 unidentified -> unidentified ? getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
248 () -> messageReceiver,
249 this::resolveSignalServiceAddress);
250 this.groupHelper = new GroupHelper(this::getRecipientProfileKeyCredential,
251 this::getRecipientProfile,
252 account::getSelfRecipientId,
253 groupsV2Operations,
254 groupsV2Api,
255 this::getGroupAuthForToday,
256 this::resolveSignalServiceAddress);
257 this.avatarStore = new AvatarStore(pathConfig.getAvatarsPath());
258 this.attachmentStore = new AttachmentStore(pathConfig.getAttachmentsPath());
259 }
260
261 public String getUsername() {
262 return account.getUsername();
263 }
264
265 public SignalServiceAddress getSelfAddress() {
266 return account.getSelfAddress();
267 }
268
269 public RecipientId getSelfRecipientId() {
270 return account.getSelfRecipientId();
271 }
272
273 private IdentityKeyPair getIdentityKeyPair() {
274 return account.getIdentityKeyPair();
275 }
276
277 public int getDeviceId() {
278 return account.getDeviceId();
279 }
280
281 public static Manager init(
282 String username, File settingsPath, ServiceEnvironment serviceEnvironment, String userAgent
283 ) throws IOException, NotRegisteredException {
284 var pathConfig = PathConfig.createDefault(settingsPath);
285
286 if (!SignalAccount.userExists(pathConfig.getDataPath(), username)) {
287 throw new NotRegisteredException();
288 }
289
290 var account = SignalAccount.load(pathConfig.getDataPath(), username);
291
292 if (!account.isRegistered()) {
293 throw new NotRegisteredException();
294 }
295
296 final var serviceEnvironmentConfig = ServiceConfig.getServiceEnvironmentConfig(serviceEnvironment, userAgent);
297
298 return new Manager(account, pathConfig, serviceEnvironmentConfig, userAgent);
299 }
300
301 public static List<String> getAllLocalUsernames(File settingsPath) {
302 var pathConfig = PathConfig.createDefault(settingsPath);
303 final var dataPath = pathConfig.getDataPath();
304 final var files = dataPath.listFiles();
305
306 if (files == null) {
307 return List.of();
308 }
309
310 return Arrays.stream(files)
311 .filter(File::isFile)
312 .map(File::getName)
313 .filter(file -> PhoneNumberFormatter.isValidNumber(file, null))
314 .collect(Collectors.toList());
315 }
316
317 public void checkAccountState() throws IOException {
318 if (accountManager.getPreKeysCount() < ServiceConfig.PREKEY_MINIMUM_COUNT) {
319 refreshPreKeys();
320 }
321 if (account.getUuid() == null) {
322 account.setUuid(accountManager.getOwnUuid());
323 }
324 updateAccountAttributes();
325 }
326
327 /**
328 * This is used for checking a set of phone numbers for registration on Signal
329 *
330 * @param numbers The set of phone number in question
331 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
332 * @throws IOException if its unable to get the contacts to check if they're registered
333 */
334 public Map<String, Boolean> areUsersRegistered(Set<String> numbers) throws IOException {
335 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
336 var contactDetails = getRegisteredUsers(numbers);
337
338 var registeredUsers = contactDetails.keySet();
339
340 return numbers.stream().collect(Collectors.toMap(x -> x, registeredUsers::contains));
341 }
342
343 public void updateAccountAttributes() throws IOException {
344 accountManager.setAccountAttributes(null,
345 account.getLocalRegistrationId(),
346 true,
347 // set legacy pin only if no KBS master key is set
348 account.getPinMasterKey() == null ? account.getRegistrationLockPin() : null,
349 account.getPinMasterKey() == null ? null : account.getPinMasterKey().deriveRegistrationLock(),
350 account.getSelfUnidentifiedAccessKey(),
351 account.isUnrestrictedUnidentifiedAccess(),
352 capabilities,
353 account.isDiscoverableByPhoneNumber());
354 }
355
356 /**
357 * @param givenName if null, the previous givenName will be kept
358 * @param familyName if null, the previous familyName will be kept
359 * @param about if null, the previous about text will be kept
360 * @param aboutEmoji if null, the previous about emoji will be kept
361 * @param avatar if avatar is null the image from the local avatar store is used (if present),
362 */
363 public void setProfile(
364 String givenName, final String familyName, String about, String aboutEmoji, Optional<File> avatar
365 ) throws IOException {
366 var profile = getRecipientProfile(account.getSelfRecipientId());
367 var builder = profile == null ? Profile.newBuilder() : Profile.newBuilder(profile);
368 if (givenName != null) {
369 builder.withGivenName(givenName);
370 }
371 if (familyName != null) {
372 builder.withFamilyName(familyName);
373 }
374 if (about != null) {
375 builder.withAbout(about);
376 }
377 if (aboutEmoji != null) {
378 builder.withAboutEmoji(aboutEmoji);
379 }
380 var newProfile = builder.build();
381
382 try (final var streamDetails = avatar == null
383 ? avatarStore.retrieveProfileAvatar(getSelfAddress())
384 : avatar.isPresent() ? Utils.createStreamDetailsFromFile(avatar.get()) : null) {
385 accountManager.setVersionedProfile(account.getUuid(),
386 account.getProfileKey(),
387 newProfile.getInternalServiceName(),
388 newProfile.getAbout() == null ? "" : newProfile.getAbout(),
389 newProfile.getAboutEmoji() == null ? "" : newProfile.getAboutEmoji(),
390 streamDetails);
391 }
392
393 if (avatar != null) {
394 if (avatar.isPresent()) {
395 avatarStore.storeProfileAvatar(getSelfAddress(),
396 outputStream -> IOUtils.copyFileToStream(avatar.get(), outputStream));
397 } else {
398 avatarStore.deleteProfileAvatar(getSelfAddress());
399 }
400 }
401 account.getProfileStore().storeProfile(account.getSelfRecipientId(), newProfile);
402
403 try {
404 sendSyncMessage(SignalServiceSyncMessage.forFetchLatest(SignalServiceSyncMessage.FetchType.LOCAL_PROFILE));
405 } catch (UntrustedIdentityException ignored) {
406 }
407 }
408
409 public void unregister() throws IOException {
410 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
411 // If this is the master device, other users can't send messages to this number anymore.
412 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
413 accountManager.setGcmId(Optional.absent());
414
415 account.setRegistered(false);
416 }
417
418 public void deleteAccount() throws IOException {
419 accountManager.deleteAccount();
420
421 account.setRegistered(false);
422 }
423
424 public List<DeviceInfo> getLinkedDevices() throws IOException {
425 var devices = accountManager.getDevices();
426 account.setMultiDevice(devices.size() > 1);
427 return devices;
428 }
429
430 public void removeLinkedDevices(int deviceId) throws IOException {
431 accountManager.removeDevice(deviceId);
432 var devices = accountManager.getDevices();
433 account.setMultiDevice(devices.size() > 1);
434 }
435
436 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
437 var info = DeviceLinkInfo.parseDeviceLinkUri(linkUri);
438
439 addDevice(info.deviceIdentifier, info.deviceKey);
440 }
441
442 private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
443 var identityKeyPair = getIdentityKeyPair();
444 var verificationCode = accountManager.getNewDeviceVerificationCode();
445
446 accountManager.addDevice(deviceIdentifier,
447 deviceKey,
448 identityKeyPair,
449 Optional.of(account.getProfileKey().serialize()),
450 verificationCode);
451 account.setMultiDevice(true);
452 }
453
454 public void setRegistrationLockPin(Optional<String> pin) throws IOException, UnauthenticatedResponseException {
455 if (!account.isMasterDevice()) {
456 throw new RuntimeException("Only master device can set a PIN");
457 }
458 if (pin.isPresent()) {
459 final var masterKey = account.getPinMasterKey() != null
460 ? account.getPinMasterKey()
461 : KeyUtils.createMasterKey();
462
463 pinHelper.setRegistrationLockPin(pin.get(), masterKey);
464
465 account.setRegistrationLockPin(pin.get(), masterKey);
466 } else {
467 // Remove legacy registration lock
468 accountManager.removeRegistrationLockV1();
469
470 // Remove KBS Pin
471 pinHelper.removeRegistrationLockPin();
472
473 account.setRegistrationLockPin(null, null);
474 }
475 }
476
477 void refreshPreKeys() throws IOException {
478 var oneTimePreKeys = generatePreKeys();
479 final var identityKeyPair = getIdentityKeyPair();
480 var signedPreKeyRecord = generateSignedPreKey(identityKeyPair);
481
482 accountManager.setPreKeys(identityKeyPair.getPublicKey(), signedPreKeyRecord, oneTimePreKeys);
483 }
484
485 private List<PreKeyRecord> generatePreKeys() {
486 final var offset = account.getPreKeyIdOffset();
487
488 var records = KeyUtils.generatePreKeyRecords(offset, ServiceConfig.PREKEY_BATCH_SIZE);
489 account.addPreKeys(records);
490
491 return records;
492 }
493
494 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
495 final var signedPreKeyId = account.getNextSignedPreKeyId();
496
497 var record = KeyUtils.generateSignedPreKeyRecord(identityKeyPair, signedPreKeyId);
498 account.addSignedPreKey(record);
499
500 return record;
501 }
502
503 private SignalServiceMessagePipe getOrCreateMessagePipe() {
504 if (messagePipe == null) {
505 messagePipe = messageReceiver.createMessagePipe();
506 }
507 return messagePipe;
508 }
509
510 private SignalServiceMessagePipe getOrCreateUnidentifiedMessagePipe() {
511 if (unidentifiedMessagePipe == null) {
512 unidentifiedMessagePipe = messageReceiver.createUnidentifiedMessagePipe();
513 }
514 return unidentifiedMessagePipe;
515 }
516
517 private SignalServiceMessageSender createMessageSender() {
518 return new SignalServiceMessageSender(serviceEnvironmentConfig.getSignalServiceConfiguration(),
519 account.getUuid(),
520 account.getUsername(),
521 account.getPassword(),
522 account.getDeviceId(),
523 account.getSignalProtocolStore(),
524 userAgent,
525 account.isMultiDevice(),
526 Optional.fromNullable(messagePipe),
527 Optional.fromNullable(unidentifiedMessagePipe),
528 Optional.absent(),
529 clientZkProfileOperations,
530 executor,
531 ServiceConfig.MAX_ENVELOPE_SIZE,
532 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
533 }
534
535 public Profile getRecipientProfile(
536 RecipientId recipientId
537 ) {
538 return getRecipientProfile(recipientId, false);
539 }
540
541 private final Set<RecipientId> pendingProfileRequest = new HashSet<>();
542
543 Profile getRecipientProfile(
544 RecipientId recipientId, boolean force
545 ) {
546 var profileKey = account.getProfileStore().getProfileKey(recipientId);
547 if (profileKey == null) {
548 if (force) {
549 // retrieve profile to get identity key
550 retrieveEncryptedProfile(recipientId);
551 }
552 return null;
553 }
554 var profile = account.getProfileStore().getProfile(recipientId);
555
556 var now = new Date().getTime();
557 // Profiles are cached for 24h before retrieving them again, unless forced
558 if (!force && profile != null && now - profile.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
559 return profile;
560 }
561
562 synchronized (pendingProfileRequest) {
563 if (pendingProfileRequest.contains(recipientId)) {
564 return profile;
565 }
566 pendingProfileRequest.add(recipientId);
567 }
568 final SignalServiceProfile encryptedProfile;
569 try {
570 encryptedProfile = retrieveEncryptedProfile(recipientId);
571 } finally {
572 synchronized (pendingProfileRequest) {
573 pendingProfileRequest.remove(recipientId);
574 }
575 }
576 if (encryptedProfile == null) {
577 return null;
578 }
579
580 profile = decryptProfileAndDownloadAvatar(recipientId, profileKey, encryptedProfile);
581 account.getProfileStore().storeProfile(recipientId, profile);
582
583 return profile;
584 }
585
586 private SignalServiceProfile retrieveEncryptedProfile(RecipientId recipientId) {
587 try {
588 return retrieveProfileAndCredential(recipientId, SignalServiceProfile.RequestType.PROFILE).getProfile();
589 } catch (IOException e) {
590 logger.warn("Failed to retrieve profile, ignoring: {}", e.getMessage());
591 return null;
592 }
593 }
594
595 private ProfileAndCredential retrieveProfileAndCredential(
596 final RecipientId recipientId, final SignalServiceProfile.RequestType requestType
597 ) throws IOException {
598 final var profileAndCredential = profileHelper.retrieveProfileSync(recipientId, requestType);
599 final var profile = profileAndCredential.getProfile();
600
601 try {
602 var newIdentity = account.getIdentityKeyStore()
603 .saveIdentity(recipientId,
604 new IdentityKey(Base64.getDecoder().decode(profile.getIdentityKey())),
605 new Date());
606
607 if (newIdentity) {
608 account.getSessionStore().archiveSessions(recipientId);
609 }
610 } catch (InvalidKeyException ignored) {
611 logger.warn("Got invalid identity key in profile for {}",
612 resolveSignalServiceAddress(recipientId).getLegacyIdentifier());
613 }
614 return profileAndCredential;
615 }
616
617 private ProfileKeyCredential getRecipientProfileKeyCredential(RecipientId recipientId) {
618 var profileKeyCredential = account.getProfileStore().getProfileKeyCredential(recipientId);
619 if (profileKeyCredential != null) {
620 return profileKeyCredential;
621 }
622
623 ProfileAndCredential profileAndCredential;
624 try {
625 profileAndCredential = retrieveProfileAndCredential(recipientId,
626 SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL);
627 } catch (IOException e) {
628 logger.warn("Failed to retrieve profile key credential, ignoring: {}", e.getMessage());
629 return null;
630 }
631
632 profileKeyCredential = profileAndCredential.getProfileKeyCredential().orNull();
633 account.getProfileStore().storeProfileKeyCredential(recipientId, profileKeyCredential);
634
635 var profileKey = account.getProfileStore().getProfileKey(recipientId);
636 if (profileKey != null) {
637 final var profile = decryptProfileAndDownloadAvatar(recipientId,
638 profileKey,
639 profileAndCredential.getProfile());
640 account.getProfileStore().storeProfile(recipientId, profile);
641 }
642
643 return profileKeyCredential;
644 }
645
646 private Profile decryptProfileAndDownloadAvatar(
647 final RecipientId recipientId, final ProfileKey profileKey, final SignalServiceProfile encryptedProfile
648 ) {
649 if (encryptedProfile.getAvatar() != null) {
650 downloadProfileAvatar(resolveSignalServiceAddress(recipientId), encryptedProfile.getAvatar(), profileKey);
651 }
652
653 return ProfileUtils.decryptProfile(profileKey, encryptedProfile);
654 }
655
656 private Optional<SignalServiceAttachmentStream> createGroupAvatarAttachment(GroupId groupId) throws IOException {
657 final var streamDetails = avatarStore.retrieveGroupAvatar(groupId);
658 if (streamDetails == null) {
659 return Optional.absent();
660 }
661
662 return Optional.of(AttachmentUtils.createAttachment(streamDetails, Optional.absent()));
663 }
664
665 private Optional<SignalServiceAttachmentStream> createContactAvatarAttachment(SignalServiceAddress address) throws IOException {
666 final var streamDetails = avatarStore.retrieveContactAvatar(address);
667 if (streamDetails == null) {
668 return Optional.absent();
669 }
670
671 return Optional.of(AttachmentUtils.createAttachment(streamDetails, Optional.absent()));
672 }
673
674 private GroupInfo getGroupForSending(GroupId groupId) throws GroupNotFoundException, NotAGroupMemberException {
675 var g = getGroup(groupId);
676 if (g == null) {
677 throw new GroupNotFoundException(groupId);
678 }
679 if (!g.isMember(account.getSelfRecipientId())) {
680 throw new NotAGroupMemberException(groupId, g.getTitle());
681 }
682 return g;
683 }
684
685 private GroupInfo getGroupForUpdating(GroupId groupId) throws GroupNotFoundException, NotAGroupMemberException {
686 var g = getGroup(groupId);
687 if (g == null) {
688 throw new GroupNotFoundException(groupId);
689 }
690 if (!g.isMember(account.getSelfRecipientId()) && !g.isPendingMember(account.getSelfRecipientId())) {
691 throw new NotAGroupMemberException(groupId, g.getTitle());
692 }
693 return g;
694 }
695
696 public List<GroupInfo> getGroups() {
697 return account.getGroupStore().getGroups();
698 }
699
700 public Pair<Long, List<SendMessageResult>> sendGroupMessage(
701 String messageText, List<String> attachments, GroupId groupId
702 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException {
703 final var messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
704 if (attachments != null) {
705 messageBuilder.withAttachments(AttachmentUtils.getSignalServiceAttachments(attachments));
706 }
707
708 return sendGroupMessage(messageBuilder, groupId);
709 }
710
711 public Pair<Long, List<SendMessageResult>> sendGroupMessageReaction(
712 String emoji, boolean remove, String targetAuthor, long targetSentTimestamp, GroupId groupId
713 ) throws IOException, InvalidNumberException, NotAGroupMemberException, GroupNotFoundException {
714 var targetAuthorRecipientId = canonicalizeAndResolveRecipient(targetAuthor);
715 var reaction = new SignalServiceDataMessage.Reaction(emoji,
716 remove,
717 resolveSignalServiceAddress(targetAuthorRecipientId),
718 targetSentTimestamp);
719 final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
720
721 return sendGroupMessage(messageBuilder, groupId);
722 }
723
724 public Pair<Long, List<SendMessageResult>> sendGroupMessage(
725 SignalServiceDataMessage.Builder messageBuilder, GroupId groupId
726 ) throws IOException, GroupNotFoundException, NotAGroupMemberException {
727 final var g = getGroupForSending(groupId);
728
729 GroupUtils.setGroupContext(messageBuilder, g);
730 messageBuilder.withExpiration(g.getMessageExpirationTime());
731
732 return sendMessage(messageBuilder, g.getMembersWithout(account.getSelfRecipientId()));
733 }
734
735 public Pair<Long, List<SendMessageResult>> sendQuitGroupMessage(GroupId groupId) throws GroupNotFoundException, IOException, NotAGroupMemberException {
736 SignalServiceDataMessage.Builder messageBuilder;
737
738 final var g = getGroupForUpdating(groupId);
739 if (g instanceof GroupInfoV1) {
740 var groupInfoV1 = (GroupInfoV1) g;
741 var group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.QUIT).withId(groupId.serialize()).build();
742 messageBuilder = SignalServiceDataMessage.newBuilder().asGroupMessage(group);
743 groupInfoV1.removeMember(account.getSelfRecipientId());
744 account.getGroupStore().updateGroup(groupInfoV1);
745 } else {
746 final var groupInfoV2 = (GroupInfoV2) g;
747 final var groupGroupChangePair = groupHelper.leaveGroup(groupInfoV2);
748 groupInfoV2.setGroup(groupGroupChangePair.first(), this::resolveRecipient);
749 messageBuilder = getGroupUpdateMessageBuilder(groupInfoV2, groupGroupChangePair.second().toByteArray());
750 account.getGroupStore().updateGroup(groupInfoV2);
751 }
752
753 return sendMessage(messageBuilder, g.getMembersWithout(account.getSelfRecipientId()));
754 }
755
756 public Pair<GroupId, List<SendMessageResult>> updateGroup(
757 GroupId groupId, String name, List<String> members, File avatarFile
758 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, InvalidNumberException, NotAGroupMemberException {
759 return sendUpdateGroupMessage(groupId,
760 name,
761 members == null ? null : getSignalServiceAddresses(members),
762 avatarFile);
763 }
764
765 private Pair<GroupId, List<SendMessageResult>> sendUpdateGroupMessage(
766 GroupId groupId, String name, Set<RecipientId> members, File avatarFile
767 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException {
768 GroupInfo g;
769 SignalServiceDataMessage.Builder messageBuilder;
770 if (groupId == null) {
771 // Create new group
772 var gv2Pair = groupHelper.createGroupV2(name == null ? "" : name,
773 members == null ? Set.of() : members,
774 avatarFile);
775 if (gv2Pair == null) {
776 var gv1 = new GroupInfoV1(GroupIdV1.createRandom());
777 gv1.addMembers(List.of(account.getSelfRecipientId()));
778 updateGroupV1(gv1, name, members, avatarFile);
779 messageBuilder = getGroupUpdateMessageBuilder(gv1);
780 g = gv1;
781 } else {
782 final var gv2 = gv2Pair.first();
783 final var decryptedGroup = gv2Pair.second();
784
785 gv2.setGroup(decryptedGroup, this::resolveRecipient);
786 if (avatarFile != null) {
787 avatarStore.storeGroupAvatar(gv2.getGroupId(),
788 outputStream -> IOUtils.copyFileToStream(avatarFile, outputStream));
789 }
790 messageBuilder = getGroupUpdateMessageBuilder(gv2, null);
791 g = gv2;
792 }
793 } else {
794 var group = getGroupForUpdating(groupId);
795 if (group instanceof GroupInfoV2) {
796 final var groupInfoV2 = (GroupInfoV2) group;
797
798 Pair<Long, List<SendMessageResult>> result = null;
799 if (groupInfoV2.isPendingMember(account.getSelfRecipientId())) {
800 var groupGroupChangePair = groupHelper.acceptInvite(groupInfoV2);
801 result = sendUpdateGroupMessage(groupInfoV2,
802 groupGroupChangePair.first(),
803 groupGroupChangePair.second());
804 }
805
806 if (members != null) {
807 final var newMembers = new HashSet<>(members);
808 newMembers.removeAll(group.getMembers());
809 if (newMembers.size() > 0) {
810 var groupGroupChangePair = groupHelper.updateGroupV2(groupInfoV2, newMembers);
811 result = sendUpdateGroupMessage(groupInfoV2,
812 groupGroupChangePair.first(),
813 groupGroupChangePair.second());
814 }
815 }
816 if (result == null || name != null || avatarFile != null) {
817 var groupGroupChangePair = groupHelper.updateGroupV2(groupInfoV2, name, avatarFile);
818 if (avatarFile != null) {
819 avatarStore.storeGroupAvatar(groupInfoV2.getGroupId(),
820 outputStream -> IOUtils.copyFileToStream(avatarFile, outputStream));
821 }
822 result = sendUpdateGroupMessage(groupInfoV2,
823 groupGroupChangePair.first(),
824 groupGroupChangePair.second());
825 }
826
827 return new Pair<>(group.getGroupId(), result.second());
828 } else {
829 var gv1 = (GroupInfoV1) group;
830 updateGroupV1(gv1, name, members, avatarFile);
831 messageBuilder = getGroupUpdateMessageBuilder(gv1);
832 g = gv1;
833 }
834 }
835
836 account.getGroupStore().updateGroup(g);
837
838 final var result = sendMessage(messageBuilder,
839 g.getMembersIncludingPendingWithout(account.getSelfRecipientId()));
840 return new Pair<>(g.getGroupId(), result.second());
841 }
842
843 private void updateGroupV1(
844 final GroupInfoV1 g, final String name, final Collection<RecipientId> members, final File avatarFile
845 ) throws IOException {
846 if (name != null) {
847 g.name = name;
848 }
849
850 if (members != null) {
851 final var newMemberAddresses = members.stream()
852 .filter(member -> !g.isMember(member))
853 .map(this::resolveSignalServiceAddress)
854 .collect(Collectors.toList());
855 final var newE164Members = new HashSet<String>();
856 for (var member : newMemberAddresses) {
857 if (!member.getNumber().isPresent()) {
858 continue;
859 }
860 newE164Members.add(member.getNumber().get());
861 }
862
863 final var registeredUsers = getRegisteredUsers(newE164Members);
864 if (registeredUsers.size() != newE164Members.size()) {
865 // Some of the new members are not registered on Signal
866 newE164Members.removeAll(registeredUsers.keySet());
867 throw new IOException("Failed to add members "
868 + String.join(", ", newE164Members)
869 + " to group: Not registered on Signal");
870 }
871
872 g.addMembers(members);
873 }
874
875 if (avatarFile != null) {
876 avatarStore.storeGroupAvatar(g.getGroupId(),
877 outputStream -> IOUtils.copyFileToStream(avatarFile, outputStream));
878 }
879 }
880
881 public Pair<GroupId, List<SendMessageResult>> joinGroup(
882 GroupInviteLinkUrl inviteLinkUrl
883 ) throws IOException, GroupLinkNotActiveException {
884 return sendJoinGroupMessage(inviteLinkUrl);
885 }
886
887 private Pair<GroupId, List<SendMessageResult>> sendJoinGroupMessage(
888 GroupInviteLinkUrl inviteLinkUrl
889 ) throws IOException, GroupLinkNotActiveException {
890 final var groupJoinInfo = groupHelper.getDecryptedGroupJoinInfo(inviteLinkUrl.getGroupMasterKey(),
891 inviteLinkUrl.getPassword());
892 final var groupChange = groupHelper.joinGroup(inviteLinkUrl.getGroupMasterKey(),
893 inviteLinkUrl.getPassword(),
894 groupJoinInfo);
895 final var group = getOrMigrateGroup(inviteLinkUrl.getGroupMasterKey(),
896 groupJoinInfo.getRevision() + 1,
897 groupChange.toByteArray());
898
899 if (group.getGroup() == null) {
900 // Only requested member, can't send update to group members
901 return new Pair<>(group.getGroupId(), List.of());
902 }
903
904 final var result = sendUpdateGroupMessage(group, group.getGroup(), groupChange);
905
906 return new Pair<>(group.getGroupId(), result.second());
907 }
908
909 private static int currentTimeDays() {
910 return (int) TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis());
911 }
912
913 private GroupsV2AuthorizationString getGroupAuthForToday(
914 final GroupSecretParams groupSecretParams
915 ) throws IOException {
916 final var today = currentTimeDays();
917 // Returns credentials for the next 7 days
918 final var credentials = groupsV2Api.getCredentials(today);
919 // TODO cache credentials until they expire
920 var authCredentialResponse = credentials.get(today);
921 try {
922 return groupsV2Api.getGroupsV2AuthorizationString(account.getUuid(),
923 today,
924 groupSecretParams,
925 authCredentialResponse);
926 } catch (VerificationFailedException e) {
927 throw new IOException(e);
928 }
929 }
930
931 private Pair<Long, List<SendMessageResult>> sendUpdateGroupMessage(
932 GroupInfoV2 group, DecryptedGroup newDecryptedGroup, GroupChange groupChange
933 ) throws IOException {
934 group.setGroup(newDecryptedGroup, this::resolveRecipient);
935 final var messageBuilder = getGroupUpdateMessageBuilder(group, groupChange.toByteArray());
936 account.getGroupStore().updateGroup(group);
937 return sendMessage(messageBuilder, group.getMembersIncludingPendingWithout(account.getSelfRecipientId()));
938 }
939
940 Pair<Long, List<SendMessageResult>> sendGroupInfoMessage(
941 GroupIdV1 groupId, SignalServiceAddress recipient
942 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, AttachmentInvalidException {
943 GroupInfoV1 g;
944 var group = getGroupForSending(groupId);
945 if (!(group instanceof GroupInfoV1)) {
946 throw new RuntimeException("Received an invalid group request for a v2 group!");
947 }
948 g = (GroupInfoV1) group;
949
950 final var recipientId = resolveRecipient(recipient);
951 if (!g.isMember(recipientId)) {
952 throw new NotAGroupMemberException(groupId, g.name);
953 }
954
955 var messageBuilder = getGroupUpdateMessageBuilder(g);
956
957 // Send group message only to the recipient who requested it
958 return sendMessage(messageBuilder, Set.of(recipientId));
959 }
960
961 private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfoV1 g) throws AttachmentInvalidException {
962 var group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.UPDATE)
963 .withId(g.getGroupId().serialize())
964 .withName(g.name)
965 .withMembers(g.getMembers()
966 .stream()
967 .map(this::resolveSignalServiceAddress)
968 .collect(Collectors.toList()));
969
970 try {
971 final var attachment = createGroupAvatarAttachment(g.getGroupId());
972 if (attachment.isPresent()) {
973 group.withAvatar(attachment.get());
974 }
975 } catch (IOException e) {
976 throw new AttachmentInvalidException(g.getGroupId().toBase64(), e);
977 }
978
979 return SignalServiceDataMessage.newBuilder()
980 .asGroupMessage(group.build())
981 .withExpiration(g.getMessageExpirationTime());
982 }
983
984 private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfoV2 g, byte[] signedGroupChange) {
985 var group = SignalServiceGroupV2.newBuilder(g.getMasterKey())
986 .withRevision(g.getGroup().getRevision())
987 .withSignedGroupChange(signedGroupChange);
988 return SignalServiceDataMessage.newBuilder()
989 .asGroupMessage(group.build())
990 .withExpiration(g.getMessageExpirationTime());
991 }
992
993 Pair<Long, List<SendMessageResult>> sendGroupInfoRequest(
994 GroupIdV1 groupId, SignalServiceAddress recipient
995 ) throws IOException {
996 var group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.REQUEST_INFO).withId(groupId.serialize());
997
998 var messageBuilder = SignalServiceDataMessage.newBuilder().asGroupMessage(group.build());
999
1000 // Send group info request message to the recipient who sent us a message with this groupId
1001 return sendMessage(messageBuilder, Set.of(resolveRecipient(recipient)));
1002 }
1003
1004 void sendReceipt(
1005 SignalServiceAddress remoteAddress, long messageId
1006 ) throws IOException, UntrustedIdentityException {
1007 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.DELIVERY,
1008 List.of(messageId),
1009 System.currentTimeMillis());
1010
1011 createMessageSender().sendReceipt(remoteAddress,
1012 unidentifiedAccessHelper.getAccessFor(resolveRecipient(remoteAddress)),
1013 receiptMessage);
1014 }
1015
1016 public Pair<Long, List<SendMessageResult>> sendMessage(
1017 String messageText, List<String> attachments, List<String> recipients
1018 ) throws IOException, AttachmentInvalidException, InvalidNumberException {
1019 final var messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
1020 if (attachments != null) {
1021 var attachmentStreams = AttachmentUtils.getSignalServiceAttachments(attachments);
1022
1023 // Upload attachments here, so we only upload once even for multiple recipients
1024 var messageSender = createMessageSender();
1025 var attachmentPointers = new ArrayList<SignalServiceAttachment>(attachmentStreams.size());
1026 for (var attachment : attachmentStreams) {
1027 if (attachment.isStream()) {
1028 attachmentPointers.add(messageSender.uploadAttachment(attachment.asStream()));
1029 } else if (attachment.isPointer()) {
1030 attachmentPointers.add(attachment.asPointer());
1031 }
1032 }
1033
1034 messageBuilder.withAttachments(attachmentPointers);
1035 }
1036 return sendMessage(messageBuilder, getSignalServiceAddresses(recipients));
1037 }
1038
1039 public Pair<Long, SendMessageResult> sendSelfMessage(
1040 String messageText, List<String> attachments
1041 ) throws IOException, AttachmentInvalidException {
1042 final var messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
1043 if (attachments != null) {
1044 messageBuilder.withAttachments(AttachmentUtils.getSignalServiceAttachments(attachments));
1045 }
1046 return sendSelfMessage(messageBuilder);
1047 }
1048
1049 public Pair<Long, List<SendMessageResult>> sendRemoteDeleteMessage(
1050 long targetSentTimestamp, List<String> recipients
1051 ) throws IOException, InvalidNumberException {
1052 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
1053 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
1054 return sendMessage(messageBuilder, getSignalServiceAddresses(recipients));
1055 }
1056
1057 public Pair<Long, List<SendMessageResult>> sendGroupRemoteDeleteMessage(
1058 long targetSentTimestamp, GroupId groupId
1059 ) throws IOException, NotAGroupMemberException, GroupNotFoundException {
1060 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
1061 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
1062 return sendGroupMessage(messageBuilder, groupId);
1063 }
1064
1065 public Pair<Long, List<SendMessageResult>> sendMessageReaction(
1066 String emoji, boolean remove, String targetAuthor, long targetSentTimestamp, List<String> recipients
1067 ) throws IOException, InvalidNumberException {
1068 var targetAuthorRecipientId = canonicalizeAndResolveRecipient(targetAuthor);
1069 var reaction = new SignalServiceDataMessage.Reaction(emoji,
1070 remove,
1071 resolveSignalServiceAddress(targetAuthorRecipientId),
1072 targetSentTimestamp);
1073 final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
1074 return sendMessage(messageBuilder, getSignalServiceAddresses(recipients));
1075 }
1076
1077 public Pair<Long, List<SendMessageResult>> sendEndSessionMessage(List<String> recipients) throws IOException, InvalidNumberException {
1078 var messageBuilder = SignalServiceDataMessage.newBuilder().asEndSessionMessage();
1079
1080 final var signalServiceAddresses = getSignalServiceAddresses(recipients);
1081 try {
1082 return sendMessage(messageBuilder, signalServiceAddresses);
1083 } catch (Exception e) {
1084 for (var address : signalServiceAddresses) {
1085 handleEndSession(address);
1086 }
1087 throw e;
1088 }
1089 }
1090
1091 SendMessageResult renewSession(RecipientId recipientId) throws IOException {
1092 account.getSessionStore().archiveSessions(recipientId);
1093 return sendNullMessage(recipientId);
1094 }
1095
1096 public String getContactName(String number) throws InvalidNumberException {
1097 var contact = account.getContactStore().getContact(canonicalizeAndResolveRecipient(number));
1098 return contact == null || contact.getName() == null ? "" : contact.getName();
1099 }
1100
1101 public void setContactName(String number, String name) throws InvalidNumberException, NotMasterDeviceException {
1102 if (!account.isMasterDevice()) {
1103 throw new NotMasterDeviceException();
1104 }
1105 final var recipientId = canonicalizeAndResolveRecipient(number);
1106 var contact = account.getContactStore().getContact(recipientId);
1107 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
1108 account.getContactStore().storeContact(recipientId, builder.withName(name).build());
1109 }
1110
1111 public void setContactBlocked(
1112 String number, boolean blocked
1113 ) throws InvalidNumberException, NotMasterDeviceException {
1114 if (!account.isMasterDevice()) {
1115 throw new NotMasterDeviceException();
1116 }
1117 setContactBlocked(canonicalizeAndResolveRecipient(number), blocked);
1118 }
1119
1120 private void setContactBlocked(RecipientId recipientId, boolean blocked) {
1121 var contact = account.getContactStore().getContact(recipientId);
1122 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
1123 account.getContactStore().storeContact(recipientId, builder.withBlocked(blocked).build());
1124 }
1125
1126 public void setGroupBlocked(final GroupId groupId, final boolean blocked) throws GroupNotFoundException {
1127 var group = getGroup(groupId);
1128 if (group == null) {
1129 throw new GroupNotFoundException(groupId);
1130 }
1131
1132 group.setBlocked(blocked);
1133 account.getGroupStore().updateGroup(group);
1134 }
1135
1136 private void setExpirationTimer(RecipientId recipientId, int messageExpirationTimer) {
1137 var contact = account.getContactStore().getContact(recipientId);
1138 if (contact != null && contact.getMessageExpirationTime() == messageExpirationTimer) {
1139 return;
1140 }
1141 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
1142 account.getContactStore()
1143 .storeContact(recipientId, builder.withMessageExpirationTime(messageExpirationTimer).build());
1144 }
1145
1146 private void sendExpirationTimerUpdate(RecipientId recipientId) throws IOException {
1147 final var messageBuilder = SignalServiceDataMessage.newBuilder().asExpirationUpdate();
1148 sendMessage(messageBuilder, Set.of(recipientId));
1149 }
1150
1151 /**
1152 * Change the expiration timer for a contact
1153 */
1154 public void setExpirationTimer(
1155 String number, int messageExpirationTimer
1156 ) throws IOException, InvalidNumberException {
1157 var recipientId = canonicalizeAndResolveRecipient(number);
1158 setExpirationTimer(recipientId, messageExpirationTimer);
1159 sendExpirationTimerUpdate(recipientId);
1160 }
1161
1162 /**
1163 * Change the expiration timer for a group
1164 */
1165 public void setExpirationTimer(GroupId groupId, int messageExpirationTimer) {
1166 var g = getGroup(groupId);
1167 if (g instanceof GroupInfoV1) {
1168 var groupInfoV1 = (GroupInfoV1) g;
1169 groupInfoV1.messageExpirationTime = messageExpirationTimer;
1170 account.getGroupStore().updateGroup(groupInfoV1);
1171 } else {
1172 throw new RuntimeException("TODO Not implemented!");
1173 }
1174 }
1175
1176 /**
1177 * Upload the sticker pack from path.
1178 *
1179 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1180 * @return if successful, returns the URL to install the sticker pack in the signal app
1181 */
1182 public String uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
1183 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
1184
1185 var messageSender = createMessageSender();
1186
1187 var packKey = KeyUtils.createStickerUploadKey();
1188 var packId = messageSender.uploadStickerManifest(manifest, packKey);
1189
1190 var sticker = new Sticker(StickerPackId.deserialize(Hex.fromStringCondensed(packId)), packKey);
1191 account.getStickerStore().updateSticker(sticker);
1192
1193 try {
1194 return new URI("https",
1195 "signal.art",
1196 "/addstickers/",
1197 "pack_id=" + URLEncoder.encode(packId, StandardCharsets.UTF_8) + "&pack_key=" + URLEncoder.encode(
1198 Hex.toStringCondensed(packKey),
1199 StandardCharsets.UTF_8)).toString();
1200 } catch (URISyntaxException e) {
1201 throw new AssertionError(e);
1202 }
1203 }
1204
1205 public void requestAllSyncData() throws IOException {
1206 requestSyncGroups();
1207 requestSyncContacts();
1208 requestSyncBlocked();
1209 requestSyncConfiguration();
1210 requestSyncKeys();
1211 }
1212
1213 private void requestSyncGroups() throws IOException {
1214 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1215 .setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS)
1216 .build();
1217 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1218 try {
1219 sendSyncMessage(message);
1220 } catch (UntrustedIdentityException e) {
1221 throw new AssertionError(e);
1222 }
1223 }
1224
1225 private void requestSyncContacts() throws IOException {
1226 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1227 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS)
1228 .build();
1229 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1230 try {
1231 sendSyncMessage(message);
1232 } catch (UntrustedIdentityException e) {
1233 throw new AssertionError(e);
1234 }
1235 }
1236
1237 private void requestSyncBlocked() throws IOException {
1238 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1239 .setType(SignalServiceProtos.SyncMessage.Request.Type.BLOCKED)
1240 .build();
1241 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1242 try {
1243 sendSyncMessage(message);
1244 } catch (UntrustedIdentityException e) {
1245 throw new AssertionError(e);
1246 }
1247 }
1248
1249 private void requestSyncConfiguration() throws IOException {
1250 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1251 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONFIGURATION)
1252 .build();
1253 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1254 try {
1255 sendSyncMessage(message);
1256 } catch (UntrustedIdentityException e) {
1257 throw new AssertionError(e);
1258 }
1259 }
1260
1261 private void requestSyncKeys() throws IOException {
1262 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1263 .setType(SignalServiceProtos.SyncMessage.Request.Type.KEYS)
1264 .build();
1265 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1266 try {
1267 sendSyncMessage(message);
1268 } catch (UntrustedIdentityException e) {
1269 throw new AssertionError(e);
1270 }
1271 }
1272
1273 private byte[] getSenderCertificate() {
1274 // TODO support UUID capable sender certificates
1275 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1276 byte[] certificate;
1277 try {
1278 certificate = accountManager.getSenderCertificate();
1279 } catch (IOException e) {
1280 logger.warn("Failed to get sender certificate, ignoring: {}", e.getMessage());
1281 return null;
1282 }
1283 // TODO cache for a day
1284 return certificate;
1285 }
1286
1287 private void sendSyncMessage(SignalServiceSyncMessage message) throws IOException, UntrustedIdentityException {
1288 var messageSender = createMessageSender();
1289 messageSender.sendMessage(message, unidentifiedAccessHelper.getAccessForSync());
1290 }
1291
1292 private Set<RecipientId> getSignalServiceAddresses(Collection<String> numbers) throws InvalidNumberException {
1293 final var signalServiceAddresses = new HashSet<SignalServiceAddress>(numbers.size());
1294 final var addressesMissingUuid = new HashSet<SignalServiceAddress>();
1295
1296 for (var number : numbers) {
1297 final var resolvedAddress = resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number));
1298 if (resolvedAddress.getUuid().isPresent()) {
1299 signalServiceAddresses.add(resolvedAddress);
1300 } else {
1301 addressesMissingUuid.add(resolvedAddress);
1302 }
1303 }
1304
1305 final var numbersMissingUuid = addressesMissingUuid.stream()
1306 .map(a -> a.getNumber().get())
1307 .collect(Collectors.toSet());
1308 Map<String, UUID> registeredUsers;
1309 try {
1310 registeredUsers = getRegisteredUsers(numbersMissingUuid);
1311 } catch (IOException e) {
1312 logger.warn("Failed to resolve uuids from server, ignoring: {}", e.getMessage());
1313 registeredUsers = Map.of();
1314 }
1315
1316 for (var address : addressesMissingUuid) {
1317 final var number = address.getNumber().get();
1318 if (registeredUsers.containsKey(number)) {
1319 final var newAddress = resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1320 registeredUsers.get(number),
1321 number)));
1322 signalServiceAddresses.add(newAddress);
1323 } else {
1324 signalServiceAddresses.add(address);
1325 }
1326 }
1327
1328 return signalServiceAddresses.stream().map(this::resolveRecipient).collect(Collectors.toSet());
1329 }
1330
1331 private RecipientId refreshRegisteredUser(RecipientId recipientId) throws IOException {
1332 final var address = resolveSignalServiceAddress(recipientId);
1333 if (!address.getNumber().isPresent()) {
1334 return recipientId;
1335 }
1336 final var number = address.getNumber().get();
1337 final var uuidMap = getRegisteredUsers(Set.of(number));
1338 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap.getOrDefault(number, null), number));
1339 }
1340
1341 private Map<String, UUID> getRegisteredUsers(final Set<String> numbers) throws IOException {
1342 try {
1343 return accountManager.getRegisteredUsers(ServiceConfig.getIasKeyStore(),
1344 numbers,
1345 serviceEnvironmentConfig.getCdsMrenclave());
1346 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
1347 throw new IOException(e);
1348 }
1349 }
1350
1351 private Pair<Long, List<SendMessageResult>> sendMessage(
1352 SignalServiceDataMessage.Builder messageBuilder, Set<RecipientId> recipientIds
1353 ) throws IOException {
1354 final var timestamp = System.currentTimeMillis();
1355 messageBuilder.withTimestamp(timestamp);
1356 getOrCreateMessagePipe();
1357 getOrCreateUnidentifiedMessagePipe();
1358 SignalServiceDataMessage message = null;
1359 try {
1360 message = messageBuilder.build();
1361 if (message.getGroupContext().isPresent()) {
1362 try {
1363 var messageSender = createMessageSender();
1364 final var isRecipientUpdate = false;
1365 final var recipientIdList = new ArrayList<>(recipientIds);
1366 final var addresses = recipientIdList.stream()
1367 .map(this::resolveSignalServiceAddress)
1368 .collect(Collectors.toList());
1369 var result = messageSender.sendMessage(addresses,
1370 unidentifiedAccessHelper.getAccessFor(recipientIdList),
1371 isRecipientUpdate,
1372 message);
1373
1374 for (var r : result) {
1375 if (r.getIdentityFailure() != null) {
1376 final var recipientId = resolveRecipient(r.getAddress());
1377 final var newIdentity = account.getIdentityKeyStore()
1378 .saveIdentity(recipientId, r.getIdentityFailure().getIdentityKey(), new Date());
1379 if (newIdentity) {
1380 account.getSessionStore().archiveSessions(recipientId);
1381 }
1382 }
1383 }
1384
1385 return new Pair<>(timestamp, result);
1386 } catch (UntrustedIdentityException e) {
1387 return new Pair<>(timestamp, List.of());
1388 }
1389 } else {
1390 // Send to all individually, so sync messages are sent correctly
1391 messageBuilder.withProfileKey(account.getProfileKey().serialize());
1392 var results = new ArrayList<SendMessageResult>(recipientIds.size());
1393 for (var recipientId : recipientIds) {
1394 final var contact = account.getContactStore().getContact(recipientId);
1395 final var expirationTime = contact != null ? contact.getMessageExpirationTime() : 0;
1396 messageBuilder.withExpiration(expirationTime);
1397 message = messageBuilder.build();
1398 results.add(sendMessage(recipientId, message));
1399 }
1400 return new Pair<>(timestamp, results);
1401 }
1402 } finally {
1403 if (message != null && message.isEndSession()) {
1404 for (var recipient : recipientIds) {
1405 handleEndSession(recipient);
1406 }
1407 }
1408 }
1409 }
1410
1411 private Pair<Long, SendMessageResult> sendSelfMessage(
1412 SignalServiceDataMessage.Builder messageBuilder
1413 ) throws IOException {
1414 final var timestamp = System.currentTimeMillis();
1415 messageBuilder.withTimestamp(timestamp);
1416 getOrCreateMessagePipe();
1417 getOrCreateUnidentifiedMessagePipe();
1418 final var recipientId = account.getSelfRecipientId();
1419
1420 final var contact = account.getContactStore().getContact(recipientId);
1421 final var expirationTime = contact != null ? contact.getMessageExpirationTime() : 0;
1422 messageBuilder.withExpiration(expirationTime);
1423
1424 var message = messageBuilder.build();
1425 final var result = sendSelfMessage(message);
1426 return new Pair<>(timestamp, result);
1427 }
1428
1429 private SendMessageResult sendSelfMessage(SignalServiceDataMessage message) throws IOException {
1430 var messageSender = createMessageSender();
1431
1432 var recipientId = account.getSelfRecipientId();
1433
1434 final var unidentifiedAccess = unidentifiedAccessHelper.getAccessFor(recipientId);
1435 var recipient = resolveSignalServiceAddress(recipientId);
1436 var transcript = new SentTranscriptMessage(Optional.of(recipient),
1437 message.getTimestamp(),
1438 message,
1439 message.getExpiresInSeconds(),
1440 Map.of(recipient, unidentifiedAccess.isPresent()),
1441 false);
1442 var syncMessage = SignalServiceSyncMessage.forSentTranscript(transcript);
1443
1444 try {
1445 var startTime = System.currentTimeMillis();
1446 messageSender.sendMessage(syncMessage, unidentifiedAccess);
1447 return SendMessageResult.success(recipient,
1448 unidentifiedAccess.isPresent(),
1449 false,
1450 System.currentTimeMillis() - startTime);
1451 } catch (UntrustedIdentityException e) {
1452 return SendMessageResult.identityFailure(recipient, e.getIdentityKey());
1453 }
1454 }
1455
1456 private SendMessageResult sendMessage(
1457 RecipientId recipientId, SignalServiceDataMessage message
1458 ) throws IOException {
1459 var messageSender = createMessageSender();
1460
1461 final var address = resolveSignalServiceAddress(recipientId);
1462 try {
1463 try {
1464 return messageSender.sendMessage(address, unidentifiedAccessHelper.getAccessFor(recipientId), message);
1465 } catch (UnregisteredUserException e) {
1466 final var newRecipientId = refreshRegisteredUser(recipientId);
1467 return messageSender.sendMessage(resolveSignalServiceAddress(newRecipientId),
1468 unidentifiedAccessHelper.getAccessFor(newRecipientId),
1469 message);
1470 }
1471 } catch (UntrustedIdentityException e) {
1472 return SendMessageResult.identityFailure(address, e.getIdentityKey());
1473 }
1474 }
1475
1476 private SendMessageResult sendNullMessage(RecipientId recipientId) throws IOException {
1477 var messageSender = createMessageSender();
1478
1479 final var address = resolveSignalServiceAddress(recipientId);
1480 try {
1481 try {
1482 return messageSender.sendNullMessage(address, unidentifiedAccessHelper.getAccessFor(recipientId));
1483 } catch (UnregisteredUserException e) {
1484 final var newRecipientId = refreshRegisteredUser(recipientId);
1485 final var newAddress = resolveSignalServiceAddress(newRecipientId);
1486 return messageSender.sendNullMessage(newAddress, unidentifiedAccessHelper.getAccessFor(newRecipientId));
1487 }
1488 } catch (UntrustedIdentityException e) {
1489 return SendMessageResult.identityFailure(address, e.getIdentityKey());
1490 }
1491 }
1492
1493 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, SelfSendException, UnsupportedDataMessageException, org.whispersystems.libsignal.UntrustedIdentityException {
1494 var cipher = new SignalServiceCipher(account.getSelfAddress(),
1495 account.getSignalProtocolStore(),
1496 certificateValidator);
1497 try {
1498 return cipher.decrypt(envelope);
1499 } catch (ProtocolUntrustedIdentityException e) {
1500 if (e.getCause() instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
1501 throw (org.whispersystems.libsignal.UntrustedIdentityException) e.getCause();
1502 }
1503 throw new AssertionError(e);
1504 }
1505 }
1506
1507 private void handleEndSession(RecipientId recipientId) {
1508 account.getSessionStore().deleteAllSessions(recipientId);
1509 }
1510
1511 private List<HandleAction> handleSignalServiceDataMessage(
1512 SignalServiceDataMessage message,
1513 boolean isSync,
1514 SignalServiceAddress source,
1515 SignalServiceAddress destination,
1516 boolean ignoreAttachments
1517 ) {
1518 var actions = new ArrayList<HandleAction>();
1519 if (message.getGroupContext().isPresent()) {
1520 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1521 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1522 var groupId = GroupId.v1(groupInfo.getGroupId());
1523 var group = getGroup(groupId);
1524 if (group == null || group instanceof GroupInfoV1) {
1525 var groupV1 = (GroupInfoV1) group;
1526 switch (groupInfo.getType()) {
1527 case UPDATE: {
1528 if (groupV1 == null) {
1529 groupV1 = new GroupInfoV1(groupId);
1530 }
1531
1532 if (groupInfo.getAvatar().isPresent()) {
1533 var avatar = groupInfo.getAvatar().get();
1534 downloadGroupAvatar(avatar, groupV1.getGroupId());
1535 }
1536
1537 if (groupInfo.getName().isPresent()) {
1538 groupV1.name = groupInfo.getName().get();
1539 }
1540
1541 if (groupInfo.getMembers().isPresent()) {
1542 groupV1.addMembers(groupInfo.getMembers()
1543 .get()
1544 .stream()
1545 .map(this::resolveRecipient)
1546 .collect(Collectors.toSet()));
1547 }
1548
1549 account.getGroupStore().updateGroup(groupV1);
1550 break;
1551 }
1552 case DELIVER:
1553 if (groupV1 == null && !isSync) {
1554 actions.add(new SendGroupInfoRequestAction(source, groupId));
1555 }
1556 break;
1557 case QUIT: {
1558 if (groupV1 != null) {
1559 groupV1.removeMember(resolveRecipient(source));
1560 account.getGroupStore().updateGroup(groupV1);
1561 }
1562 break;
1563 }
1564 case REQUEST_INFO:
1565 if (groupV1 != null && !isSync) {
1566 actions.add(new SendGroupInfoAction(source, groupV1.getGroupId()));
1567 }
1568 break;
1569 }
1570 } else {
1571 // Received a group v1 message for a v2 group
1572 }
1573 }
1574 if (message.getGroupContext().get().getGroupV2().isPresent()) {
1575 final var groupContext = message.getGroupContext().get().getGroupV2().get();
1576 final var groupMasterKey = groupContext.getMasterKey();
1577
1578 getOrMigrateGroup(groupMasterKey,
1579 groupContext.getRevision(),
1580 groupContext.hasSignedGroupChange() ? groupContext.getSignedGroupChange() : null);
1581 }
1582 }
1583
1584 final var conversationPartnerAddress = isSync ? destination : source;
1585 if (conversationPartnerAddress != null && message.isEndSession()) {
1586 handleEndSession(resolveRecipient(conversationPartnerAddress));
1587 }
1588 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
1589 if (message.getGroupContext().isPresent()) {
1590 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1591 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1592 var group = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(groupInfo.getGroupId()));
1593 if (group != null) {
1594 if (group.messageExpirationTime != message.getExpiresInSeconds()) {
1595 group.messageExpirationTime = message.getExpiresInSeconds();
1596 account.getGroupStore().updateGroup(group);
1597 }
1598 }
1599 } else if (message.getGroupContext().get().getGroupV2().isPresent()) {
1600 // disappearing message timer already stored in the DecryptedGroup
1601 }
1602 } else if (conversationPartnerAddress != null) {
1603 setExpirationTimer(resolveRecipient(conversationPartnerAddress), message.getExpiresInSeconds());
1604 }
1605 }
1606 if (!ignoreAttachments) {
1607 if (message.getAttachments().isPresent()) {
1608 for (var attachment : message.getAttachments().get()) {
1609 downloadAttachment(attachment);
1610 }
1611 }
1612 if (message.getSharedContacts().isPresent()) {
1613 for (var contact : message.getSharedContacts().get()) {
1614 if (contact.getAvatar().isPresent()) {
1615 downloadAttachment(contact.getAvatar().get().getAttachment());
1616 }
1617 }
1618 }
1619 }
1620 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
1621 final ProfileKey profileKey;
1622 try {
1623 profileKey = new ProfileKey(message.getProfileKey().get());
1624 } catch (InvalidInputException e) {
1625 throw new AssertionError(e);
1626 }
1627 if (source.matches(account.getSelfAddress())) {
1628 this.account.setProfileKey(profileKey);
1629 }
1630 this.account.getProfileStore().storeProfileKey(resolveRecipient(source), profileKey);
1631 }
1632 if (message.getPreviews().isPresent()) {
1633 final var previews = message.getPreviews().get();
1634 for (var preview : previews) {
1635 if (preview.getImage().isPresent()) {
1636 downloadAttachment(preview.getImage().get());
1637 }
1638 }
1639 }
1640 if (message.getQuote().isPresent()) {
1641 final var quote = message.getQuote().get();
1642
1643 for (var quotedAttachment : quote.getAttachments()) {
1644 final var thumbnail = quotedAttachment.getThumbnail();
1645 if (thumbnail != null) {
1646 downloadAttachment(thumbnail);
1647 }
1648 }
1649 }
1650 if (message.getSticker().isPresent()) {
1651 final var messageSticker = message.getSticker().get();
1652 final var stickerPackId = StickerPackId.deserialize(messageSticker.getPackId());
1653 var sticker = account.getStickerStore().getSticker(stickerPackId);
1654 if (sticker == null) {
1655 sticker = new Sticker(stickerPackId, messageSticker.getPackKey());
1656 account.getStickerStore().updateSticker(sticker);
1657 }
1658 }
1659 return actions;
1660 }
1661
1662 private GroupInfoV2 getOrMigrateGroup(
1663 final GroupMasterKey groupMasterKey, final int revision, final byte[] signedGroupChange
1664 ) {
1665 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
1666
1667 var groupId = GroupUtils.getGroupIdV2(groupSecretParams);
1668 var groupInfo = getGroup(groupId);
1669 final GroupInfoV2 groupInfoV2;
1670 if (groupInfo instanceof GroupInfoV1) {
1671 // Received a v2 group message for a v1 group, we need to locally migrate the group
1672 account.getGroupStore().deleteGroupV1(((GroupInfoV1) groupInfo).getGroupId());
1673 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1674 logger.info("Locally migrated group {} to group v2, id: {}",
1675 groupInfo.getGroupId().toBase64(),
1676 groupInfoV2.getGroupId().toBase64());
1677 } else if (groupInfo instanceof GroupInfoV2) {
1678 groupInfoV2 = (GroupInfoV2) groupInfo;
1679 } else {
1680 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1681 }
1682
1683 if (groupInfoV2.getGroup() == null || groupInfoV2.getGroup().getRevision() < revision) {
1684 DecryptedGroup group = null;
1685 if (signedGroupChange != null
1686 && groupInfoV2.getGroup() != null
1687 && groupInfoV2.getGroup().getRevision() + 1 == revision) {
1688 group = groupHelper.getUpdatedDecryptedGroup(groupInfoV2.getGroup(), signedGroupChange, groupMasterKey);
1689 }
1690 if (group == null) {
1691 group = groupHelper.getDecryptedGroup(groupSecretParams);
1692 }
1693 if (group != null) {
1694 storeProfileKeysFromMembers(group);
1695 final var avatar = group.getAvatar();
1696 if (avatar != null && !avatar.isEmpty()) {
1697 downloadGroupAvatar(groupId, groupSecretParams, avatar);
1698 }
1699 }
1700 groupInfoV2.setGroup(group, this::resolveRecipient);
1701 account.getGroupStore().updateGroup(groupInfoV2);
1702 }
1703
1704 return groupInfoV2;
1705 }
1706
1707 private void storeProfileKeysFromMembers(final DecryptedGroup group) {
1708 for (var member : group.getMembersList()) {
1709 final var uuid = UuidUtil.parseOrThrow(member.getUuid().toByteArray());
1710 final var recipientId = account.getRecipientStore().resolveRecipient(uuid);
1711 try {
1712 account.getProfileStore()
1713 .storeProfileKey(recipientId, new ProfileKey(member.getProfileKey().toByteArray()));
1714 } catch (InvalidInputException ignored) {
1715 }
1716 }
1717 }
1718
1719 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1720 Set<HandleAction> queuedActions = new HashSet<>();
1721 for (var cachedMessage : account.getMessageCache().getCachedMessages()) {
1722 var actions = retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
1723 if (actions != null) {
1724 queuedActions.addAll(actions);
1725 }
1726 }
1727 for (var action : queuedActions) {
1728 try {
1729 action.execute(this);
1730 } catch (Throwable e) {
1731 logger.warn("Message action failed.", e);
1732 }
1733 }
1734 }
1735
1736 private List<HandleAction> retryFailedReceivedMessage(
1737 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
1738 ) {
1739 var envelope = cachedMessage.loadEnvelope();
1740 if (envelope == null) {
1741 return null;
1742 }
1743 SignalServiceContent content = null;
1744 List<HandleAction> actions = null;
1745 if (!envelope.isReceipt()) {
1746 try {
1747 content = decryptMessage(envelope);
1748 } catch (org.whispersystems.libsignal.UntrustedIdentityException e) {
1749 if (!envelope.hasSource()) {
1750 final var identifier = ((org.whispersystems.libsignal.UntrustedIdentityException) e).getName();
1751 final var recipientId = resolveRecipient(identifier);
1752 try {
1753 account.getMessageCache().replaceSender(cachedMessage, recipientId);
1754 } catch (IOException ioException) {
1755 logger.warn("Failed to move cached message to recipient folder: {}", ioException.getMessage());
1756 }
1757 }
1758 return null;
1759 } catch (Exception er) {
1760 // All other errors are not recoverable, so delete the cached message
1761 cachedMessage.delete();
1762 return null;
1763 }
1764 actions = handleMessage(envelope, content, ignoreAttachments);
1765 }
1766 handler.handleMessage(envelope, content, null);
1767 cachedMessage.delete();
1768 return actions;
1769 }
1770
1771 public void receiveMessages(
1772 long timeout,
1773 TimeUnit unit,
1774 boolean returnOnTimeout,
1775 boolean ignoreAttachments,
1776 ReceiveMessageHandler handler
1777 ) throws IOException {
1778 retryFailedReceivedMessages(handler, ignoreAttachments);
1779
1780 Set<HandleAction> queuedActions = null;
1781
1782 final var messagePipe = getOrCreateMessagePipe();
1783
1784 var hasCaughtUpWithOldMessages = false;
1785
1786 while (true) {
1787 SignalServiceEnvelope envelope;
1788 SignalServiceContent content = null;
1789 Exception exception = null;
1790 final CachedMessage[] cachedMessage = {null};
1791 try {
1792 var result = messagePipe.readOrEmpty(timeout, unit, envelope1 -> {
1793 final var recipientId = envelope1.hasSource()
1794 ? resolveRecipient(envelope1.getSourceIdentifier())
1795 : null;
1796 // store message on disk, before acknowledging receipt to the server
1797 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
1798 });
1799 if (result.isPresent()) {
1800 envelope = result.get();
1801 } else {
1802 // Received indicator that server queue is empty
1803 hasCaughtUpWithOldMessages = true;
1804
1805 if (queuedActions != null) {
1806 for (var action : queuedActions) {
1807 try {
1808 action.execute(this);
1809 } catch (Throwable e) {
1810 logger.warn("Message action failed.", e);
1811 }
1812 }
1813 queuedActions.clear();
1814 queuedActions = null;
1815 }
1816
1817 // Continue to wait another timeout for new messages
1818 continue;
1819 }
1820 } catch (TimeoutException e) {
1821 if (returnOnTimeout) return;
1822 continue;
1823 }
1824
1825 if (envelope.hasSource()) {
1826 // Store uuid if we don't have it already
1827 resolveRecipientTrusted(envelope.getSourceAddress());
1828 }
1829 final var notAGroupMember = isNotAGroupMember(envelope, content);
1830 if (!envelope.isReceipt()) {
1831 try {
1832 content = decryptMessage(envelope);
1833 } catch (Exception e) {
1834 exception = e;
1835 }
1836 var actions = handleMessage(envelope, content, ignoreAttachments);
1837 if (exception instanceof ProtocolInvalidMessageException) {
1838 final var sender = resolveRecipient(((ProtocolInvalidMessageException) exception).getSender());
1839 logger.debug("Received invalid message, queuing renew session action.");
1840 actions.add(new RenewSessionAction(sender));
1841 }
1842 if (hasCaughtUpWithOldMessages) {
1843 for (var action : actions) {
1844 try {
1845 action.execute(this);
1846 } catch (Throwable e) {
1847 logger.warn("Message action failed.", e);
1848 }
1849 }
1850 } else {
1851 if (queuedActions == null) {
1852 queuedActions = new HashSet<>();
1853 }
1854 queuedActions.addAll(actions);
1855 }
1856 }
1857 if (isMessageBlocked(envelope, content)) {
1858 logger.info("Ignoring a message from blocked user/group: {}", envelope.getTimestamp());
1859 } else if (notAGroupMember) {
1860 logger.info("Ignoring a message from a non group member: {}", envelope.getTimestamp());
1861 } else {
1862 handler.handleMessage(envelope, content, exception);
1863 }
1864 if (cachedMessage[0] != null) {
1865 if (exception instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
1866 final var identifier = ((org.whispersystems.libsignal.UntrustedIdentityException) exception).getName();
1867 final var recipientId = resolveRecipient(identifier);
1868 queuedActions.add(new RetrieveProfileAction(recipientId));
1869 if (!envelope.hasSource()) {
1870 try {
1871 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
1872 } catch (IOException ioException) {
1873 logger.warn("Failed to move cached message to recipient folder: {}",
1874 ioException.getMessage());
1875 }
1876 }
1877 } else {
1878 cachedMessage[0].delete();
1879 }
1880 }
1881 }
1882 }
1883
1884 private boolean isMessageBlocked(
1885 SignalServiceEnvelope envelope, SignalServiceContent content
1886 ) {
1887 SignalServiceAddress source;
1888 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1889 source = envelope.getSourceAddress();
1890 } else if (content != null) {
1891 source = content.getSender();
1892 } else {
1893 return false;
1894 }
1895 final var recipientId = resolveRecipient(source);
1896 if (isContactBlocked(recipientId)) {
1897 return true;
1898 }
1899
1900 if (content != null && content.getDataMessage().isPresent()) {
1901 var message = content.getDataMessage().get();
1902 if (message.getGroupContext().isPresent()) {
1903 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1904 var group = getGroup(groupId);
1905 if (group != null && group.isBlocked()) {
1906 return true;
1907 }
1908 }
1909 }
1910 return false;
1911 }
1912
1913 public boolean isContactBlocked(final String identifier) throws InvalidNumberException {
1914 final var recipientId = canonicalizeAndResolveRecipient(identifier);
1915 return isContactBlocked(recipientId);
1916 }
1917
1918 private boolean isContactBlocked(final RecipientId recipientId) {
1919 var sourceContact = account.getContactStore().getContact(recipientId);
1920 return sourceContact != null && sourceContact.isBlocked();
1921 }
1922
1923 private boolean isNotAGroupMember(
1924 SignalServiceEnvelope envelope, SignalServiceContent content
1925 ) {
1926 SignalServiceAddress source;
1927 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1928 source = envelope.getSourceAddress();
1929 } else if (content != null) {
1930 source = content.getSender();
1931 } else {
1932 return false;
1933 }
1934
1935 if (content != null && content.getDataMessage().isPresent()) {
1936 var message = content.getDataMessage().get();
1937 if (message.getGroupContext().isPresent()) {
1938 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1939 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1940 if (groupInfo.getType() == SignalServiceGroup.Type.QUIT) {
1941 return false;
1942 }
1943 }
1944 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1945 var group = getGroup(groupId);
1946 if (group != null && !group.isMember(resolveRecipient(source))) {
1947 return true;
1948 }
1949 }
1950 }
1951 return false;
1952 }
1953
1954 private List<HandleAction> handleMessage(
1955 SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments
1956 ) {
1957 var actions = new ArrayList<HandleAction>();
1958 if (content != null) {
1959 final SignalServiceAddress sender;
1960 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1961 sender = envelope.getSourceAddress();
1962 } else {
1963 sender = content.getSender();
1964 }
1965
1966 if (content.getDataMessage().isPresent()) {
1967 var message = content.getDataMessage().get();
1968
1969 if (content.isNeedsReceipt()) {
1970 actions.add(new SendReceiptAction(sender, message.getTimestamp()));
1971 }
1972
1973 actions.addAll(handleSignalServiceDataMessage(message,
1974 false,
1975 sender,
1976 account.getSelfAddress(),
1977 ignoreAttachments));
1978 }
1979 if (content.getSyncMessage().isPresent()) {
1980 account.setMultiDevice(true);
1981 var syncMessage = content.getSyncMessage().get();
1982 if (syncMessage.getSent().isPresent()) {
1983 var message = syncMessage.getSent().get();
1984 final var destination = message.getDestination().orNull();
1985 actions.addAll(handleSignalServiceDataMessage(message.getMessage(),
1986 true,
1987 sender,
1988 destination,
1989 ignoreAttachments));
1990 }
1991 if (syncMessage.getRequest().isPresent() && account.isMasterDevice()) {
1992 var rm = syncMessage.getRequest().get();
1993 if (rm.isContactsRequest()) {
1994 actions.add(SendSyncContactsAction.create());
1995 }
1996 if (rm.isGroupsRequest()) {
1997 actions.add(SendSyncGroupsAction.create());
1998 }
1999 if (rm.isBlockedListRequest()) {
2000 actions.add(SendSyncBlockedListAction.create());
2001 }
2002 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2003 }
2004 if (syncMessage.getGroups().isPresent()) {
2005 File tmpFile = null;
2006 try {
2007 tmpFile = IOUtils.createTempFile();
2008 final var groupsMessage = syncMessage.getGroups().get();
2009 try (var attachmentAsStream = retrieveAttachmentAsStream(groupsMessage.asPointer(), tmpFile)) {
2010 var s = new DeviceGroupsInputStream(attachmentAsStream);
2011 DeviceGroup g;
2012 while ((g = s.read()) != null) {
2013 var syncGroup = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(g.getId()));
2014 if (syncGroup != null) {
2015 if (g.getName().isPresent()) {
2016 syncGroup.name = g.getName().get();
2017 }
2018 syncGroup.addMembers(g.getMembers()
2019 .stream()
2020 .map(this::resolveRecipient)
2021 .collect(Collectors.toSet()));
2022 if (!g.isActive()) {
2023 syncGroup.removeMember(account.getSelfRecipientId());
2024 } else {
2025 // Add ourself to the member set as it's marked as active
2026 syncGroup.addMembers(List.of(account.getSelfRecipientId()));
2027 }
2028 syncGroup.blocked = g.isBlocked();
2029 if (g.getColor().isPresent()) {
2030 syncGroup.color = g.getColor().get();
2031 }
2032
2033 if (g.getAvatar().isPresent()) {
2034 downloadGroupAvatar(g.getAvatar().get(), syncGroup.getGroupId());
2035 }
2036 syncGroup.archived = g.isArchived();
2037 account.getGroupStore().updateGroup(syncGroup);
2038 }
2039 }
2040 }
2041 } catch (Exception e) {
2042 logger.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2043 tmpFile,
2044 e.getMessage());
2045 } finally {
2046 if (tmpFile != null) {
2047 try {
2048 Files.delete(tmpFile.toPath());
2049 } catch (IOException e) {
2050 logger.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2051 tmpFile,
2052 e.getMessage());
2053 }
2054 }
2055 }
2056 }
2057 if (syncMessage.getBlockedList().isPresent()) {
2058 final var blockedListMessage = syncMessage.getBlockedList().get();
2059 for (var address : blockedListMessage.getAddresses()) {
2060 setContactBlocked(resolveRecipient(address), true);
2061 }
2062 for (var groupId : blockedListMessage.getGroupIds()
2063 .stream()
2064 .map(GroupId::unknownVersion)
2065 .collect(Collectors.toSet())) {
2066 try {
2067 setGroupBlocked(groupId, true);
2068 } catch (GroupNotFoundException e) {
2069 logger.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2070 groupId.toBase64());
2071 }
2072 }
2073 }
2074 if (syncMessage.getContacts().isPresent()) {
2075 File tmpFile = null;
2076 try {
2077 tmpFile = IOUtils.createTempFile();
2078 final var contactsMessage = syncMessage.getContacts().get();
2079 try (var attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream()
2080 .asPointer(), tmpFile)) {
2081 var s = new DeviceContactsInputStream(attachmentAsStream);
2082 DeviceContact c;
2083 while ((c = s.read()) != null) {
2084 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
2085 account.setProfileKey(c.getProfileKey().get());
2086 }
2087 final var recipientId = resolveRecipientTrusted(c.getAddress());
2088 var contact = account.getContactStore().getContact(recipientId);
2089 final var builder = contact == null
2090 ? Contact.newBuilder()
2091 : Contact.newBuilder(contact);
2092 if (c.getName().isPresent()) {
2093 builder.withName(c.getName().get());
2094 }
2095 if (c.getColor().isPresent()) {
2096 builder.withColor(c.getColor().get());
2097 }
2098 if (c.getProfileKey().isPresent()) {
2099 account.getProfileStore().storeProfileKey(recipientId, c.getProfileKey().get());
2100 }
2101 if (c.getVerified().isPresent()) {
2102 final var verifiedMessage = c.getVerified().get();
2103 account.getIdentityKeyStore()
2104 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
2105 verifiedMessage.getIdentityKey(),
2106 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2107 }
2108 if (c.getExpirationTimer().isPresent()) {
2109 builder.withMessageExpirationTime(c.getExpirationTimer().get());
2110 }
2111 builder.withBlocked(c.isBlocked());
2112 builder.withArchived(c.isArchived());
2113 account.getContactStore().storeContact(recipientId, builder.build());
2114
2115 if (c.getAvatar().isPresent()) {
2116 downloadContactAvatar(c.getAvatar().get(), c.getAddress());
2117 }
2118 }
2119 }
2120 } catch (Exception e) {
2121 logger.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2122 tmpFile,
2123 e.getMessage());
2124 } finally {
2125 if (tmpFile != null) {
2126 try {
2127 Files.delete(tmpFile.toPath());
2128 } catch (IOException e) {
2129 logger.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2130 tmpFile,
2131 e.getMessage());
2132 }
2133 }
2134 }
2135 }
2136 if (syncMessage.getVerified().isPresent()) {
2137 final var verifiedMessage = syncMessage.getVerified().get();
2138 account.getIdentityKeyStore()
2139 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
2140 verifiedMessage.getIdentityKey(),
2141 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2142 }
2143 if (syncMessage.getStickerPackOperations().isPresent()) {
2144 final var stickerPackOperationMessages = syncMessage.getStickerPackOperations().get();
2145 for (var m : stickerPackOperationMessages) {
2146 if (!m.getPackId().isPresent()) {
2147 continue;
2148 }
2149 final var stickerPackId = StickerPackId.deserialize(m.getPackId().get());
2150 var sticker = account.getStickerStore().getSticker(stickerPackId);
2151 if (sticker == null) {
2152 if (!m.getPackKey().isPresent()) {
2153 continue;
2154 }
2155 sticker = new Sticker(stickerPackId, m.getPackKey().get());
2156 }
2157 sticker.setInstalled(!m.getType().isPresent()
2158 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL);
2159 account.getStickerStore().updateSticker(sticker);
2160 }
2161 }
2162 if (syncMessage.getFetchType().isPresent()) {
2163 switch (syncMessage.getFetchType().get()) {
2164 case LOCAL_PROFILE:
2165 getRecipientProfile(account.getSelfRecipientId(), true);
2166 case STORAGE_MANIFEST:
2167 // TODO
2168 }
2169 }
2170 if (syncMessage.getKeys().isPresent()) {
2171 final var keysMessage = syncMessage.getKeys().get();
2172 if (keysMessage.getStorageService().isPresent()) {
2173 final var storageKey = keysMessage.getStorageService().get();
2174 account.setStorageKey(storageKey);
2175 }
2176 }
2177 if (syncMessage.getConfiguration().isPresent()) {
2178 // TODO
2179 }
2180 }
2181 }
2182 return actions;
2183 }
2184
2185 private void downloadContactAvatar(SignalServiceAttachment avatar, SignalServiceAddress address) {
2186 try {
2187 avatarStore.storeContactAvatar(address, outputStream -> retrieveAttachment(avatar, outputStream));
2188 } catch (IOException e) {
2189 logger.warn("Failed to download avatar for contact {}, ignoring: {}", address, e.getMessage());
2190 }
2191 }
2192
2193 private void downloadGroupAvatar(SignalServiceAttachment avatar, GroupId groupId) {
2194 try {
2195 avatarStore.storeGroupAvatar(groupId, outputStream -> retrieveAttachment(avatar, outputStream));
2196 } catch (IOException e) {
2197 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2198 }
2199 }
2200
2201 private void downloadGroupAvatar(GroupId groupId, GroupSecretParams groupSecretParams, String cdnKey) {
2202 try {
2203 avatarStore.storeGroupAvatar(groupId,
2204 outputStream -> retrieveGroupV2Avatar(groupSecretParams, cdnKey, outputStream));
2205 } catch (IOException e) {
2206 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2207 }
2208 }
2209
2210 private void downloadProfileAvatar(
2211 SignalServiceAddress address, String avatarPath, ProfileKey profileKey
2212 ) {
2213 try {
2214 avatarStore.storeProfileAvatar(address,
2215 outputStream -> retrieveProfileAvatar(avatarPath, profileKey, outputStream));
2216 } catch (Throwable e) {
2217 logger.warn("Failed to download profile avatar, ignoring: {}", e.getMessage());
2218 }
2219 }
2220
2221 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
2222 return attachmentStore.getAttachmentFile(attachmentId);
2223 }
2224
2225 private void downloadAttachment(final SignalServiceAttachment attachment) {
2226 if (!attachment.isPointer()) {
2227 logger.warn("Invalid state, can't store an attachment stream.");
2228 }
2229
2230 var pointer = attachment.asPointer();
2231 if (pointer.getPreview().isPresent()) {
2232 final var preview = pointer.getPreview().get();
2233 try {
2234 attachmentStore.storeAttachmentPreview(pointer.getRemoteId(),
2235 outputStream -> outputStream.write(preview, 0, preview.length));
2236 } catch (IOException e) {
2237 logger.warn("Failed to download attachment preview, ignoring: {}", e.getMessage());
2238 }
2239 }
2240
2241 try {
2242 attachmentStore.storeAttachment(pointer.getRemoteId(),
2243 outputStream -> retrieveAttachmentPointer(pointer, outputStream));
2244 } catch (IOException e) {
2245 logger.warn("Failed to download attachment ({}), ignoring: {}", pointer.getRemoteId(), e.getMessage());
2246 }
2247 }
2248
2249 private void retrieveGroupV2Avatar(
2250 GroupSecretParams groupSecretParams, String cdnKey, OutputStream outputStream
2251 ) throws IOException {
2252 var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
2253
2254 var tmpFile = IOUtils.createTempFile();
2255 try (InputStream input = messageReceiver.retrieveGroupsV2ProfileAvatar(cdnKey,
2256 tmpFile,
2257 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2258 var encryptedData = IOUtils.readFully(input);
2259
2260 var decryptedData = groupOperations.decryptAvatar(encryptedData);
2261 outputStream.write(decryptedData);
2262 } finally {
2263 try {
2264 Files.delete(tmpFile.toPath());
2265 } catch (IOException e) {
2266 logger.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2267 tmpFile,
2268 e.getMessage());
2269 }
2270 }
2271 }
2272
2273 private void retrieveProfileAvatar(
2274 String avatarPath, ProfileKey profileKey, OutputStream outputStream
2275 ) throws IOException {
2276 var tmpFile = IOUtils.createTempFile();
2277 try (var input = messageReceiver.retrieveProfileAvatar(avatarPath,
2278 tmpFile,
2279 profileKey,
2280 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2281 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2282 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
2283 } finally {
2284 try {
2285 Files.delete(tmpFile.toPath());
2286 } catch (IOException e) {
2287 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2288 tmpFile,
2289 e.getMessage());
2290 }
2291 }
2292 }
2293
2294 private void retrieveAttachment(
2295 final SignalServiceAttachment attachment, final OutputStream outputStream
2296 ) throws IOException {
2297 if (attachment.isPointer()) {
2298 var pointer = attachment.asPointer();
2299 retrieveAttachmentPointer(pointer, outputStream);
2300 } else {
2301 var stream = attachment.asStream();
2302 IOUtils.copyStream(stream.getInputStream(), outputStream);
2303 }
2304 }
2305
2306 private void retrieveAttachmentPointer(
2307 SignalServiceAttachmentPointer pointer, OutputStream outputStream
2308 ) throws IOException {
2309 var tmpFile = IOUtils.createTempFile();
2310 try (var input = retrieveAttachmentAsStream(pointer, tmpFile)) {
2311 IOUtils.copyStream(input, outputStream);
2312 } catch (MissingConfigurationException | InvalidMessageException e) {
2313 throw new IOException(e);
2314 } finally {
2315 try {
2316 Files.delete(tmpFile.toPath());
2317 } catch (IOException e) {
2318 logger.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2319 tmpFile,
2320 e.getMessage());
2321 }
2322 }
2323 }
2324
2325 private InputStream retrieveAttachmentAsStream(
2326 SignalServiceAttachmentPointer pointer, File tmpFile
2327 ) throws IOException, InvalidMessageException, MissingConfigurationException {
2328 return messageReceiver.retrieveAttachment(pointer, tmpFile, ServiceConfig.MAX_ATTACHMENT_SIZE);
2329 }
2330
2331 void sendGroups() throws IOException, UntrustedIdentityException {
2332 var groupsFile = IOUtils.createTempFile();
2333
2334 try {
2335 try (OutputStream fos = new FileOutputStream(groupsFile)) {
2336 var out = new DeviceGroupsOutputStream(fos);
2337 for (var record : getGroups()) {
2338 if (record instanceof GroupInfoV1) {
2339 var groupInfo = (GroupInfoV1) record;
2340 out.write(new DeviceGroup(groupInfo.getGroupId().serialize(),
2341 Optional.fromNullable(groupInfo.name),
2342 groupInfo.getMembers()
2343 .stream()
2344 .map(this::resolveSignalServiceAddress)
2345 .collect(Collectors.toList()),
2346 createGroupAvatarAttachment(groupInfo.getGroupId()),
2347 groupInfo.isMember(account.getSelfRecipientId()),
2348 Optional.of(groupInfo.messageExpirationTime),
2349 Optional.fromNullable(groupInfo.color),
2350 groupInfo.blocked,
2351 Optional.absent(),
2352 groupInfo.archived));
2353 }
2354 }
2355 }
2356
2357 if (groupsFile.exists() && groupsFile.length() > 0) {
2358 try (var groupsFileStream = new FileInputStream(groupsFile)) {
2359 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2360 .withStream(groupsFileStream)
2361 .withContentType("application/octet-stream")
2362 .withLength(groupsFile.length())
2363 .build();
2364
2365 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
2366 }
2367 }
2368 } finally {
2369 try {
2370 Files.delete(groupsFile.toPath());
2371 } catch (IOException e) {
2372 logger.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile, e.getMessage());
2373 }
2374 }
2375 }
2376
2377 public void sendContacts() throws IOException, UntrustedIdentityException {
2378 var contactsFile = IOUtils.createTempFile();
2379
2380 try {
2381 try (OutputStream fos = new FileOutputStream(contactsFile)) {
2382 var out = new DeviceContactsOutputStream(fos);
2383 for (var contactPair : account.getContactStore().getContacts()) {
2384 final var recipientId = contactPair.first();
2385 final var contact = contactPair.second();
2386 final var address = resolveSignalServiceAddress(recipientId);
2387
2388 var currentIdentity = account.getIdentityKeyStore().getIdentity(recipientId);
2389 VerifiedMessage verifiedMessage = null;
2390 if (currentIdentity != null) {
2391 verifiedMessage = new VerifiedMessage(address,
2392 currentIdentity.getIdentityKey(),
2393 currentIdentity.getTrustLevel().toVerifiedState(),
2394 currentIdentity.getDateAdded().getTime());
2395 }
2396
2397 var profileKey = account.getProfileStore().getProfileKey(recipientId);
2398 out.write(new DeviceContact(address,
2399 Optional.fromNullable(contact.getName()),
2400 createContactAvatarAttachment(address),
2401 Optional.fromNullable(contact.getColor()),
2402 Optional.fromNullable(verifiedMessage),
2403 Optional.fromNullable(profileKey),
2404 contact.isBlocked(),
2405 Optional.of(contact.getMessageExpirationTime()),
2406 Optional.absent(),
2407 contact.isArchived()));
2408 }
2409
2410 if (account.getProfileKey() != null) {
2411 // Send our own profile key as well
2412 out.write(new DeviceContact(account.getSelfAddress(),
2413 Optional.absent(),
2414 Optional.absent(),
2415 Optional.absent(),
2416 Optional.absent(),
2417 Optional.of(account.getProfileKey()),
2418 false,
2419 Optional.absent(),
2420 Optional.absent(),
2421 false));
2422 }
2423 }
2424
2425 if (contactsFile.exists() && contactsFile.length() > 0) {
2426 try (var contactsFileStream = new FileInputStream(contactsFile)) {
2427 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2428 .withStream(contactsFileStream)
2429 .withContentType("application/octet-stream")
2430 .withLength(contactsFile.length())
2431 .build();
2432
2433 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
2434 }
2435 }
2436 } finally {
2437 try {
2438 Files.delete(contactsFile.toPath());
2439 } catch (IOException e) {
2440 logger.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile, e.getMessage());
2441 }
2442 }
2443 }
2444
2445 void sendBlockedList() throws IOException, UntrustedIdentityException {
2446 var addresses = new ArrayList<SignalServiceAddress>();
2447 for (var record : account.getContactStore().getContacts()) {
2448 if (record.second().isBlocked()) {
2449 addresses.add(resolveSignalServiceAddress(record.first()));
2450 }
2451 }
2452 var groupIds = new ArrayList<byte[]>();
2453 for (var record : getGroups()) {
2454 if (record.isBlocked()) {
2455 groupIds.add(record.getGroupId().serialize());
2456 }
2457 }
2458 sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
2459 }
2460
2461 private void sendVerifiedMessage(
2462 SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel
2463 ) throws IOException, UntrustedIdentityException {
2464 var verifiedMessage = new VerifiedMessage(destination,
2465 identityKey,
2466 trustLevel.toVerifiedState(),
2467 System.currentTimeMillis());
2468 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
2469 }
2470
2471 public List<Pair<RecipientId, Contact>> getContacts() {
2472 return account.getContactStore().getContacts();
2473 }
2474
2475 public String getContactOrProfileName(String number) throws InvalidNumberException {
2476 final var recipientId = canonicalizeAndResolveRecipient(number);
2477 final var recipient = account.getRecipientStore().getRecipient(recipientId);
2478 if (recipient == null) {
2479 return null;
2480 }
2481
2482 if (recipient.getContact() != null && !Util.isEmpty(recipient.getContact().getName())) {
2483 return recipient.getContact().getName();
2484 }
2485
2486 if (recipient.getProfile() != null && recipient.getProfile() != null) {
2487 return recipient.getProfile().getDisplayName();
2488 }
2489
2490 return null;
2491 }
2492
2493 public GroupInfo getGroup(GroupId groupId) {
2494 final var group = account.getGroupStore().getGroup(groupId);
2495 if (group instanceof GroupInfoV2 && ((GroupInfoV2) group).getGroup() == null) {
2496 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(((GroupInfoV2) group).getMasterKey());
2497 ((GroupInfoV2) group).setGroup(groupHelper.getDecryptedGroup(groupSecretParams), this::resolveRecipient);
2498 account.getGroupStore().updateGroup(group);
2499 }
2500 return group;
2501 }
2502
2503 public List<IdentityInfo> getIdentities() {
2504 return account.getIdentityKeyStore().getIdentities();
2505 }
2506
2507 public List<IdentityInfo> getIdentities(String number) throws InvalidNumberException {
2508 final var identity = account.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number));
2509 return identity == null ? List.of() : List.of(identity);
2510 }
2511
2512 /**
2513 * Trust this the identity with this fingerprint
2514 *
2515 * @param name username of the identity
2516 * @param fingerprint Fingerprint
2517 */
2518 public boolean trustIdentityVerified(String name, byte[] fingerprint) throws InvalidNumberException {
2519 var recipientId = canonicalizeAndResolveRecipient(name);
2520 return trustIdentity(recipientId,
2521 identityKey -> Arrays.equals(identityKey.serialize(), fingerprint),
2522 TrustLevel.TRUSTED_VERIFIED);
2523 }
2524
2525 /**
2526 * Trust this the identity with this safety number
2527 *
2528 * @param name username of the identity
2529 * @param safetyNumber Safety number
2530 */
2531 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) throws InvalidNumberException {
2532 var recipientId = canonicalizeAndResolveRecipient(name);
2533 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
2534 return trustIdentity(recipientId,
2535 identityKey -> safetyNumber.equals(computeSafetyNumber(address, identityKey)),
2536 TrustLevel.TRUSTED_VERIFIED);
2537 }
2538
2539 /**
2540 * Trust all keys of this identity without verification
2541 *
2542 * @param name username of the identity
2543 */
2544 public boolean trustIdentityAllKeys(String name) throws InvalidNumberException {
2545 var recipientId = canonicalizeAndResolveRecipient(name);
2546 return trustIdentity(recipientId, identityKey -> true, TrustLevel.TRUSTED_UNVERIFIED);
2547 }
2548
2549 private boolean trustIdentity(
2550 RecipientId recipientId, Function<IdentityKey, Boolean> verifier, TrustLevel trustLevel
2551 ) {
2552 var identity = account.getIdentityKeyStore().getIdentity(recipientId);
2553 if (identity == null) {
2554 return false;
2555 }
2556
2557 if (!verifier.apply(identity.getIdentityKey())) {
2558 return false;
2559 }
2560
2561 account.getIdentityKeyStore().setIdentityTrustLevel(recipientId, identity.getIdentityKey(), trustLevel);
2562 try {
2563 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
2564 sendVerifiedMessage(address, identity.getIdentityKey(), trustLevel);
2565 } catch (IOException | UntrustedIdentityException e) {
2566 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2567 }
2568
2569 return true;
2570 }
2571
2572 public String computeSafetyNumber(
2573 SignalServiceAddress theirAddress, IdentityKey theirIdentityKey
2574 ) {
2575 return Utils.computeSafetyNumber(ServiceConfig.capabilities.isUuid(),
2576 account.getSelfAddress(),
2577 getIdentityKeyPair().getPublicKey(),
2578 theirAddress,
2579 theirIdentityKey);
2580 }
2581
2582 @Deprecated
2583 public SignalServiceAddress resolveSignalServiceAddress(String identifier) {
2584 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2585
2586 return resolveSignalServiceAddress(address);
2587 }
2588
2589 @Deprecated
2590 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
2591 if (address.matches(account.getSelfAddress())) {
2592 return account.getSelfAddress();
2593 }
2594
2595 return account.getRecipientStore().resolveServiceAddress(address);
2596 }
2597
2598 public SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
2599 return account.getRecipientStore().resolveServiceAddress(recipientId);
2600 }
2601
2602 public RecipientId canonicalizeAndResolveRecipient(String identifier) throws InvalidNumberException {
2603 var canonicalizedNumber = UuidUtil.isUuid(identifier)
2604 ? identifier
2605 : PhoneNumberFormatter.formatNumber(identifier, account.getUsername());
2606
2607 return resolveRecipient(canonicalizedNumber);
2608 }
2609
2610 private RecipientId resolveRecipient(final String identifier) {
2611 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2612
2613 return resolveRecipient(address);
2614 }
2615
2616 public RecipientId resolveRecipient(SignalServiceAddress address) {
2617 return account.getRecipientStore().resolveRecipient(address);
2618 }
2619
2620 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
2621 return account.getRecipientStore().resolveRecipientTrusted(address);
2622 }
2623
2624 @Override
2625 public void close() throws IOException {
2626 close(true);
2627 }
2628
2629 void close(boolean closeAccount) throws IOException {
2630 executor.shutdown();
2631
2632 if (messagePipe != null) {
2633 messagePipe.shutdown();
2634 messagePipe = null;
2635 }
2636
2637 if (unidentifiedMessagePipe != null) {
2638 unidentifiedMessagePipe.shutdown();
2639 unidentifiedMessagePipe = null;
2640 }
2641
2642 if (closeAccount && account != null) {
2643 account.close();
2644 }
2645 account = null;
2646 }
2647
2648 public interface ReceiveMessageHandler {
2649
2650 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
2651 }
2652 }