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