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