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