]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/Manager.java
Split createGroup out of updateGroup method
[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>> createGroup(
786 String name, List<String> members, File avatarFile
787 ) throws IOException, AttachmentInvalidException, InvalidNumberException {
788 return createGroup(name, members == null ? null : getSignalServiceAddresses(members), avatarFile);
789 }
790
791 private Pair<GroupId, List<SendMessageResult>> createGroup(
792 String name, Set<RecipientId> members, File avatarFile
793 ) throws IOException, AttachmentInvalidException {
794 final var selfRecipientId = account.getSelfRecipientId();
795 if (members != null && members.contains(selfRecipientId)) {
796 members = new HashSet<>(members);
797 members.remove(selfRecipientId);
798 }
799
800 var gv2Pair = groupHelper.createGroupV2(name == null ? "" : name,
801 members == null ? Set.of() : members,
802 avatarFile);
803
804 SignalServiceDataMessage.Builder messageBuilder;
805 if (gv2Pair == null) {
806 // Failed to create v2 group, creating v1 group instead
807 var gv1 = new GroupInfoV1(GroupIdV1.createRandom());
808 gv1.addMembers(List.of(selfRecipientId));
809 final var result = updateGroupV1(gv1, name, members, avatarFile);
810 return new Pair<>(gv1.getGroupId(), result.second());
811 }
812
813 final var gv2 = gv2Pair.first();
814 final var decryptedGroup = gv2Pair.second();
815
816 gv2.setGroup(decryptedGroup, this::resolveRecipient);
817 if (avatarFile != null) {
818 avatarStore.storeGroupAvatar(gv2.getGroupId(),
819 outputStream -> IOUtils.copyFileToStream(avatarFile, outputStream));
820 }
821 messageBuilder = getGroupUpdateMessageBuilder(gv2, null);
822 account.getGroupStore().updateGroup(gv2);
823
824 final var result = sendMessage(messageBuilder, gv2.getMembersIncludingPendingWithout(selfRecipientId));
825 return new Pair<>(gv2.getGroupId(), result.second());
826 }
827
828 public Pair<Long, List<SendMessageResult>> updateGroup(
829 GroupId groupId, String name, String description, List<String> members, File avatarFile
830 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, InvalidNumberException, NotAGroupMemberException {
831 return updateGroup(groupId,
832 name,
833 description,
834 members == null ? null : getSignalServiceAddresses(members),
835 avatarFile);
836 }
837
838 private Pair<Long, List<SendMessageResult>> updateGroup(
839 GroupId groupId, String name, String description, Set<RecipientId> members, File avatarFile
840 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException {
841 var group = getGroupForUpdating(groupId);
842
843 if (group instanceof GroupInfoV2) {
844 return updateGroupV2((GroupInfoV2) group, name, description, members, avatarFile);
845 }
846
847 return updateGroupV1((GroupInfoV1) group, name, members, avatarFile);
848 }
849
850 private Pair<Long, List<SendMessageResult>> updateGroupV1(
851 final GroupInfoV1 gv1, final String name, final Set<RecipientId> members, final File avatarFile
852 ) throws IOException, AttachmentInvalidException {
853 updateGroupV1Details(gv1, name, members, avatarFile);
854 var messageBuilder = getGroupUpdateMessageBuilder(gv1);
855
856 account.getGroupStore().updateGroup(gv1);
857
858 return sendMessage(messageBuilder, gv1.getMembersIncludingPendingWithout(account.getSelfRecipientId()));
859 }
860
861 private void updateGroupV1Details(
862 final GroupInfoV1 g, final String name, final Collection<RecipientId> members, final File avatarFile
863 ) throws IOException {
864 if (name != null) {
865 g.name = name;
866 }
867
868 if (members != null) {
869 final var newMemberAddresses = members.stream()
870 .filter(member -> !g.isMember(member))
871 .map(this::resolveSignalServiceAddress)
872 .collect(Collectors.toList());
873 final var newE164Members = new HashSet<String>();
874 for (var member : newMemberAddresses) {
875 if (!member.getNumber().isPresent()) {
876 continue;
877 }
878 newE164Members.add(member.getNumber().get());
879 }
880
881 final var registeredUsers = getRegisteredUsers(newE164Members);
882 if (registeredUsers.size() != newE164Members.size()) {
883 // Some of the new members are not registered on Signal
884 newE164Members.removeAll(registeredUsers.keySet());
885 throw new IOException("Failed to add members "
886 + String.join(", ", newE164Members)
887 + " to group: Not registered on Signal");
888 }
889
890 g.addMembers(members);
891 }
892
893 if (avatarFile != null) {
894 avatarStore.storeGroupAvatar(g.getGroupId(),
895 outputStream -> IOUtils.copyFileToStream(avatarFile, outputStream));
896 }
897 }
898
899 private Pair<Long, List<SendMessageResult>> updateGroupV2(
900 final GroupInfoV2 group,
901 final String name,
902 final String description,
903 final Set<RecipientId> members,
904 final File avatarFile
905 ) throws IOException {
906 Pair<Long, List<SendMessageResult>> result = null;
907 if (group.isPendingMember(account.getSelfRecipientId())) {
908 var groupGroupChangePair = groupHelper.acceptInvite(group);
909 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
910 }
911
912 if (members != null) {
913 final var newMembers = new HashSet<>(members);
914 newMembers.removeAll(group.getMembers());
915 if (newMembers.size() > 0) {
916 var groupGroupChangePair = groupHelper.updateGroupV2(group, newMembers);
917 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
918 }
919 }
920 if (result == null || name != null || description != null || avatarFile != null) {
921 var groupGroupChangePair = groupHelper.updateGroupV2(group, name, description, avatarFile);
922 if (avatarFile != null) {
923 avatarStore.storeGroupAvatar(group.getGroupId(),
924 outputStream -> IOUtils.copyFileToStream(avatarFile, outputStream));
925 }
926 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
927 }
928
929 return result;
930 }
931
932 public Pair<GroupId, List<SendMessageResult>> joinGroup(
933 GroupInviteLinkUrl inviteLinkUrl
934 ) throws IOException, GroupLinkNotActiveException {
935 final var groupJoinInfo = groupHelper.getDecryptedGroupJoinInfo(inviteLinkUrl.getGroupMasterKey(),
936 inviteLinkUrl.getPassword());
937 final var groupChange = groupHelper.joinGroup(inviteLinkUrl.getGroupMasterKey(),
938 inviteLinkUrl.getPassword(),
939 groupJoinInfo);
940 final var group = getOrMigrateGroup(inviteLinkUrl.getGroupMasterKey(),
941 groupJoinInfo.getRevision() + 1,
942 groupChange.toByteArray());
943
944 if (group.getGroup() == null) {
945 // Only requested member, can't send update to group members
946 return new Pair<>(group.getGroupId(), List.of());
947 }
948
949 final var result = sendUpdateGroupV2Message(group, group.getGroup(), groupChange);
950
951 return new Pair<>(group.getGroupId(), result.second());
952 }
953
954 private Pair<Long, List<SendMessageResult>> sendUpdateGroupV2Message(
955 GroupInfoV2 group, DecryptedGroup newDecryptedGroup, GroupChange groupChange
956 ) throws IOException {
957 group.setGroup(newDecryptedGroup, this::resolveRecipient);
958 final var messageBuilder = getGroupUpdateMessageBuilder(group, groupChange.toByteArray());
959 account.getGroupStore().updateGroup(group);
960 return sendMessage(messageBuilder, group.getMembersIncludingPendingWithout(account.getSelfRecipientId()));
961 }
962
963 private static int currentTimeDays() {
964 return (int) TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis());
965 }
966
967 private GroupsV2AuthorizationString getGroupAuthForToday(
968 final GroupSecretParams groupSecretParams
969 ) throws IOException {
970 final var today = currentTimeDays();
971 // Returns credentials for the next 7 days
972 final var credentials = groupsV2Api.getCredentials(today);
973 // TODO cache credentials until they expire
974 var authCredentialResponse = credentials.get(today);
975 try {
976 return groupsV2Api.getGroupsV2AuthorizationString(account.getUuid(),
977 today,
978 groupSecretParams,
979 authCredentialResponse);
980 } catch (VerificationFailedException e) {
981 throw new IOException(e);
982 }
983 }
984
985 Pair<Long, List<SendMessageResult>> sendGroupInfoMessage(
986 GroupIdV1 groupId, SignalServiceAddress recipient
987 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, AttachmentInvalidException {
988 GroupInfoV1 g;
989 var group = getGroupForSending(groupId);
990 if (!(group instanceof GroupInfoV1)) {
991 throw new RuntimeException("Received an invalid group request for a v2 group!");
992 }
993 g = (GroupInfoV1) group;
994
995 final var recipientId = resolveRecipient(recipient);
996 if (!g.isMember(recipientId)) {
997 throw new NotAGroupMemberException(groupId, g.name);
998 }
999
1000 var messageBuilder = getGroupUpdateMessageBuilder(g);
1001
1002 // Send group message only to the recipient who requested it
1003 return sendMessage(messageBuilder, Set.of(recipientId));
1004 }
1005
1006 private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfoV1 g) throws AttachmentInvalidException {
1007 var group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.UPDATE)
1008 .withId(g.getGroupId().serialize())
1009 .withName(g.name)
1010 .withMembers(g.getMembers()
1011 .stream()
1012 .map(this::resolveSignalServiceAddress)
1013 .collect(Collectors.toList()));
1014
1015 try {
1016 final var attachment = createGroupAvatarAttachment(g.getGroupId());
1017 if (attachment.isPresent()) {
1018 group.withAvatar(attachment.get());
1019 }
1020 } catch (IOException e) {
1021 throw new AttachmentInvalidException(g.getGroupId().toBase64(), e);
1022 }
1023
1024 return SignalServiceDataMessage.newBuilder()
1025 .asGroupMessage(group.build())
1026 .withExpiration(g.getMessageExpirationTime());
1027 }
1028
1029 private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfoV2 g, byte[] signedGroupChange) {
1030 var group = SignalServiceGroupV2.newBuilder(g.getMasterKey())
1031 .withRevision(g.getGroup().getRevision())
1032 .withSignedGroupChange(signedGroupChange);
1033 return SignalServiceDataMessage.newBuilder()
1034 .asGroupMessage(group.build())
1035 .withExpiration(g.getMessageExpirationTime());
1036 }
1037
1038 Pair<Long, List<SendMessageResult>> sendGroupInfoRequest(
1039 GroupIdV1 groupId, SignalServiceAddress recipient
1040 ) throws IOException {
1041 var group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.REQUEST_INFO).withId(groupId.serialize());
1042
1043 var messageBuilder = SignalServiceDataMessage.newBuilder().asGroupMessage(group.build());
1044
1045 // Send group info request message to the recipient who sent us a message with this groupId
1046 return sendMessage(messageBuilder, Set.of(resolveRecipient(recipient)));
1047 }
1048
1049 void sendReceipt(
1050 SignalServiceAddress remoteAddress, long messageId
1051 ) throws IOException, UntrustedIdentityException {
1052 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.DELIVERY,
1053 List.of(messageId),
1054 System.currentTimeMillis());
1055
1056 createMessageSender().sendReceipt(remoteAddress,
1057 unidentifiedAccessHelper.getAccessFor(resolveRecipient(remoteAddress)),
1058 receiptMessage);
1059 }
1060
1061 public Pair<Long, List<SendMessageResult>> sendMessage(
1062 String messageText, List<String> attachments, List<String> recipients
1063 ) throws IOException, AttachmentInvalidException, InvalidNumberException {
1064 final var messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
1065 if (attachments != null) {
1066 var attachmentStreams = AttachmentUtils.getSignalServiceAttachments(attachments);
1067
1068 // Upload attachments here, so we only upload once even for multiple recipients
1069 var messageSender = createMessageSender();
1070 var attachmentPointers = new ArrayList<SignalServiceAttachment>(attachmentStreams.size());
1071 for (var attachment : attachmentStreams) {
1072 if (attachment.isStream()) {
1073 attachmentPointers.add(messageSender.uploadAttachment(attachment.asStream()));
1074 } else if (attachment.isPointer()) {
1075 attachmentPointers.add(attachment.asPointer());
1076 }
1077 }
1078
1079 messageBuilder.withAttachments(attachmentPointers);
1080 }
1081 return sendMessage(messageBuilder, getSignalServiceAddresses(recipients));
1082 }
1083
1084 public Pair<Long, SendMessageResult> sendSelfMessage(
1085 String messageText, List<String> attachments
1086 ) throws IOException, AttachmentInvalidException {
1087 final var messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
1088 if (attachments != null) {
1089 messageBuilder.withAttachments(AttachmentUtils.getSignalServiceAttachments(attachments));
1090 }
1091 return sendSelfMessage(messageBuilder);
1092 }
1093
1094 public Pair<Long, List<SendMessageResult>> sendRemoteDeleteMessage(
1095 long targetSentTimestamp, List<String> recipients
1096 ) throws IOException, InvalidNumberException {
1097 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
1098 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
1099 return sendMessage(messageBuilder, getSignalServiceAddresses(recipients));
1100 }
1101
1102 public Pair<Long, List<SendMessageResult>> sendGroupRemoteDeleteMessage(
1103 long targetSentTimestamp, GroupId groupId
1104 ) throws IOException, NotAGroupMemberException, GroupNotFoundException {
1105 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
1106 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
1107 return sendGroupMessage(messageBuilder, groupId);
1108 }
1109
1110 public Pair<Long, List<SendMessageResult>> sendMessageReaction(
1111 String emoji, boolean remove, String targetAuthor, long targetSentTimestamp, List<String> recipients
1112 ) throws IOException, InvalidNumberException {
1113 var targetAuthorRecipientId = canonicalizeAndResolveRecipient(targetAuthor);
1114 var reaction = new SignalServiceDataMessage.Reaction(emoji,
1115 remove,
1116 resolveSignalServiceAddress(targetAuthorRecipientId),
1117 targetSentTimestamp);
1118 final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
1119 return sendMessage(messageBuilder, getSignalServiceAddresses(recipients));
1120 }
1121
1122 public Pair<Long, List<SendMessageResult>> sendEndSessionMessage(List<String> recipients) throws IOException, InvalidNumberException {
1123 var messageBuilder = SignalServiceDataMessage.newBuilder().asEndSessionMessage();
1124
1125 final var signalServiceAddresses = getSignalServiceAddresses(recipients);
1126 try {
1127 return sendMessage(messageBuilder, signalServiceAddresses);
1128 } catch (Exception e) {
1129 for (var address : signalServiceAddresses) {
1130 handleEndSession(address);
1131 }
1132 throw e;
1133 }
1134 }
1135
1136 void renewSession(RecipientId recipientId) throws IOException {
1137 account.getSessionStore().archiveSessions(recipientId);
1138 if (!recipientId.equals(getSelfRecipientId())) {
1139 sendNullMessage(recipientId);
1140 }
1141 }
1142
1143 public String getContactName(String number) throws InvalidNumberException {
1144 var contact = account.getContactStore().getContact(canonicalizeAndResolveRecipient(number));
1145 return contact == null || contact.getName() == null ? "" : contact.getName();
1146 }
1147
1148 public void setContactName(String number, String name) throws InvalidNumberException, NotMasterDeviceException {
1149 if (!account.isMasterDevice()) {
1150 throw new NotMasterDeviceException();
1151 }
1152 final var recipientId = canonicalizeAndResolveRecipient(number);
1153 var contact = account.getContactStore().getContact(recipientId);
1154 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
1155 account.getContactStore().storeContact(recipientId, builder.withName(name).build());
1156 }
1157
1158 public void setContactBlocked(
1159 String number, boolean blocked
1160 ) throws InvalidNumberException, NotMasterDeviceException {
1161 if (!account.isMasterDevice()) {
1162 throw new NotMasterDeviceException();
1163 }
1164 setContactBlocked(canonicalizeAndResolveRecipient(number), blocked);
1165 }
1166
1167 private void setContactBlocked(RecipientId recipientId, boolean blocked) {
1168 var contact = account.getContactStore().getContact(recipientId);
1169 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
1170 account.getContactStore().storeContact(recipientId, builder.withBlocked(blocked).build());
1171 }
1172
1173 public void setGroupBlocked(final GroupId groupId, final boolean blocked) throws GroupNotFoundException {
1174 var group = getGroup(groupId);
1175 if (group == null) {
1176 throw new GroupNotFoundException(groupId);
1177 }
1178
1179 group.setBlocked(blocked);
1180 account.getGroupStore().updateGroup(group);
1181 }
1182
1183 private void setExpirationTimer(RecipientId recipientId, int messageExpirationTimer) {
1184 var contact = account.getContactStore().getContact(recipientId);
1185 if (contact != null && contact.getMessageExpirationTime() == messageExpirationTimer) {
1186 return;
1187 }
1188 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
1189 account.getContactStore()
1190 .storeContact(recipientId, builder.withMessageExpirationTime(messageExpirationTimer).build());
1191 }
1192
1193 private void sendExpirationTimerUpdate(RecipientId recipientId) throws IOException {
1194 final var messageBuilder = SignalServiceDataMessage.newBuilder().asExpirationUpdate();
1195 sendMessage(messageBuilder, Set.of(recipientId));
1196 }
1197
1198 /**
1199 * Change the expiration timer for a contact
1200 */
1201 public void setExpirationTimer(
1202 String number, int messageExpirationTimer
1203 ) throws IOException, InvalidNumberException {
1204 var recipientId = canonicalizeAndResolveRecipient(number);
1205 setExpirationTimer(recipientId, messageExpirationTimer);
1206 sendExpirationTimerUpdate(recipientId);
1207 }
1208
1209 /**
1210 * Change the expiration timer for a group
1211 */
1212 public void setExpirationTimer(GroupId groupId, int messageExpirationTimer) {
1213 var g = getGroup(groupId);
1214 if (g instanceof GroupInfoV1) {
1215 var groupInfoV1 = (GroupInfoV1) g;
1216 groupInfoV1.messageExpirationTime = messageExpirationTimer;
1217 account.getGroupStore().updateGroup(groupInfoV1);
1218 } else {
1219 throw new RuntimeException("TODO Not implemented!");
1220 }
1221 }
1222
1223 /**
1224 * Upload the sticker pack from path.
1225 *
1226 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1227 * @return if successful, returns the URL to install the sticker pack in the signal app
1228 */
1229 public String uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
1230 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
1231
1232 var messageSender = createMessageSender();
1233
1234 var packKey = KeyUtils.createStickerUploadKey();
1235 var packId = messageSender.uploadStickerManifest(manifest, packKey);
1236
1237 var sticker = new Sticker(StickerPackId.deserialize(Hex.fromStringCondensed(packId)), packKey);
1238 account.getStickerStore().updateSticker(sticker);
1239
1240 try {
1241 return new URI("https",
1242 "signal.art",
1243 "/addstickers/",
1244 "pack_id=" + URLEncoder.encode(packId, StandardCharsets.UTF_8) + "&pack_key=" + URLEncoder.encode(
1245 Hex.toStringCondensed(packKey),
1246 StandardCharsets.UTF_8)).toString();
1247 } catch (URISyntaxException e) {
1248 throw new AssertionError(e);
1249 }
1250 }
1251
1252 public void requestAllSyncData() throws IOException {
1253 requestSyncGroups();
1254 requestSyncContacts();
1255 requestSyncBlocked();
1256 requestSyncConfiguration();
1257 requestSyncKeys();
1258 }
1259
1260 private void requestSyncGroups() throws IOException {
1261 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1262 .setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS)
1263 .build();
1264 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1265 try {
1266 sendSyncMessage(message);
1267 } catch (UntrustedIdentityException e) {
1268 throw new AssertionError(e);
1269 }
1270 }
1271
1272 private void requestSyncContacts() throws IOException {
1273 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1274 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS)
1275 .build();
1276 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1277 try {
1278 sendSyncMessage(message);
1279 } catch (UntrustedIdentityException e) {
1280 throw new AssertionError(e);
1281 }
1282 }
1283
1284 private void requestSyncBlocked() throws IOException {
1285 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1286 .setType(SignalServiceProtos.SyncMessage.Request.Type.BLOCKED)
1287 .build();
1288 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1289 try {
1290 sendSyncMessage(message);
1291 } catch (UntrustedIdentityException e) {
1292 throw new AssertionError(e);
1293 }
1294 }
1295
1296 private void requestSyncConfiguration() throws IOException {
1297 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1298 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONFIGURATION)
1299 .build();
1300 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1301 try {
1302 sendSyncMessage(message);
1303 } catch (UntrustedIdentityException e) {
1304 throw new AssertionError(e);
1305 }
1306 }
1307
1308 private void requestSyncKeys() throws IOException {
1309 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1310 .setType(SignalServiceProtos.SyncMessage.Request.Type.KEYS)
1311 .build();
1312 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1313 try {
1314 sendSyncMessage(message);
1315 } catch (UntrustedIdentityException e) {
1316 throw new AssertionError(e);
1317 }
1318 }
1319
1320 private byte[] getSenderCertificate() {
1321 byte[] certificate;
1322 try {
1323 if (account.isPhoneNumberShared()) {
1324 certificate = accountManager.getSenderCertificate();
1325 } else {
1326 certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1327 }
1328 } catch (IOException e) {
1329 logger.warn("Failed to get sender certificate, ignoring: {}", e.getMessage());
1330 return null;
1331 }
1332 // TODO cache for a day
1333 return certificate;
1334 }
1335
1336 private void sendSyncMessage(SignalServiceSyncMessage message) throws IOException, UntrustedIdentityException {
1337 var messageSender = createMessageSender();
1338 messageSender.sendMessage(message, unidentifiedAccessHelper.getAccessForSync());
1339 }
1340
1341 private Set<RecipientId> getSignalServiceAddresses(Collection<String> numbers) throws InvalidNumberException {
1342 final var signalServiceAddresses = new HashSet<SignalServiceAddress>(numbers.size());
1343 final var addressesMissingUuid = new HashSet<SignalServiceAddress>();
1344
1345 for (var number : numbers) {
1346 final var resolvedAddress = resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number));
1347 if (resolvedAddress.getUuid().isPresent()) {
1348 signalServiceAddresses.add(resolvedAddress);
1349 } else {
1350 addressesMissingUuid.add(resolvedAddress);
1351 }
1352 }
1353
1354 final var numbersMissingUuid = addressesMissingUuid.stream()
1355 .map(a -> a.getNumber().get())
1356 .collect(Collectors.toSet());
1357 Map<String, UUID> registeredUsers;
1358 try {
1359 registeredUsers = getRegisteredUsers(numbersMissingUuid);
1360 } catch (IOException e) {
1361 logger.warn("Failed to resolve uuids from server, ignoring: {}", e.getMessage());
1362 registeredUsers = Map.of();
1363 }
1364
1365 for (var address : addressesMissingUuid) {
1366 final var number = address.getNumber().get();
1367 if (registeredUsers.containsKey(number)) {
1368 final var newAddress = resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1369 registeredUsers.get(number),
1370 number)));
1371 signalServiceAddresses.add(newAddress);
1372 } else {
1373 signalServiceAddresses.add(address);
1374 }
1375 }
1376
1377 return signalServiceAddresses.stream().map(this::resolveRecipient).collect(Collectors.toSet());
1378 }
1379
1380 private RecipientId refreshRegisteredUser(RecipientId recipientId) throws IOException {
1381 final var address = resolveSignalServiceAddress(recipientId);
1382 if (!address.getNumber().isPresent()) {
1383 return recipientId;
1384 }
1385 final var number = address.getNumber().get();
1386 final var uuidMap = getRegisteredUsers(Set.of(number));
1387 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap.getOrDefault(number, null), number));
1388 }
1389
1390 private Map<String, UUID> getRegisteredUsers(final Set<String> numbers) throws IOException {
1391 try {
1392 return accountManager.getRegisteredUsers(ServiceConfig.getIasKeyStore(),
1393 numbers,
1394 serviceEnvironmentConfig.getCdsMrenclave());
1395 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
1396 throw new IOException(e);
1397 }
1398 }
1399
1400 private Pair<Long, List<SendMessageResult>> sendMessage(
1401 SignalServiceDataMessage.Builder messageBuilder, Set<RecipientId> recipientIds
1402 ) throws IOException {
1403 final var timestamp = System.currentTimeMillis();
1404 messageBuilder.withTimestamp(timestamp);
1405 getOrCreateMessagePipe();
1406 getOrCreateUnidentifiedMessagePipe();
1407 SignalServiceDataMessage message = null;
1408 try {
1409 message = messageBuilder.build();
1410 if (message.getGroupContext().isPresent()) {
1411 try {
1412 var messageSender = createMessageSender();
1413 final var isRecipientUpdate = false;
1414 final var recipientIdList = new ArrayList<>(recipientIds);
1415 final var addresses = recipientIdList.stream()
1416 .map(this::resolveSignalServiceAddress)
1417 .collect(Collectors.toList());
1418 var result = messageSender.sendMessage(addresses,
1419 unidentifiedAccessHelper.getAccessFor(recipientIdList),
1420 isRecipientUpdate,
1421 message);
1422
1423 for (var r : result) {
1424 if (r.getIdentityFailure() != null) {
1425 final var recipientId = resolveRecipient(r.getAddress());
1426 final var newIdentity = account.getIdentityKeyStore()
1427 .saveIdentity(recipientId, r.getIdentityFailure().getIdentityKey(), new Date());
1428 if (newIdentity) {
1429 account.getSessionStore().archiveSessions(recipientId);
1430 }
1431 }
1432 }
1433
1434 return new Pair<>(timestamp, result);
1435 } catch (UntrustedIdentityException e) {
1436 return new Pair<>(timestamp, List.of());
1437 }
1438 } else {
1439 // Send to all individually, so sync messages are sent correctly
1440 messageBuilder.withProfileKey(account.getProfileKey().serialize());
1441 var results = new ArrayList<SendMessageResult>(recipientIds.size());
1442 for (var recipientId : recipientIds) {
1443 final var contact = account.getContactStore().getContact(recipientId);
1444 final var expirationTime = contact != null ? contact.getMessageExpirationTime() : 0;
1445 messageBuilder.withExpiration(expirationTime);
1446 message = messageBuilder.build();
1447 results.add(sendMessage(recipientId, message));
1448 }
1449 return new Pair<>(timestamp, results);
1450 }
1451 } finally {
1452 if (message != null && message.isEndSession()) {
1453 for (var recipient : recipientIds) {
1454 handleEndSession(recipient);
1455 }
1456 }
1457 }
1458 }
1459
1460 private Pair<Long, SendMessageResult> sendSelfMessage(
1461 SignalServiceDataMessage.Builder messageBuilder
1462 ) throws IOException {
1463 final var timestamp = System.currentTimeMillis();
1464 messageBuilder.withTimestamp(timestamp);
1465 getOrCreateMessagePipe();
1466 getOrCreateUnidentifiedMessagePipe();
1467 final var recipientId = account.getSelfRecipientId();
1468
1469 final var contact = account.getContactStore().getContact(recipientId);
1470 final var expirationTime = contact != null ? contact.getMessageExpirationTime() : 0;
1471 messageBuilder.withExpiration(expirationTime);
1472
1473 var message = messageBuilder.build();
1474 final var result = sendSelfMessage(message);
1475 return new Pair<>(timestamp, result);
1476 }
1477
1478 private SendMessageResult sendSelfMessage(SignalServiceDataMessage message) throws IOException {
1479 var messageSender = createMessageSender();
1480
1481 var recipientId = account.getSelfRecipientId();
1482
1483 final var unidentifiedAccess = unidentifiedAccessHelper.getAccessFor(recipientId);
1484 var recipient = resolveSignalServiceAddress(recipientId);
1485 var transcript = new SentTranscriptMessage(Optional.of(recipient),
1486 message.getTimestamp(),
1487 message,
1488 message.getExpiresInSeconds(),
1489 Map.of(recipient, unidentifiedAccess.isPresent()),
1490 false);
1491 var syncMessage = SignalServiceSyncMessage.forSentTranscript(transcript);
1492
1493 try {
1494 var startTime = System.currentTimeMillis();
1495 messageSender.sendMessage(syncMessage, unidentifiedAccess);
1496 return SendMessageResult.success(recipient,
1497 unidentifiedAccess.isPresent(),
1498 false,
1499 System.currentTimeMillis() - startTime);
1500 } catch (UntrustedIdentityException e) {
1501 return SendMessageResult.identityFailure(recipient, e.getIdentityKey());
1502 }
1503 }
1504
1505 private SendMessageResult sendMessage(
1506 RecipientId recipientId, SignalServiceDataMessage message
1507 ) throws IOException {
1508 var messageSender = createMessageSender();
1509
1510 final var address = resolveSignalServiceAddress(recipientId);
1511 try {
1512 try {
1513 return messageSender.sendMessage(address, unidentifiedAccessHelper.getAccessFor(recipientId), message);
1514 } catch (UnregisteredUserException e) {
1515 final var newRecipientId = refreshRegisteredUser(recipientId);
1516 return messageSender.sendMessage(resolveSignalServiceAddress(newRecipientId),
1517 unidentifiedAccessHelper.getAccessFor(newRecipientId),
1518 message);
1519 }
1520 } catch (UntrustedIdentityException e) {
1521 return SendMessageResult.identityFailure(address, e.getIdentityKey());
1522 }
1523 }
1524
1525 private SendMessageResult sendNullMessage(RecipientId recipientId) throws IOException {
1526 var messageSender = createMessageSender();
1527
1528 final var address = resolveSignalServiceAddress(recipientId);
1529 try {
1530 try {
1531 return messageSender.sendNullMessage(address, unidentifiedAccessHelper.getAccessFor(recipientId));
1532 } catch (UnregisteredUserException e) {
1533 final var newRecipientId = refreshRegisteredUser(recipientId);
1534 final var newAddress = resolveSignalServiceAddress(newRecipientId);
1535 return messageSender.sendNullMessage(newAddress, unidentifiedAccessHelper.getAccessFor(newRecipientId));
1536 }
1537 } catch (UntrustedIdentityException e) {
1538 return SendMessageResult.identityFailure(address, e.getIdentityKey());
1539 }
1540 }
1541
1542 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, SelfSendException, UnsupportedDataMessageException, ProtocolUntrustedIdentityException {
1543 var cipher = new SignalServiceCipher(account.getSelfAddress(),
1544 account.getSignalProtocolStore(),
1545 sessionLock,
1546 certificateValidator);
1547 return cipher.decrypt(envelope);
1548 }
1549
1550 private void handleEndSession(RecipientId recipientId) {
1551 account.getSessionStore().deleteAllSessions(recipientId);
1552 }
1553
1554 private List<HandleAction> handleSignalServiceDataMessage(
1555 SignalServiceDataMessage message,
1556 boolean isSync,
1557 SignalServiceAddress source,
1558 SignalServiceAddress destination,
1559 boolean ignoreAttachments
1560 ) {
1561 var actions = new ArrayList<HandleAction>();
1562 if (message.getGroupContext().isPresent()) {
1563 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1564 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1565 var groupId = GroupId.v1(groupInfo.getGroupId());
1566 var group = getGroup(groupId);
1567 if (group == null || group instanceof GroupInfoV1) {
1568 var groupV1 = (GroupInfoV1) group;
1569 switch (groupInfo.getType()) {
1570 case UPDATE: {
1571 if (groupV1 == null) {
1572 groupV1 = new GroupInfoV1(groupId);
1573 }
1574
1575 if (groupInfo.getAvatar().isPresent()) {
1576 var avatar = groupInfo.getAvatar().get();
1577 downloadGroupAvatar(avatar, groupV1.getGroupId());
1578 }
1579
1580 if (groupInfo.getName().isPresent()) {
1581 groupV1.name = groupInfo.getName().get();
1582 }
1583
1584 if (groupInfo.getMembers().isPresent()) {
1585 groupV1.addMembers(groupInfo.getMembers()
1586 .get()
1587 .stream()
1588 .map(this::resolveRecipient)
1589 .collect(Collectors.toSet()));
1590 }
1591
1592 account.getGroupStore().updateGroup(groupV1);
1593 break;
1594 }
1595 case DELIVER:
1596 if (groupV1 == null && !isSync) {
1597 actions.add(new SendGroupInfoRequestAction(source, groupId));
1598 }
1599 break;
1600 case QUIT: {
1601 if (groupV1 != null) {
1602 groupV1.removeMember(resolveRecipient(source));
1603 account.getGroupStore().updateGroup(groupV1);
1604 }
1605 break;
1606 }
1607 case REQUEST_INFO:
1608 if (groupV1 != null && !isSync) {
1609 actions.add(new SendGroupInfoAction(source, groupV1.getGroupId()));
1610 }
1611 break;
1612 }
1613 } else {
1614 // Received a group v1 message for a v2 group
1615 }
1616 }
1617 if (message.getGroupContext().get().getGroupV2().isPresent()) {
1618 final var groupContext = message.getGroupContext().get().getGroupV2().get();
1619 final var groupMasterKey = groupContext.getMasterKey();
1620
1621 getOrMigrateGroup(groupMasterKey,
1622 groupContext.getRevision(),
1623 groupContext.hasSignedGroupChange() ? groupContext.getSignedGroupChange() : null);
1624 }
1625 }
1626
1627 final var conversationPartnerAddress = isSync ? destination : source;
1628 if (conversationPartnerAddress != null && message.isEndSession()) {
1629 handleEndSession(resolveRecipient(conversationPartnerAddress));
1630 }
1631 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
1632 if (message.getGroupContext().isPresent()) {
1633 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1634 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1635 var group = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(groupInfo.getGroupId()));
1636 if (group != null) {
1637 if (group.messageExpirationTime != message.getExpiresInSeconds()) {
1638 group.messageExpirationTime = message.getExpiresInSeconds();
1639 account.getGroupStore().updateGroup(group);
1640 }
1641 }
1642 } else if (message.getGroupContext().get().getGroupV2().isPresent()) {
1643 // disappearing message timer already stored in the DecryptedGroup
1644 }
1645 } else if (conversationPartnerAddress != null) {
1646 setExpirationTimer(resolveRecipient(conversationPartnerAddress), message.getExpiresInSeconds());
1647 }
1648 }
1649 if (!ignoreAttachments) {
1650 if (message.getAttachments().isPresent()) {
1651 for (var attachment : message.getAttachments().get()) {
1652 downloadAttachment(attachment);
1653 }
1654 }
1655 if (message.getSharedContacts().isPresent()) {
1656 for (var contact : message.getSharedContacts().get()) {
1657 if (contact.getAvatar().isPresent()) {
1658 downloadAttachment(contact.getAvatar().get().getAttachment());
1659 }
1660 }
1661 }
1662 }
1663 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
1664 final ProfileKey profileKey;
1665 try {
1666 profileKey = new ProfileKey(message.getProfileKey().get());
1667 } catch (InvalidInputException e) {
1668 throw new AssertionError(e);
1669 }
1670 if (source.matches(account.getSelfAddress())) {
1671 this.account.setProfileKey(profileKey);
1672 }
1673 this.account.getProfileStore().storeProfileKey(resolveRecipient(source), profileKey);
1674 }
1675 if (message.getPreviews().isPresent()) {
1676 final var previews = message.getPreviews().get();
1677 for (var preview : previews) {
1678 if (preview.getImage().isPresent()) {
1679 downloadAttachment(preview.getImage().get());
1680 }
1681 }
1682 }
1683 if (message.getQuote().isPresent()) {
1684 final var quote = message.getQuote().get();
1685
1686 for (var quotedAttachment : quote.getAttachments()) {
1687 final var thumbnail = quotedAttachment.getThumbnail();
1688 if (thumbnail != null) {
1689 downloadAttachment(thumbnail);
1690 }
1691 }
1692 }
1693 if (message.getSticker().isPresent()) {
1694 final var messageSticker = message.getSticker().get();
1695 final var stickerPackId = StickerPackId.deserialize(messageSticker.getPackId());
1696 var sticker = account.getStickerStore().getSticker(stickerPackId);
1697 if (sticker == null) {
1698 sticker = new Sticker(stickerPackId, messageSticker.getPackKey());
1699 account.getStickerStore().updateSticker(sticker);
1700 }
1701 }
1702 return actions;
1703 }
1704
1705 private GroupInfoV2 getOrMigrateGroup(
1706 final GroupMasterKey groupMasterKey, final int revision, final byte[] signedGroupChange
1707 ) {
1708 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
1709
1710 var groupId = GroupUtils.getGroupIdV2(groupSecretParams);
1711 var groupInfo = getGroup(groupId);
1712 final GroupInfoV2 groupInfoV2;
1713 if (groupInfo instanceof GroupInfoV1) {
1714 // Received a v2 group message for a v1 group, we need to locally migrate the group
1715 account.getGroupStore().deleteGroupV1(((GroupInfoV1) groupInfo).getGroupId());
1716 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1717 logger.info("Locally migrated group {} to group v2, id: {}",
1718 groupInfo.getGroupId().toBase64(),
1719 groupInfoV2.getGroupId().toBase64());
1720 } else if (groupInfo instanceof GroupInfoV2) {
1721 groupInfoV2 = (GroupInfoV2) groupInfo;
1722 } else {
1723 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1724 }
1725
1726 if (groupInfoV2.getGroup() == null || groupInfoV2.getGroup().getRevision() < revision) {
1727 DecryptedGroup group = null;
1728 if (signedGroupChange != null
1729 && groupInfoV2.getGroup() != null
1730 && groupInfoV2.getGroup().getRevision() + 1 == revision) {
1731 group = groupHelper.getUpdatedDecryptedGroup(groupInfoV2.getGroup(), signedGroupChange, groupMasterKey);
1732 }
1733 if (group == null) {
1734 group = groupHelper.getDecryptedGroup(groupSecretParams);
1735 }
1736 if (group != null) {
1737 storeProfileKeysFromMembers(group);
1738 final var avatar = group.getAvatar();
1739 if (avatar != null && !avatar.isEmpty()) {
1740 downloadGroupAvatar(groupId, groupSecretParams, avatar);
1741 }
1742 }
1743 groupInfoV2.setGroup(group, this::resolveRecipient);
1744 account.getGroupStore().updateGroup(groupInfoV2);
1745 }
1746
1747 return groupInfoV2;
1748 }
1749
1750 private void storeProfileKeysFromMembers(final DecryptedGroup group) {
1751 for (var member : group.getMembersList()) {
1752 final var uuid = UuidUtil.parseOrThrow(member.getUuid().toByteArray());
1753 final var recipientId = account.getRecipientStore().resolveRecipient(uuid);
1754 try {
1755 account.getProfileStore()
1756 .storeProfileKey(recipientId, new ProfileKey(member.getProfileKey().toByteArray()));
1757 } catch (InvalidInputException ignored) {
1758 }
1759 }
1760 }
1761
1762 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1763 Set<HandleAction> queuedActions = new HashSet<>();
1764 for (var cachedMessage : account.getMessageCache().getCachedMessages()) {
1765 var actions = retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
1766 if (actions != null) {
1767 queuedActions.addAll(actions);
1768 }
1769 }
1770 for (var action : queuedActions) {
1771 try {
1772 action.execute(this);
1773 } catch (Throwable e) {
1774 logger.warn("Message action failed.", e);
1775 }
1776 }
1777 }
1778
1779 private List<HandleAction> retryFailedReceivedMessage(
1780 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
1781 ) {
1782 var envelope = cachedMessage.loadEnvelope();
1783 if (envelope == null) {
1784 return null;
1785 }
1786 SignalServiceContent content = null;
1787 List<HandleAction> actions = null;
1788 if (!envelope.isReceipt()) {
1789 try {
1790 content = decryptMessage(envelope);
1791 } catch (ProtocolUntrustedIdentityException e) {
1792 if (!envelope.hasSource()) {
1793 final var identifier = e.getSender();
1794 final var recipientId = resolveRecipient(identifier);
1795 try {
1796 account.getMessageCache().replaceSender(cachedMessage, recipientId);
1797 } catch (IOException ioException) {
1798 logger.warn("Failed to move cached message to recipient folder: {}", ioException.getMessage());
1799 }
1800 }
1801 return null;
1802 } catch (Exception er) {
1803 // All other errors are not recoverable, so delete the cached message
1804 cachedMessage.delete();
1805 return null;
1806 }
1807 actions = handleMessage(envelope, content, ignoreAttachments);
1808 }
1809 handler.handleMessage(envelope, content, null);
1810 cachedMessage.delete();
1811 return actions;
1812 }
1813
1814 public void receiveMessages(
1815 long timeout,
1816 TimeUnit unit,
1817 boolean returnOnTimeout,
1818 boolean ignoreAttachments,
1819 ReceiveMessageHandler handler
1820 ) throws IOException {
1821 retryFailedReceivedMessages(handler, ignoreAttachments);
1822
1823 Set<HandleAction> queuedActions = null;
1824
1825 final var messagePipe = getOrCreateMessagePipe();
1826
1827 var hasCaughtUpWithOldMessages = false;
1828
1829 while (true) {
1830 SignalServiceEnvelope envelope;
1831 SignalServiceContent content = null;
1832 Exception exception = null;
1833 final CachedMessage[] cachedMessage = {null};
1834 try {
1835 var result = messagePipe.readOrEmpty(timeout, unit, envelope1 -> {
1836 final var recipientId = envelope1.hasSource()
1837 ? resolveRecipient(envelope1.getSourceIdentifier())
1838 : null;
1839 // store message on disk, before acknowledging receipt to the server
1840 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
1841 });
1842 if (result.isPresent()) {
1843 envelope = result.get();
1844 } else {
1845 // Received indicator that server queue is empty
1846 hasCaughtUpWithOldMessages = true;
1847
1848 if (queuedActions != null) {
1849 for (var action : queuedActions) {
1850 try {
1851 action.execute(this);
1852 } catch (Throwable e) {
1853 logger.warn("Message action failed.", e);
1854 }
1855 }
1856 queuedActions.clear();
1857 queuedActions = null;
1858 }
1859
1860 // Continue to wait another timeout for new messages
1861 continue;
1862 }
1863 } catch (TimeoutException e) {
1864 if (returnOnTimeout) return;
1865 continue;
1866 }
1867
1868 if (envelope.hasSource()) {
1869 // Store uuid if we don't have it already
1870 // address/uuid in envelope is sent by server
1871 resolveRecipientTrusted(envelope.getSourceAddress());
1872 }
1873 final var notAGroupMember = isNotAGroupMember(envelope, content);
1874 if (!envelope.isReceipt()) {
1875 try {
1876 content = decryptMessage(envelope);
1877 } catch (Exception e) {
1878 exception = e;
1879 }
1880 if (!envelope.hasSource() && content != null) {
1881 // Store uuid if we don't have it already
1882 // address/uuid is validated by unidentified sender certificate
1883 resolveRecipientTrusted(content.getSender());
1884 }
1885 var actions = handleMessage(envelope, content, ignoreAttachments);
1886 if (exception instanceof ProtocolInvalidMessageException) {
1887 final var sender = resolveRecipient(((ProtocolInvalidMessageException) exception).getSender());
1888 logger.debug("Received invalid message, queuing renew session action.");
1889 actions.add(new RenewSessionAction(sender));
1890 }
1891 if (hasCaughtUpWithOldMessages) {
1892 for (var action : actions) {
1893 try {
1894 action.execute(this);
1895 } catch (Throwable e) {
1896 logger.warn("Message action failed.", e);
1897 }
1898 }
1899 } else {
1900 if (queuedActions == null) {
1901 queuedActions = new HashSet<>();
1902 }
1903 queuedActions.addAll(actions);
1904 }
1905 }
1906 if (isMessageBlocked(envelope, content)) {
1907 logger.info("Ignoring a message from blocked user/group: {}", envelope.getTimestamp());
1908 } else if (notAGroupMember) {
1909 logger.info("Ignoring a message from a non group member: {}", envelope.getTimestamp());
1910 } else {
1911 handler.handleMessage(envelope, content, exception);
1912 }
1913 if (cachedMessage[0] != null) {
1914 if (exception instanceof ProtocolUntrustedIdentityException) {
1915 final var identifier = ((ProtocolUntrustedIdentityException) exception).getSender();
1916 final var recipientId = resolveRecipient(identifier);
1917 queuedActions.add(new RetrieveProfileAction(recipientId));
1918 if (!envelope.hasSource()) {
1919 try {
1920 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
1921 } catch (IOException ioException) {
1922 logger.warn("Failed to move cached message to recipient folder: {}",
1923 ioException.getMessage());
1924 }
1925 }
1926 } else {
1927 cachedMessage[0].delete();
1928 }
1929 }
1930 }
1931 }
1932
1933 private boolean isMessageBlocked(
1934 SignalServiceEnvelope envelope, SignalServiceContent content
1935 ) {
1936 SignalServiceAddress source;
1937 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1938 source = envelope.getSourceAddress();
1939 } else if (content != null) {
1940 source = content.getSender();
1941 } else {
1942 return false;
1943 }
1944 final var recipientId = resolveRecipient(source);
1945 if (isContactBlocked(recipientId)) {
1946 return true;
1947 }
1948
1949 if (content != null && content.getDataMessage().isPresent()) {
1950 var message = content.getDataMessage().get();
1951 if (message.getGroupContext().isPresent()) {
1952 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1953 var group = getGroup(groupId);
1954 if (group != null && group.isBlocked()) {
1955 return true;
1956 }
1957 }
1958 }
1959 return false;
1960 }
1961
1962 public boolean isContactBlocked(final String identifier) throws InvalidNumberException {
1963 final var recipientId = canonicalizeAndResolveRecipient(identifier);
1964 return isContactBlocked(recipientId);
1965 }
1966
1967 private boolean isContactBlocked(final RecipientId recipientId) {
1968 var sourceContact = account.getContactStore().getContact(recipientId);
1969 return sourceContact != null && sourceContact.isBlocked();
1970 }
1971
1972 private boolean isNotAGroupMember(
1973 SignalServiceEnvelope envelope, SignalServiceContent content
1974 ) {
1975 SignalServiceAddress source;
1976 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1977 source = envelope.getSourceAddress();
1978 } else if (content != null) {
1979 source = content.getSender();
1980 } else {
1981 return false;
1982 }
1983
1984 if (content != null && content.getDataMessage().isPresent()) {
1985 var message = content.getDataMessage().get();
1986 if (message.getGroupContext().isPresent()) {
1987 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1988 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1989 if (groupInfo.getType() == SignalServiceGroup.Type.QUIT) {
1990 return false;
1991 }
1992 }
1993 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1994 var group = getGroup(groupId);
1995 if (group != null && !group.isMember(resolveRecipient(source))) {
1996 return true;
1997 }
1998 }
1999 }
2000 return false;
2001 }
2002
2003 private List<HandleAction> handleMessage(
2004 SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments
2005 ) {
2006 var actions = new ArrayList<HandleAction>();
2007 if (content != null) {
2008 final SignalServiceAddress sender;
2009 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
2010 sender = envelope.getSourceAddress();
2011 } else {
2012 sender = content.getSender();
2013 }
2014
2015 if (content.getDataMessage().isPresent()) {
2016 var message = content.getDataMessage().get();
2017
2018 if (content.isNeedsReceipt()) {
2019 actions.add(new SendReceiptAction(sender, message.getTimestamp()));
2020 }
2021
2022 actions.addAll(handleSignalServiceDataMessage(message,
2023 false,
2024 sender,
2025 account.getSelfAddress(),
2026 ignoreAttachments));
2027 }
2028 if (content.getSyncMessage().isPresent()) {
2029 account.setMultiDevice(true);
2030 var syncMessage = content.getSyncMessage().get();
2031 if (syncMessage.getSent().isPresent()) {
2032 var message = syncMessage.getSent().get();
2033 final var destination = message.getDestination().orNull();
2034 actions.addAll(handleSignalServiceDataMessage(message.getMessage(),
2035 true,
2036 sender,
2037 destination,
2038 ignoreAttachments));
2039 }
2040 if (syncMessage.getRequest().isPresent() && account.isMasterDevice()) {
2041 var rm = syncMessage.getRequest().get();
2042 if (rm.isContactsRequest()) {
2043 actions.add(SendSyncContactsAction.create());
2044 }
2045 if (rm.isGroupsRequest()) {
2046 actions.add(SendSyncGroupsAction.create());
2047 }
2048 if (rm.isBlockedListRequest()) {
2049 actions.add(SendSyncBlockedListAction.create());
2050 }
2051 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2052 }
2053 if (syncMessage.getGroups().isPresent()) {
2054 File tmpFile = null;
2055 try {
2056 tmpFile = IOUtils.createTempFile();
2057 final var groupsMessage = syncMessage.getGroups().get();
2058 try (var attachmentAsStream = retrieveAttachmentAsStream(groupsMessage.asPointer(), tmpFile)) {
2059 var s = new DeviceGroupsInputStream(attachmentAsStream);
2060 DeviceGroup g;
2061 while ((g = s.read()) != null) {
2062 var syncGroup = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(g.getId()));
2063 if (syncGroup != null) {
2064 if (g.getName().isPresent()) {
2065 syncGroup.name = g.getName().get();
2066 }
2067 syncGroup.addMembers(g.getMembers()
2068 .stream()
2069 .map(this::resolveRecipient)
2070 .collect(Collectors.toSet()));
2071 if (!g.isActive()) {
2072 syncGroup.removeMember(account.getSelfRecipientId());
2073 } else {
2074 // Add ourself to the member set as it's marked as active
2075 syncGroup.addMembers(List.of(account.getSelfRecipientId()));
2076 }
2077 syncGroup.blocked = g.isBlocked();
2078 if (g.getColor().isPresent()) {
2079 syncGroup.color = g.getColor().get();
2080 }
2081
2082 if (g.getAvatar().isPresent()) {
2083 downloadGroupAvatar(g.getAvatar().get(), syncGroup.getGroupId());
2084 }
2085 syncGroup.archived = g.isArchived();
2086 account.getGroupStore().updateGroup(syncGroup);
2087 }
2088 }
2089 }
2090 } catch (Exception e) {
2091 logger.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2092 tmpFile,
2093 e.getMessage());
2094 } finally {
2095 if (tmpFile != null) {
2096 try {
2097 Files.delete(tmpFile.toPath());
2098 } catch (IOException e) {
2099 logger.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2100 tmpFile,
2101 e.getMessage());
2102 }
2103 }
2104 }
2105 }
2106 if (syncMessage.getBlockedList().isPresent()) {
2107 final var blockedListMessage = syncMessage.getBlockedList().get();
2108 for (var address : blockedListMessage.getAddresses()) {
2109 setContactBlocked(resolveRecipient(address), true);
2110 }
2111 for (var groupId : blockedListMessage.getGroupIds()
2112 .stream()
2113 .map(GroupId::unknownVersion)
2114 .collect(Collectors.toSet())) {
2115 try {
2116 setGroupBlocked(groupId, true);
2117 } catch (GroupNotFoundException e) {
2118 logger.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2119 groupId.toBase64());
2120 }
2121 }
2122 }
2123 if (syncMessage.getContacts().isPresent()) {
2124 File tmpFile = null;
2125 try {
2126 tmpFile = IOUtils.createTempFile();
2127 final var contactsMessage = syncMessage.getContacts().get();
2128 try (var attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream()
2129 .asPointer(), tmpFile)) {
2130 var s = new DeviceContactsInputStream(attachmentAsStream);
2131 DeviceContact c;
2132 while ((c = s.read()) != null) {
2133 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
2134 account.setProfileKey(c.getProfileKey().get());
2135 }
2136 final var recipientId = resolveRecipientTrusted(c.getAddress());
2137 var contact = account.getContactStore().getContact(recipientId);
2138 final var builder = contact == null
2139 ? Contact.newBuilder()
2140 : Contact.newBuilder(contact);
2141 if (c.getName().isPresent()) {
2142 builder.withName(c.getName().get());
2143 }
2144 if (c.getColor().isPresent()) {
2145 builder.withColor(c.getColor().get());
2146 }
2147 if (c.getProfileKey().isPresent()) {
2148 account.getProfileStore().storeProfileKey(recipientId, c.getProfileKey().get());
2149 }
2150 if (c.getVerified().isPresent()) {
2151 final var verifiedMessage = c.getVerified().get();
2152 account.getIdentityKeyStore()
2153 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
2154 verifiedMessage.getIdentityKey(),
2155 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2156 }
2157 if (c.getExpirationTimer().isPresent()) {
2158 builder.withMessageExpirationTime(c.getExpirationTimer().get());
2159 }
2160 builder.withBlocked(c.isBlocked());
2161 builder.withArchived(c.isArchived());
2162 account.getContactStore().storeContact(recipientId, builder.build());
2163
2164 if (c.getAvatar().isPresent()) {
2165 downloadContactAvatar(c.getAvatar().get(), c.getAddress());
2166 }
2167 }
2168 }
2169 } catch (Exception e) {
2170 logger.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2171 tmpFile,
2172 e.getMessage());
2173 } finally {
2174 if (tmpFile != null) {
2175 try {
2176 Files.delete(tmpFile.toPath());
2177 } catch (IOException e) {
2178 logger.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2179 tmpFile,
2180 e.getMessage());
2181 }
2182 }
2183 }
2184 }
2185 if (syncMessage.getVerified().isPresent()) {
2186 final var verifiedMessage = syncMessage.getVerified().get();
2187 account.getIdentityKeyStore()
2188 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
2189 verifiedMessage.getIdentityKey(),
2190 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2191 }
2192 if (syncMessage.getStickerPackOperations().isPresent()) {
2193 final var stickerPackOperationMessages = syncMessage.getStickerPackOperations().get();
2194 for (var m : stickerPackOperationMessages) {
2195 if (!m.getPackId().isPresent()) {
2196 continue;
2197 }
2198 final var stickerPackId = StickerPackId.deserialize(m.getPackId().get());
2199 var sticker = account.getStickerStore().getSticker(stickerPackId);
2200 if (sticker == null) {
2201 if (!m.getPackKey().isPresent()) {
2202 continue;
2203 }
2204 sticker = new Sticker(stickerPackId, m.getPackKey().get());
2205 }
2206 sticker.setInstalled(!m.getType().isPresent()
2207 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL);
2208 account.getStickerStore().updateSticker(sticker);
2209 }
2210 }
2211 if (syncMessage.getFetchType().isPresent()) {
2212 switch (syncMessage.getFetchType().get()) {
2213 case LOCAL_PROFILE:
2214 getRecipientProfile(account.getSelfRecipientId(), true);
2215 case STORAGE_MANIFEST:
2216 // TODO
2217 }
2218 }
2219 if (syncMessage.getKeys().isPresent()) {
2220 final var keysMessage = syncMessage.getKeys().get();
2221 if (keysMessage.getStorageService().isPresent()) {
2222 final var storageKey = keysMessage.getStorageService().get();
2223 account.setStorageKey(storageKey);
2224 }
2225 }
2226 if (syncMessage.getConfiguration().isPresent()) {
2227 // TODO
2228 }
2229 }
2230 }
2231 return actions;
2232 }
2233
2234 private void downloadContactAvatar(SignalServiceAttachment avatar, SignalServiceAddress address) {
2235 try {
2236 avatarStore.storeContactAvatar(address, outputStream -> retrieveAttachment(avatar, outputStream));
2237 } catch (IOException e) {
2238 logger.warn("Failed to download avatar for contact {}, ignoring: {}", address, e.getMessage());
2239 }
2240 }
2241
2242 private void downloadGroupAvatar(SignalServiceAttachment avatar, GroupId groupId) {
2243 try {
2244 avatarStore.storeGroupAvatar(groupId, outputStream -> retrieveAttachment(avatar, outputStream));
2245 } catch (IOException e) {
2246 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2247 }
2248 }
2249
2250 private void downloadGroupAvatar(GroupId groupId, GroupSecretParams groupSecretParams, String cdnKey) {
2251 try {
2252 avatarStore.storeGroupAvatar(groupId,
2253 outputStream -> retrieveGroupV2Avatar(groupSecretParams, cdnKey, outputStream));
2254 } catch (IOException e) {
2255 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2256 }
2257 }
2258
2259 private void downloadProfileAvatar(
2260 SignalServiceAddress address, String avatarPath, ProfileKey profileKey
2261 ) {
2262 try {
2263 avatarStore.storeProfileAvatar(address,
2264 outputStream -> retrieveProfileAvatar(avatarPath, profileKey, outputStream));
2265 } catch (Throwable e) {
2266 logger.warn("Failed to download profile avatar, ignoring: {}", e.getMessage());
2267 }
2268 }
2269
2270 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
2271 return attachmentStore.getAttachmentFile(attachmentId);
2272 }
2273
2274 private void downloadAttachment(final SignalServiceAttachment attachment) {
2275 if (!attachment.isPointer()) {
2276 logger.warn("Invalid state, can't store an attachment stream.");
2277 }
2278
2279 var pointer = attachment.asPointer();
2280 if (pointer.getPreview().isPresent()) {
2281 final var preview = pointer.getPreview().get();
2282 try {
2283 attachmentStore.storeAttachmentPreview(pointer.getRemoteId(),
2284 outputStream -> outputStream.write(preview, 0, preview.length));
2285 } catch (IOException e) {
2286 logger.warn("Failed to download attachment preview, ignoring: {}", e.getMessage());
2287 }
2288 }
2289
2290 try {
2291 attachmentStore.storeAttachment(pointer.getRemoteId(),
2292 outputStream -> retrieveAttachmentPointer(pointer, outputStream));
2293 } catch (IOException e) {
2294 logger.warn("Failed to download attachment ({}), ignoring: {}", pointer.getRemoteId(), e.getMessage());
2295 }
2296 }
2297
2298 private void retrieveGroupV2Avatar(
2299 GroupSecretParams groupSecretParams, String cdnKey, OutputStream outputStream
2300 ) throws IOException {
2301 var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
2302
2303 var tmpFile = IOUtils.createTempFile();
2304 try (InputStream input = messageReceiver.retrieveGroupsV2ProfileAvatar(cdnKey,
2305 tmpFile,
2306 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2307 var encryptedData = IOUtils.readFully(input);
2308
2309 var decryptedData = groupOperations.decryptAvatar(encryptedData);
2310 outputStream.write(decryptedData);
2311 } finally {
2312 try {
2313 Files.delete(tmpFile.toPath());
2314 } catch (IOException e) {
2315 logger.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2316 tmpFile,
2317 e.getMessage());
2318 }
2319 }
2320 }
2321
2322 private void retrieveProfileAvatar(
2323 String avatarPath, ProfileKey profileKey, OutputStream outputStream
2324 ) throws IOException {
2325 var tmpFile = IOUtils.createTempFile();
2326 try (var input = messageReceiver.retrieveProfileAvatar(avatarPath,
2327 tmpFile,
2328 profileKey,
2329 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2330 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2331 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
2332 } finally {
2333 try {
2334 Files.delete(tmpFile.toPath());
2335 } catch (IOException e) {
2336 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2337 tmpFile,
2338 e.getMessage());
2339 }
2340 }
2341 }
2342
2343 private void retrieveAttachment(
2344 final SignalServiceAttachment attachment, final OutputStream outputStream
2345 ) throws IOException {
2346 if (attachment.isPointer()) {
2347 var pointer = attachment.asPointer();
2348 retrieveAttachmentPointer(pointer, outputStream);
2349 } else {
2350 var stream = attachment.asStream();
2351 IOUtils.copyStream(stream.getInputStream(), outputStream);
2352 }
2353 }
2354
2355 private void retrieveAttachmentPointer(
2356 SignalServiceAttachmentPointer pointer, OutputStream outputStream
2357 ) throws IOException {
2358 var tmpFile = IOUtils.createTempFile();
2359 try (var input = retrieveAttachmentAsStream(pointer, tmpFile)) {
2360 IOUtils.copyStream(input, outputStream);
2361 } catch (MissingConfigurationException | InvalidMessageException e) {
2362 throw new IOException(e);
2363 } finally {
2364 try {
2365 Files.delete(tmpFile.toPath());
2366 } catch (IOException e) {
2367 logger.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2368 tmpFile,
2369 e.getMessage());
2370 }
2371 }
2372 }
2373
2374 private InputStream retrieveAttachmentAsStream(
2375 SignalServiceAttachmentPointer pointer, File tmpFile
2376 ) throws IOException, InvalidMessageException, MissingConfigurationException {
2377 return messageReceiver.retrieveAttachment(pointer, tmpFile, ServiceConfig.MAX_ATTACHMENT_SIZE);
2378 }
2379
2380 void sendGroups() throws IOException, UntrustedIdentityException {
2381 var groupsFile = IOUtils.createTempFile();
2382
2383 try {
2384 try (OutputStream fos = new FileOutputStream(groupsFile)) {
2385 var out = new DeviceGroupsOutputStream(fos);
2386 for (var record : getGroups()) {
2387 if (record instanceof GroupInfoV1) {
2388 var groupInfo = (GroupInfoV1) record;
2389 out.write(new DeviceGroup(groupInfo.getGroupId().serialize(),
2390 Optional.fromNullable(groupInfo.name),
2391 groupInfo.getMembers()
2392 .stream()
2393 .map(this::resolveSignalServiceAddress)
2394 .collect(Collectors.toList()),
2395 createGroupAvatarAttachment(groupInfo.getGroupId()),
2396 groupInfo.isMember(account.getSelfRecipientId()),
2397 Optional.of(groupInfo.messageExpirationTime),
2398 Optional.fromNullable(groupInfo.color),
2399 groupInfo.blocked,
2400 Optional.absent(),
2401 groupInfo.archived));
2402 }
2403 }
2404 }
2405
2406 if (groupsFile.exists() && groupsFile.length() > 0) {
2407 try (var groupsFileStream = new FileInputStream(groupsFile)) {
2408 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2409 .withStream(groupsFileStream)
2410 .withContentType("application/octet-stream")
2411 .withLength(groupsFile.length())
2412 .build();
2413
2414 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
2415 }
2416 }
2417 } finally {
2418 try {
2419 Files.delete(groupsFile.toPath());
2420 } catch (IOException e) {
2421 logger.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile, e.getMessage());
2422 }
2423 }
2424 }
2425
2426 public void sendContacts() throws IOException, UntrustedIdentityException {
2427 var contactsFile = IOUtils.createTempFile();
2428
2429 try {
2430 try (OutputStream fos = new FileOutputStream(contactsFile)) {
2431 var out = new DeviceContactsOutputStream(fos);
2432 for (var contactPair : account.getContactStore().getContacts()) {
2433 final var recipientId = contactPair.first();
2434 final var contact = contactPair.second();
2435 final var address = resolveSignalServiceAddress(recipientId);
2436
2437 var currentIdentity = account.getIdentityKeyStore().getIdentity(recipientId);
2438 VerifiedMessage verifiedMessage = null;
2439 if (currentIdentity != null) {
2440 verifiedMessage = new VerifiedMessage(address,
2441 currentIdentity.getIdentityKey(),
2442 currentIdentity.getTrustLevel().toVerifiedState(),
2443 currentIdentity.getDateAdded().getTime());
2444 }
2445
2446 var profileKey = account.getProfileStore().getProfileKey(recipientId);
2447 out.write(new DeviceContact(address,
2448 Optional.fromNullable(contact.getName()),
2449 createContactAvatarAttachment(address),
2450 Optional.fromNullable(contact.getColor()),
2451 Optional.fromNullable(verifiedMessage),
2452 Optional.fromNullable(profileKey),
2453 contact.isBlocked(),
2454 Optional.of(contact.getMessageExpirationTime()),
2455 Optional.absent(),
2456 contact.isArchived()));
2457 }
2458
2459 if (account.getProfileKey() != null) {
2460 // Send our own profile key as well
2461 out.write(new DeviceContact(account.getSelfAddress(),
2462 Optional.absent(),
2463 Optional.absent(),
2464 Optional.absent(),
2465 Optional.absent(),
2466 Optional.of(account.getProfileKey()),
2467 false,
2468 Optional.absent(),
2469 Optional.absent(),
2470 false));
2471 }
2472 }
2473
2474 if (contactsFile.exists() && contactsFile.length() > 0) {
2475 try (var contactsFileStream = new FileInputStream(contactsFile)) {
2476 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2477 .withStream(contactsFileStream)
2478 .withContentType("application/octet-stream")
2479 .withLength(contactsFile.length())
2480 .build();
2481
2482 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
2483 }
2484 }
2485 } finally {
2486 try {
2487 Files.delete(contactsFile.toPath());
2488 } catch (IOException e) {
2489 logger.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile, e.getMessage());
2490 }
2491 }
2492 }
2493
2494 void sendBlockedList() throws IOException, UntrustedIdentityException {
2495 var addresses = new ArrayList<SignalServiceAddress>();
2496 for (var record : account.getContactStore().getContacts()) {
2497 if (record.second().isBlocked()) {
2498 addresses.add(resolveSignalServiceAddress(record.first()));
2499 }
2500 }
2501 var groupIds = new ArrayList<byte[]>();
2502 for (var record : getGroups()) {
2503 if (record.isBlocked()) {
2504 groupIds.add(record.getGroupId().serialize());
2505 }
2506 }
2507 sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
2508 }
2509
2510 private void sendVerifiedMessage(
2511 SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel
2512 ) throws IOException, UntrustedIdentityException {
2513 var verifiedMessage = new VerifiedMessage(destination,
2514 identityKey,
2515 trustLevel.toVerifiedState(),
2516 System.currentTimeMillis());
2517 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
2518 }
2519
2520 public List<Pair<RecipientId, Contact>> getContacts() {
2521 return account.getContactStore().getContacts();
2522 }
2523
2524 public String getContactOrProfileName(String number) throws InvalidNumberException {
2525 final var recipientId = canonicalizeAndResolveRecipient(number);
2526 final var recipient = account.getRecipientStore().getRecipient(recipientId);
2527 if (recipient == null) {
2528 return null;
2529 }
2530
2531 if (recipient.getContact() != null && !Util.isEmpty(recipient.getContact().getName())) {
2532 return recipient.getContact().getName();
2533 }
2534
2535 if (recipient.getProfile() != null && recipient.getProfile() != null) {
2536 return recipient.getProfile().getDisplayName();
2537 }
2538
2539 return null;
2540 }
2541
2542 public GroupInfo getGroup(GroupId groupId) {
2543 final var group = account.getGroupStore().getGroup(groupId);
2544 if (group instanceof GroupInfoV2 && ((GroupInfoV2) group).getGroup() == null) {
2545 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(((GroupInfoV2) group).getMasterKey());
2546 ((GroupInfoV2) group).setGroup(groupHelper.getDecryptedGroup(groupSecretParams), this::resolveRecipient);
2547 account.getGroupStore().updateGroup(group);
2548 }
2549 return group;
2550 }
2551
2552 public List<IdentityInfo> getIdentities() {
2553 return account.getIdentityKeyStore().getIdentities();
2554 }
2555
2556 public List<IdentityInfo> getIdentities(String number) throws InvalidNumberException {
2557 final var identity = account.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number));
2558 return identity == null ? List.of() : List.of(identity);
2559 }
2560
2561 /**
2562 * Trust this the identity with this fingerprint
2563 *
2564 * @param name username of the identity
2565 * @param fingerprint Fingerprint
2566 */
2567 public boolean trustIdentityVerified(String name, byte[] fingerprint) throws InvalidNumberException {
2568 var recipientId = canonicalizeAndResolveRecipient(name);
2569 return trustIdentity(recipientId,
2570 identityKey -> Arrays.equals(identityKey.serialize(), fingerprint),
2571 TrustLevel.TRUSTED_VERIFIED);
2572 }
2573
2574 /**
2575 * Trust this the identity with this safety number
2576 *
2577 * @param name username of the identity
2578 * @param safetyNumber Safety number
2579 */
2580 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) throws InvalidNumberException {
2581 var recipientId = canonicalizeAndResolveRecipient(name);
2582 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
2583 return trustIdentity(recipientId,
2584 identityKey -> safetyNumber.equals(computeSafetyNumber(address, identityKey)),
2585 TrustLevel.TRUSTED_VERIFIED);
2586 }
2587
2588 /**
2589 * Trust all keys of this identity without verification
2590 *
2591 * @param name username of the identity
2592 */
2593 public boolean trustIdentityAllKeys(String name) throws InvalidNumberException {
2594 var recipientId = canonicalizeAndResolveRecipient(name);
2595 return trustIdentity(recipientId, identityKey -> true, TrustLevel.TRUSTED_UNVERIFIED);
2596 }
2597
2598 private boolean trustIdentity(
2599 RecipientId recipientId, Function<IdentityKey, Boolean> verifier, TrustLevel trustLevel
2600 ) {
2601 var identity = account.getIdentityKeyStore().getIdentity(recipientId);
2602 if (identity == null) {
2603 return false;
2604 }
2605
2606 if (!verifier.apply(identity.getIdentityKey())) {
2607 return false;
2608 }
2609
2610 account.getIdentityKeyStore().setIdentityTrustLevel(recipientId, identity.getIdentityKey(), trustLevel);
2611 try {
2612 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
2613 sendVerifiedMessage(address, identity.getIdentityKey(), trustLevel);
2614 } catch (IOException | UntrustedIdentityException e) {
2615 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2616 }
2617
2618 return true;
2619 }
2620
2621 public String computeSafetyNumber(
2622 SignalServiceAddress theirAddress, IdentityKey theirIdentityKey
2623 ) {
2624 return Utils.computeSafetyNumber(ServiceConfig.capabilities.isUuid(),
2625 account.getSelfAddress(),
2626 getIdentityKeyPair().getPublicKey(),
2627 theirAddress,
2628 theirIdentityKey);
2629 }
2630
2631 @Deprecated
2632 public SignalServiceAddress resolveSignalServiceAddress(String identifier) {
2633 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2634
2635 return resolveSignalServiceAddress(address);
2636 }
2637
2638 @Deprecated
2639 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
2640 if (address.matches(account.getSelfAddress())) {
2641 return account.getSelfAddress();
2642 }
2643
2644 return account.getRecipientStore().resolveServiceAddress(address);
2645 }
2646
2647 public SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
2648 return account.getRecipientStore().resolveServiceAddress(recipientId);
2649 }
2650
2651 public RecipientId canonicalizeAndResolveRecipient(String identifier) throws InvalidNumberException {
2652 var canonicalizedNumber = UuidUtil.isUuid(identifier)
2653 ? identifier
2654 : PhoneNumberFormatter.formatNumber(identifier, account.getUsername());
2655
2656 return resolveRecipient(canonicalizedNumber);
2657 }
2658
2659 private RecipientId resolveRecipient(final String identifier) {
2660 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2661
2662 return resolveRecipient(address);
2663 }
2664
2665 public RecipientId resolveRecipient(SignalServiceAddress address) {
2666 return account.getRecipientStore().resolveRecipient(address);
2667 }
2668
2669 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
2670 return account.getRecipientStore().resolveRecipientTrusted(address);
2671 }
2672
2673 @Override
2674 public void close() throws IOException {
2675 close(true);
2676 }
2677
2678 void close(boolean closeAccount) throws IOException {
2679 executor.shutdown();
2680
2681 if (messagePipe != null) {
2682 messagePipe.shutdown();
2683 messagePipe = null;
2684 }
2685
2686 if (unidentifiedMessagePipe != null) {
2687 unidentifiedMessagePipe.shutdown();
2688 unidentifiedMessagePipe = null;
2689 }
2690
2691 if (closeAccount && account != null) {
2692 account.close();
2693 }
2694 account = null;
2695 }
2696
2697 public interface ReceiveMessageHandler {
2698
2699 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
2700 }
2701 }