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