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