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