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