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