]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/Manager.java
Store messages in cache by recipient id
[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 if (!envelope.hasSource()) {
1633 final var recipientId = resolveRecipient(((org.whispersystems.libsignal.UntrustedIdentityException) e)
1634 .getName());
1635 try {
1636 account.getMessageCache().replaceSender(cachedMessage, recipientId);
1637 } catch (IOException ioException) {
1638 logger.warn("Failed to move cached message to recipient folder: {}", ioException.getMessage());
1639 }
1640 }
1641 return;
1642 } catch (Exception er) {
1643 // All other errors are not recoverable, so delete the cached message
1644 cachedMessage.delete();
1645 return;
1646 }
1647 var actions = handleMessage(envelope, content, ignoreAttachments);
1648 for (var action : actions) {
1649 try {
1650 action.execute(this);
1651 } catch (Throwable e) {
1652 logger.warn("Message action failed.", e);
1653 }
1654 }
1655 }
1656 account.save();
1657 handler.handleMessage(envelope, content, null);
1658 cachedMessage.delete();
1659 }
1660
1661 public void receiveMessages(
1662 long timeout,
1663 TimeUnit unit,
1664 boolean returnOnTimeout,
1665 boolean ignoreAttachments,
1666 ReceiveMessageHandler handler
1667 ) throws IOException {
1668 retryFailedReceivedMessages(handler, ignoreAttachments);
1669
1670 Set<HandleAction> queuedActions = null;
1671
1672 final var messagePipe = getOrCreateMessagePipe();
1673
1674 var hasCaughtUpWithOldMessages = false;
1675
1676 while (true) {
1677 SignalServiceEnvelope envelope;
1678 SignalServiceContent content = null;
1679 Exception exception = null;
1680 final CachedMessage[] cachedMessage = {null};
1681 try {
1682 var result = messagePipe.readOrEmpty(timeout, unit, envelope1 -> {
1683 final var recipientId = envelope1.hasSource()
1684 ? resolveRecipient(envelope1.getSourceIdentifier())
1685 : null;
1686 // store message on disk, before acknowledging receipt to the server
1687 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
1688 });
1689 if (result.isPresent()) {
1690 envelope = result.get();
1691 } else {
1692 // Received indicator that server queue is empty
1693 hasCaughtUpWithOldMessages = true;
1694
1695 if (queuedActions != null) {
1696 for (var action : queuedActions) {
1697 try {
1698 action.execute(this);
1699 } catch (Throwable e) {
1700 logger.warn("Message action failed.", e);
1701 }
1702 }
1703 account.save();
1704 queuedActions.clear();
1705 queuedActions = null;
1706 }
1707
1708 // Continue to wait another timeout for new messages
1709 continue;
1710 }
1711 } catch (TimeoutException e) {
1712 if (returnOnTimeout) return;
1713 continue;
1714 }
1715
1716 if (envelope.hasSource()) {
1717 // Store uuid if we don't have it already
1718 resolveRecipientTrusted(envelope.getSourceAddress());
1719 }
1720 if (!envelope.isReceipt()) {
1721 try {
1722 content = decryptMessage(envelope);
1723 } catch (Exception e) {
1724 exception = e;
1725 }
1726 var actions = handleMessage(envelope, content, ignoreAttachments);
1727 if (hasCaughtUpWithOldMessages) {
1728 for (var action : actions) {
1729 try {
1730 action.execute(this);
1731 } catch (Throwable e) {
1732 logger.warn("Message action failed.", e);
1733 }
1734 }
1735 } else {
1736 if (queuedActions == null) {
1737 queuedActions = new HashSet<>();
1738 }
1739 queuedActions.addAll(actions);
1740 }
1741 }
1742 account.save();
1743 if (isMessageBlocked(envelope, content)) {
1744 logger.info("Ignoring a message from blocked user/group: {}", envelope.getTimestamp());
1745 } else if (isNotAGroupMember(envelope, content)) {
1746 logger.info("Ignoring a message from a non group member: {}", envelope.getTimestamp());
1747 } else {
1748 handler.handleMessage(envelope, content, exception);
1749 }
1750 if (cachedMessage[0] != null) {
1751 if (exception instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
1752 if (!envelope.hasSource()) {
1753 final var recipientId = resolveRecipient(((org.whispersystems.libsignal.UntrustedIdentityException) exception)
1754 .getName());
1755 try {
1756 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
1757 } catch (IOException ioException) {
1758 logger.warn("Failed to move cached message to recipient folder: {}",
1759 ioException.getMessage());
1760 }
1761 }
1762 } else {
1763 cachedMessage[0].delete();
1764 }
1765 }
1766 }
1767 }
1768
1769 private boolean isMessageBlocked(
1770 SignalServiceEnvelope envelope, SignalServiceContent content
1771 ) {
1772 SignalServiceAddress source;
1773 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1774 source = envelope.getSourceAddress();
1775 } else if (content != null) {
1776 source = content.getSender();
1777 } else {
1778 return false;
1779 }
1780 var sourceContact = account.getContactStore().getContact(source);
1781 if (sourceContact != null && sourceContact.blocked) {
1782 return true;
1783 }
1784
1785 if (content != null && content.getDataMessage().isPresent()) {
1786 var message = content.getDataMessage().get();
1787 if (message.getGroupContext().isPresent()) {
1788 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1789 var group = getGroup(groupId);
1790 if (group != null && group.isBlocked()) {
1791 return true;
1792 }
1793 }
1794 }
1795 return false;
1796 }
1797
1798 private boolean isNotAGroupMember(
1799 SignalServiceEnvelope envelope, SignalServiceContent content
1800 ) {
1801 SignalServiceAddress source;
1802 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1803 source = envelope.getSourceAddress();
1804 } else if (content != null) {
1805 source = content.getSender();
1806 } else {
1807 return false;
1808 }
1809
1810 if (content != null && content.getDataMessage().isPresent()) {
1811 var message = content.getDataMessage().get();
1812 if (message.getGroupContext().isPresent()) {
1813 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1814 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1815 if (groupInfo.getType() == SignalServiceGroup.Type.QUIT) {
1816 return false;
1817 }
1818 }
1819 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1820 var group = getGroup(groupId);
1821 if (group != null && !group.isMember(source)) {
1822 return true;
1823 }
1824 }
1825 }
1826 return false;
1827 }
1828
1829 private List<HandleAction> handleMessage(
1830 SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments
1831 ) {
1832 var actions = new ArrayList<HandleAction>();
1833 if (content != null) {
1834 final SignalServiceAddress sender;
1835 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1836 sender = envelope.getSourceAddress();
1837 } else {
1838 sender = content.getSender();
1839 }
1840 // Store uuid if we don't have it already
1841 resolveSignalServiceAddress(sender);
1842
1843 if (content.getDataMessage().isPresent()) {
1844 var message = content.getDataMessage().get();
1845
1846 if (content.isNeedsReceipt()) {
1847 actions.add(new SendReceiptAction(sender, message.getTimestamp()));
1848 }
1849
1850 actions.addAll(handleSignalServiceDataMessage(message,
1851 false,
1852 sender,
1853 account.getSelfAddress(),
1854 ignoreAttachments));
1855 }
1856 if (content.getSyncMessage().isPresent()) {
1857 account.setMultiDevice(true);
1858 var syncMessage = content.getSyncMessage().get();
1859 if (syncMessage.getSent().isPresent()) {
1860 var message = syncMessage.getSent().get();
1861 final var destination = message.getDestination().orNull();
1862 actions.addAll(handleSignalServiceDataMessage(message.getMessage(),
1863 true,
1864 sender,
1865 destination,
1866 ignoreAttachments));
1867 }
1868 if (syncMessage.getRequest().isPresent()) {
1869 var rm = syncMessage.getRequest().get();
1870 if (rm.isContactsRequest()) {
1871 actions.add(SendSyncContactsAction.create());
1872 }
1873 if (rm.isGroupsRequest()) {
1874 actions.add(SendSyncGroupsAction.create());
1875 }
1876 if (rm.isBlockedListRequest()) {
1877 actions.add(SendSyncBlockedListAction.create());
1878 }
1879 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1880 }
1881 if (syncMessage.getGroups().isPresent()) {
1882 File tmpFile = null;
1883 try {
1884 tmpFile = IOUtils.createTempFile();
1885 final var groupsMessage = syncMessage.getGroups().get();
1886 try (var attachmentAsStream = retrieveAttachmentAsStream(groupsMessage.asPointer(), tmpFile)) {
1887 var s = new DeviceGroupsInputStream(attachmentAsStream);
1888 DeviceGroup g;
1889 while ((g = s.read()) != null) {
1890 var syncGroup = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(g.getId()));
1891 if (syncGroup != null) {
1892 if (g.getName().isPresent()) {
1893 syncGroup.name = g.getName().get();
1894 }
1895 syncGroup.addMembers(g.getMembers()
1896 .stream()
1897 .map(this::resolveSignalServiceAddress)
1898 .collect(Collectors.toSet()));
1899 if (!g.isActive()) {
1900 syncGroup.removeMember(account.getSelfAddress());
1901 } else {
1902 // Add ourself to the member set as it's marked as active
1903 syncGroup.addMembers(List.of(account.getSelfAddress()));
1904 }
1905 syncGroup.blocked = g.isBlocked();
1906 if (g.getColor().isPresent()) {
1907 syncGroup.color = g.getColor().get();
1908 }
1909
1910 if (g.getAvatar().isPresent()) {
1911 downloadGroupAvatar(g.getAvatar().get(), syncGroup.getGroupId());
1912 }
1913 syncGroup.inboxPosition = g.getInboxPosition().orNull();
1914 syncGroup.archived = g.isArchived();
1915 account.getGroupStore().updateGroup(syncGroup);
1916 }
1917 }
1918 }
1919 } catch (Exception e) {
1920 logger.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1921 tmpFile,
1922 e.getMessage());
1923 } finally {
1924 if (tmpFile != null) {
1925 try {
1926 Files.delete(tmpFile.toPath());
1927 } catch (IOException e) {
1928 logger.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1929 tmpFile,
1930 e.getMessage());
1931 }
1932 }
1933 }
1934 }
1935 if (syncMessage.getBlockedList().isPresent()) {
1936 final var blockedListMessage = syncMessage.getBlockedList().get();
1937 for (var address : blockedListMessage.getAddresses()) {
1938 setContactBlocked(resolveSignalServiceAddress(address), true);
1939 }
1940 for (var groupId : blockedListMessage.getGroupIds()
1941 .stream()
1942 .map(GroupId::unknownVersion)
1943 .collect(Collectors.toSet())) {
1944 try {
1945 setGroupBlocked(groupId, true);
1946 } catch (GroupNotFoundException e) {
1947 logger.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1948 groupId.toBase64());
1949 }
1950 }
1951 }
1952 if (syncMessage.getContacts().isPresent()) {
1953 File tmpFile = null;
1954 try {
1955 tmpFile = IOUtils.createTempFile();
1956 final var contactsMessage = syncMessage.getContacts().get();
1957 try (var attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream()
1958 .asPointer(), tmpFile)) {
1959 var s = new DeviceContactsInputStream(attachmentAsStream);
1960 if (contactsMessage.isComplete()) {
1961 account.getContactStore().clear();
1962 }
1963 DeviceContact c;
1964 while ((c = s.read()) != null) {
1965 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
1966 account.setProfileKey(c.getProfileKey().get());
1967 }
1968 final var address = resolveSignalServiceAddress(c.getAddress());
1969 var contact = account.getContactStore().getContact(address);
1970 if (contact == null) {
1971 contact = new ContactInfo(address);
1972 }
1973 if (c.getName().isPresent()) {
1974 contact.name = c.getName().get();
1975 }
1976 if (c.getColor().isPresent()) {
1977 contact.color = c.getColor().get();
1978 }
1979 if (c.getProfileKey().isPresent()) {
1980 account.getProfileStore().storeProfileKey(address, c.getProfileKey().get());
1981 }
1982 if (c.getVerified().isPresent()) {
1983 final var verifiedMessage = c.getVerified().get();
1984 account.getIdentityKeyStore()
1985 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
1986 verifiedMessage.getIdentityKey(),
1987 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1988 }
1989 if (c.getExpirationTimer().isPresent()) {
1990 contact.messageExpirationTime = c.getExpirationTimer().get();
1991 }
1992 contact.blocked = c.isBlocked();
1993 contact.inboxPosition = c.getInboxPosition().orNull();
1994 contact.archived = c.isArchived();
1995 account.getContactStore().updateContact(contact);
1996
1997 if (c.getAvatar().isPresent()) {
1998 downloadContactAvatar(c.getAvatar().get(), contact.getAddress());
1999 }
2000 }
2001 }
2002 } catch (Exception e) {
2003 logger.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2004 tmpFile,
2005 e.getMessage());
2006 } finally {
2007 if (tmpFile != null) {
2008 try {
2009 Files.delete(tmpFile.toPath());
2010 } catch (IOException e) {
2011 logger.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2012 tmpFile,
2013 e.getMessage());
2014 }
2015 }
2016 }
2017 }
2018 if (syncMessage.getVerified().isPresent()) {
2019 final var verifiedMessage = syncMessage.getVerified().get();
2020 account.getIdentityKeyStore()
2021 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
2022 verifiedMessage.getIdentityKey(),
2023 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2024 }
2025 if (syncMessage.getStickerPackOperations().isPresent()) {
2026 final var stickerPackOperationMessages = syncMessage.getStickerPackOperations().get();
2027 for (var m : stickerPackOperationMessages) {
2028 if (!m.getPackId().isPresent()) {
2029 continue;
2030 }
2031 var sticker = account.getStickerStore().getSticker(m.getPackId().get());
2032 if (sticker == null) {
2033 if (!m.getPackKey().isPresent()) {
2034 continue;
2035 }
2036 sticker = new Sticker(m.getPackId().get(), m.getPackKey().get());
2037 }
2038 sticker.setInstalled(!m.getType().isPresent()
2039 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL);
2040 account.getStickerStore().updateSticker(sticker);
2041 }
2042 }
2043 if (syncMessage.getFetchType().isPresent()) {
2044 switch (syncMessage.getFetchType().get()) {
2045 case LOCAL_PROFILE:
2046 getRecipientProfile(getSelfAddress(), true);
2047 case STORAGE_MANIFEST:
2048 // TODO
2049 }
2050 }
2051 if (syncMessage.getKeys().isPresent()) {
2052 final var keysMessage = syncMessage.getKeys().get();
2053 if (keysMessage.getStorageService().isPresent()) {
2054 final var storageKey = keysMessage.getStorageService().get();
2055 account.setStorageKey(storageKey);
2056 }
2057 }
2058 if (syncMessage.getConfiguration().isPresent()) {
2059 // TODO
2060 }
2061 }
2062 }
2063 return actions;
2064 }
2065
2066 private void downloadContactAvatar(SignalServiceAttachment avatar, SignalServiceAddress address) {
2067 try {
2068 avatarStore.storeContactAvatar(address, outputStream -> retrieveAttachment(avatar, outputStream));
2069 } catch (IOException e) {
2070 logger.warn("Failed to download avatar for contact {}, ignoring: {}", address, e.getMessage());
2071 }
2072 }
2073
2074 private void downloadGroupAvatar(SignalServiceAttachment avatar, GroupId groupId) {
2075 try {
2076 avatarStore.storeGroupAvatar(groupId, outputStream -> retrieveAttachment(avatar, outputStream));
2077 } catch (IOException e) {
2078 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2079 }
2080 }
2081
2082 private void downloadGroupAvatar(GroupId groupId, GroupSecretParams groupSecretParams, String cdnKey) {
2083 try {
2084 avatarStore.storeGroupAvatar(groupId,
2085 outputStream -> retrieveGroupV2Avatar(groupSecretParams, cdnKey, outputStream));
2086 } catch (IOException e) {
2087 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2088 }
2089 }
2090
2091 private void downloadProfileAvatar(
2092 SignalServiceAddress address, String avatarPath, ProfileKey profileKey
2093 ) {
2094 try {
2095 avatarStore.storeProfileAvatar(address,
2096 outputStream -> retrieveProfileAvatar(avatarPath, profileKey, outputStream));
2097 } catch (Throwable e) {
2098 logger.warn("Failed to download profile avatar, ignoring: {}", e.getMessage());
2099 }
2100 }
2101
2102 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
2103 return attachmentStore.getAttachmentFile(attachmentId);
2104 }
2105
2106 private void downloadAttachment(final SignalServiceAttachment attachment) {
2107 if (!attachment.isPointer()) {
2108 logger.warn("Invalid state, can't store an attachment stream.");
2109 }
2110
2111 var pointer = attachment.asPointer();
2112 if (pointer.getPreview().isPresent()) {
2113 final var preview = pointer.getPreview().get();
2114 try {
2115 attachmentStore.storeAttachmentPreview(pointer.getRemoteId(),
2116 outputStream -> outputStream.write(preview, 0, preview.length));
2117 } catch (IOException e) {
2118 logger.warn("Failed to download attachment preview, ignoring: {}", e.getMessage());
2119 }
2120 }
2121
2122 try {
2123 attachmentStore.storeAttachment(pointer.getRemoteId(),
2124 outputStream -> retrieveAttachmentPointer(pointer, outputStream));
2125 } catch (IOException e) {
2126 logger.warn("Failed to download attachment ({}), ignoring: {}", pointer.getRemoteId(), e.getMessage());
2127 }
2128 }
2129
2130 private void retrieveGroupV2Avatar(
2131 GroupSecretParams groupSecretParams, String cdnKey, OutputStream outputStream
2132 ) throws IOException {
2133 var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
2134
2135 var tmpFile = IOUtils.createTempFile();
2136 try (InputStream input = messageReceiver.retrieveGroupsV2ProfileAvatar(cdnKey,
2137 tmpFile,
2138 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2139 var encryptedData = IOUtils.readFully(input);
2140
2141 var decryptedData = groupOperations.decryptAvatar(encryptedData);
2142 outputStream.write(decryptedData);
2143 } finally {
2144 try {
2145 Files.delete(tmpFile.toPath());
2146 } catch (IOException e) {
2147 logger.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2148 tmpFile,
2149 e.getMessage());
2150 }
2151 }
2152 }
2153
2154 private void retrieveProfileAvatar(
2155 String avatarPath, ProfileKey profileKey, OutputStream outputStream
2156 ) throws IOException {
2157 var tmpFile = IOUtils.createTempFile();
2158 try (var input = messageReceiver.retrieveProfileAvatar(avatarPath,
2159 tmpFile,
2160 profileKey,
2161 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2162 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2163 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
2164 } finally {
2165 try {
2166 Files.delete(tmpFile.toPath());
2167 } catch (IOException e) {
2168 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2169 tmpFile,
2170 e.getMessage());
2171 }
2172 }
2173 }
2174
2175 private void retrieveAttachment(
2176 final SignalServiceAttachment attachment, final OutputStream outputStream
2177 ) throws IOException {
2178 if (attachment.isPointer()) {
2179 var pointer = attachment.asPointer();
2180 retrieveAttachmentPointer(pointer, outputStream);
2181 } else {
2182 var stream = attachment.asStream();
2183 IOUtils.copyStream(stream.getInputStream(), outputStream);
2184 }
2185 }
2186
2187 private void retrieveAttachmentPointer(
2188 SignalServiceAttachmentPointer pointer, OutputStream outputStream
2189 ) throws IOException {
2190 var tmpFile = IOUtils.createTempFile();
2191 try (var input = retrieveAttachmentAsStream(pointer, tmpFile)) {
2192 IOUtils.copyStream(input, outputStream);
2193 } catch (MissingConfigurationException | InvalidMessageException e) {
2194 throw new IOException(e);
2195 } finally {
2196 try {
2197 Files.delete(tmpFile.toPath());
2198 } catch (IOException e) {
2199 logger.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2200 tmpFile,
2201 e.getMessage());
2202 }
2203 }
2204 }
2205
2206 private InputStream retrieveAttachmentAsStream(
2207 SignalServiceAttachmentPointer pointer, File tmpFile
2208 ) throws IOException, InvalidMessageException, MissingConfigurationException {
2209 return messageReceiver.retrieveAttachment(pointer, tmpFile, ServiceConfig.MAX_ATTACHMENT_SIZE);
2210 }
2211
2212 void sendGroups() throws IOException, UntrustedIdentityException {
2213 var groupsFile = IOUtils.createTempFile();
2214
2215 try {
2216 try (OutputStream fos = new FileOutputStream(groupsFile)) {
2217 var out = new DeviceGroupsOutputStream(fos);
2218 for (var record : getGroups()) {
2219 if (record instanceof GroupInfoV1) {
2220 var groupInfo = (GroupInfoV1) record;
2221 out.write(new DeviceGroup(groupInfo.getGroupId().serialize(),
2222 Optional.fromNullable(groupInfo.name),
2223 new ArrayList<>(groupInfo.getMembers()),
2224 createGroupAvatarAttachment(groupInfo.getGroupId()),
2225 groupInfo.isMember(account.getSelfAddress()),
2226 Optional.of(groupInfo.messageExpirationTime),
2227 Optional.fromNullable(groupInfo.color),
2228 groupInfo.blocked,
2229 Optional.fromNullable(groupInfo.inboxPosition),
2230 groupInfo.archived));
2231 }
2232 }
2233 }
2234
2235 if (groupsFile.exists() && groupsFile.length() > 0) {
2236 try (var groupsFileStream = new FileInputStream(groupsFile)) {
2237 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2238 .withStream(groupsFileStream)
2239 .withContentType("application/octet-stream")
2240 .withLength(groupsFile.length())
2241 .build();
2242
2243 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
2244 }
2245 }
2246 } finally {
2247 try {
2248 Files.delete(groupsFile.toPath());
2249 } catch (IOException e) {
2250 logger.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile, e.getMessage());
2251 }
2252 }
2253 }
2254
2255 public void sendContacts() throws IOException, UntrustedIdentityException {
2256 var contactsFile = IOUtils.createTempFile();
2257
2258 try {
2259 try (OutputStream fos = new FileOutputStream(contactsFile)) {
2260 var out = new DeviceContactsOutputStream(fos);
2261 for (var record : account.getContactStore().getContacts()) {
2262 VerifiedMessage verifiedMessage = null;
2263 var currentIdentity = account.getIdentityKeyStore()
2264 .getIdentity(resolveRecipientTrusted(record.getAddress()));
2265 if (currentIdentity != null) {
2266 verifiedMessage = new VerifiedMessage(record.getAddress(),
2267 currentIdentity.getIdentityKey(),
2268 currentIdentity.getTrustLevel().toVerifiedState(),
2269 currentIdentity.getDateAdded().getTime());
2270 }
2271
2272 var profileKey = account.getProfileStore().getProfileKey(record.getAddress());
2273 out.write(new DeviceContact(record.getAddress(),
2274 Optional.fromNullable(record.name),
2275 createContactAvatarAttachment(record.getAddress()),
2276 Optional.fromNullable(record.color),
2277 Optional.fromNullable(verifiedMessage),
2278 Optional.fromNullable(profileKey),
2279 record.blocked,
2280 Optional.of(record.messageExpirationTime),
2281 Optional.fromNullable(record.inboxPosition),
2282 record.archived));
2283 }
2284
2285 if (account.getProfileKey() != null) {
2286 // Send our own profile key as well
2287 out.write(new DeviceContact(account.getSelfAddress(),
2288 Optional.absent(),
2289 Optional.absent(),
2290 Optional.absent(),
2291 Optional.absent(),
2292 Optional.of(account.getProfileKey()),
2293 false,
2294 Optional.absent(),
2295 Optional.absent(),
2296 false));
2297 }
2298 }
2299
2300 if (contactsFile.exists() && contactsFile.length() > 0) {
2301 try (var contactsFileStream = new FileInputStream(contactsFile)) {
2302 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2303 .withStream(contactsFileStream)
2304 .withContentType("application/octet-stream")
2305 .withLength(contactsFile.length())
2306 .build();
2307
2308 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
2309 }
2310 }
2311 } finally {
2312 try {
2313 Files.delete(contactsFile.toPath());
2314 } catch (IOException e) {
2315 logger.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile, e.getMessage());
2316 }
2317 }
2318 }
2319
2320 void sendBlockedList() throws IOException, UntrustedIdentityException {
2321 var addresses = new ArrayList<SignalServiceAddress>();
2322 for (var record : account.getContactStore().getContacts()) {
2323 if (record.blocked) {
2324 addresses.add(record.getAddress());
2325 }
2326 }
2327 var groupIds = new ArrayList<byte[]>();
2328 for (var record : getGroups()) {
2329 if (record.isBlocked()) {
2330 groupIds.add(record.getGroupId().serialize());
2331 }
2332 }
2333 sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
2334 }
2335
2336 private void sendVerifiedMessage(
2337 SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel
2338 ) throws IOException, UntrustedIdentityException {
2339 var verifiedMessage = new VerifiedMessage(destination,
2340 identityKey,
2341 trustLevel.toVerifiedState(),
2342 System.currentTimeMillis());
2343 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
2344 }
2345
2346 public List<ContactInfo> getContacts() {
2347 return account.getContactStore().getContacts();
2348 }
2349
2350 public String getContactOrProfileName(String number) {
2351 final var address = Utils.getSignalServiceAddressFromIdentifier(number);
2352
2353 final var contact = account.getContactStore().getContact(address);
2354 if (contact != null && !Util.isEmpty(contact.name)) {
2355 return contact.name;
2356 }
2357
2358 final var profileEntry = account.getProfileStore().getProfileEntry(address);
2359 if (profileEntry != null && profileEntry.getProfile() != null) {
2360 return profileEntry.getProfile().getDisplayName();
2361 }
2362 return null;
2363 }
2364
2365 public GroupInfo getGroup(GroupId groupId) {
2366 final var group = account.getGroupStore().getGroup(groupId);
2367 if (group instanceof GroupInfoV2 && ((GroupInfoV2) group).getGroup() == null) {
2368 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(((GroupInfoV2) group).getMasterKey());
2369 ((GroupInfoV2) group).setGroup(groupHelper.getDecryptedGroup(groupSecretParams));
2370 account.getGroupStore().updateGroup(group);
2371 }
2372 return group;
2373 }
2374
2375 public List<IdentityInfo> getIdentities() {
2376 return account.getIdentityKeyStore().getIdentities();
2377 }
2378
2379 public List<IdentityInfo> getIdentities(String number) throws InvalidNumberException {
2380 final var identity = account.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number));
2381 return identity == null ? List.of() : List.of(identity);
2382 }
2383
2384 /**
2385 * Trust this the identity with this fingerprint
2386 *
2387 * @param name username of the identity
2388 * @param fingerprint Fingerprint
2389 */
2390 public boolean trustIdentityVerified(String name, byte[] fingerprint) throws InvalidNumberException {
2391 var recipientId = canonicalizeAndResolveRecipient(name);
2392 return trustIdentity(recipientId,
2393 identityKey -> Arrays.equals(identityKey.serialize(), fingerprint),
2394 TrustLevel.TRUSTED_VERIFIED);
2395 }
2396
2397 /**
2398 * Trust this the identity with this safety number
2399 *
2400 * @param name username of the identity
2401 * @param safetyNumber Safety number
2402 */
2403 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) throws InvalidNumberException {
2404 var recipientId = canonicalizeAndResolveRecipient(name);
2405 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
2406 return trustIdentity(recipientId,
2407 identityKey -> safetyNumber.equals(computeSafetyNumber(address, identityKey)),
2408 TrustLevel.TRUSTED_VERIFIED);
2409 }
2410
2411 /**
2412 * Trust all keys of this identity without verification
2413 *
2414 * @param name username of the identity
2415 */
2416 public boolean trustIdentityAllKeys(String name) throws InvalidNumberException {
2417 var recipientId = canonicalizeAndResolveRecipient(name);
2418 return trustIdentity(recipientId, identityKey -> true, TrustLevel.TRUSTED_UNVERIFIED);
2419 }
2420
2421 private boolean trustIdentity(
2422 RecipientId recipientId, Function<IdentityKey, Boolean> verifier, TrustLevel trustLevel
2423 ) {
2424 var identity = account.getIdentityKeyStore().getIdentity(recipientId);
2425 if (identity == null) {
2426 return false;
2427 }
2428
2429 if (!verifier.apply(identity.getIdentityKey())) {
2430 return false;
2431 }
2432
2433 account.getIdentityKeyStore().setIdentityTrustLevel(recipientId, identity.getIdentityKey(), trustLevel);
2434 try {
2435 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
2436 sendVerifiedMessage(address, identity.getIdentityKey(), trustLevel);
2437 } catch (IOException | UntrustedIdentityException e) {
2438 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2439 }
2440
2441 return true;
2442 }
2443
2444 public String computeSafetyNumber(
2445 SignalServiceAddress theirAddress, IdentityKey theirIdentityKey
2446 ) {
2447 return Utils.computeSafetyNumber(ServiceConfig.capabilities.isUuid(),
2448 account.getSelfAddress(),
2449 getIdentityKeyPair().getPublicKey(),
2450 theirAddress,
2451 theirIdentityKey);
2452 }
2453
2454 @Deprecated
2455 public SignalServiceAddress canonicalizeAndResolveSignalServiceAddress(String identifier) throws InvalidNumberException {
2456 var canonicalizedNumber = UuidUtil.isUuid(identifier)
2457 ? identifier
2458 : PhoneNumberFormatter.formatNumber(identifier, account.getUsername());
2459 return resolveSignalServiceAddress(canonicalizedNumber);
2460 }
2461
2462 @Deprecated
2463 public SignalServiceAddress resolveSignalServiceAddress(String identifier) {
2464 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2465
2466 return resolveSignalServiceAddress(address);
2467 }
2468
2469 @Deprecated
2470 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
2471 if (address.matches(account.getSelfAddress())) {
2472 return account.getSelfAddress();
2473 }
2474
2475 return account.getRecipientStore().resolveServiceAddress(address);
2476 }
2477
2478 public SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
2479 return account.getRecipientStore().resolveServiceAddress(recipientId);
2480 }
2481
2482 public RecipientId canonicalizeAndResolveRecipient(String identifier) throws InvalidNumberException {
2483 var canonicalizedNumber = UuidUtil.isUuid(identifier)
2484 ? identifier
2485 : PhoneNumberFormatter.formatNumber(identifier, account.getUsername());
2486
2487 return resolveRecipient(canonicalizedNumber);
2488 }
2489
2490 private RecipientId resolveRecipient(final String identifier) {
2491 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2492
2493 return resolveRecipient(address);
2494 }
2495
2496 public RecipientId resolveRecipient(SignalServiceAddress address) {
2497 return account.getRecipientStore().resolveRecipientUntrusted(address);
2498 }
2499
2500 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
2501 return account.getRecipientStore().resolveRecipient(address);
2502 }
2503
2504 @Override
2505 public void close() throws IOException {
2506 close(true);
2507 }
2508
2509 void close(boolean closeAccount) throws IOException {
2510 executor.shutdown();
2511
2512 if (messagePipe != null) {
2513 messagePipe.shutdown();
2514 messagePipe = null;
2515 }
2516
2517 if (unidentifiedMessagePipe != null) {
2518 unidentifiedMessagePipe.shutdown();
2519 unidentifiedMessagePipe = null;
2520 }
2521
2522 if (closeAccount && account != null) {
2523 account.close();
2524 }
2525 account = null;
2526 }
2527
2528 public interface ReceiveMessageHandler {
2529
2530 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
2531 }
2532 }