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