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