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