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