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