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