]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/Manager.java
Don't clear contact store before receiving new sync contacts
[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 DeviceContact c;
1999 while ((c = s.read()) != null) {
2000 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
2001 account.setProfileKey(c.getProfileKey().get());
2002 }
2003 final var address = resolveSignalServiceAddress(c.getAddress());
2004 var contact = account.getContactStore().getContact(address);
2005 if (contact == null) {
2006 contact = new ContactInfo(address);
2007 }
2008 if (c.getName().isPresent()) {
2009 contact.name = c.getName().get();
2010 }
2011 if (c.getColor().isPresent()) {
2012 contact.color = c.getColor().get();
2013 }
2014 if (c.getProfileKey().isPresent()) {
2015 account.getProfileStore().storeProfileKey(address, c.getProfileKey().get());
2016 }
2017 if (c.getVerified().isPresent()) {
2018 final var verifiedMessage = c.getVerified().get();
2019 account.getIdentityKeyStore()
2020 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
2021 verifiedMessage.getIdentityKey(),
2022 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2023 }
2024 if (c.getExpirationTimer().isPresent()) {
2025 contact.messageExpirationTime = c.getExpirationTimer().get();
2026 }
2027 contact.blocked = c.isBlocked();
2028 contact.inboxPosition = c.getInboxPosition().orNull();
2029 contact.archived = c.isArchived();
2030 account.getContactStore().updateContact(contact);
2031
2032 if (c.getAvatar().isPresent()) {
2033 downloadContactAvatar(c.getAvatar().get(), contact.getAddress());
2034 }
2035 }
2036 }
2037 } catch (Exception e) {
2038 logger.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2039 tmpFile,
2040 e.getMessage());
2041 } finally {
2042 if (tmpFile != null) {
2043 try {
2044 Files.delete(tmpFile.toPath());
2045 } catch (IOException e) {
2046 logger.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2047 tmpFile,
2048 e.getMessage());
2049 }
2050 }
2051 }
2052 }
2053 if (syncMessage.getVerified().isPresent()) {
2054 final var verifiedMessage = syncMessage.getVerified().get();
2055 account.getIdentityKeyStore()
2056 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
2057 verifiedMessage.getIdentityKey(),
2058 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2059 }
2060 if (syncMessage.getStickerPackOperations().isPresent()) {
2061 final var stickerPackOperationMessages = syncMessage.getStickerPackOperations().get();
2062 for (var m : stickerPackOperationMessages) {
2063 if (!m.getPackId().isPresent()) {
2064 continue;
2065 }
2066 var sticker = account.getStickerStore().getSticker(m.getPackId().get());
2067 if (sticker == null) {
2068 if (!m.getPackKey().isPresent()) {
2069 continue;
2070 }
2071 sticker = new Sticker(m.getPackId().get(), m.getPackKey().get());
2072 }
2073 sticker.setInstalled(!m.getType().isPresent()
2074 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL);
2075 account.getStickerStore().updateSticker(sticker);
2076 }
2077 }
2078 if (syncMessage.getFetchType().isPresent()) {
2079 switch (syncMessage.getFetchType().get()) {
2080 case LOCAL_PROFILE:
2081 getRecipientProfile(getSelfAddress(), true);
2082 case STORAGE_MANIFEST:
2083 // TODO
2084 }
2085 }
2086 if (syncMessage.getKeys().isPresent()) {
2087 final var keysMessage = syncMessage.getKeys().get();
2088 if (keysMessage.getStorageService().isPresent()) {
2089 final var storageKey = keysMessage.getStorageService().get();
2090 account.setStorageKey(storageKey);
2091 }
2092 }
2093 if (syncMessage.getConfiguration().isPresent()) {
2094 // TODO
2095 }
2096 }
2097 }
2098 return actions;
2099 }
2100
2101 private void downloadContactAvatar(SignalServiceAttachment avatar, SignalServiceAddress address) {
2102 try {
2103 avatarStore.storeContactAvatar(address, outputStream -> retrieveAttachment(avatar, outputStream));
2104 } catch (IOException e) {
2105 logger.warn("Failed to download avatar for contact {}, ignoring: {}", address, e.getMessage());
2106 }
2107 }
2108
2109 private void downloadGroupAvatar(SignalServiceAttachment avatar, GroupId groupId) {
2110 try {
2111 avatarStore.storeGroupAvatar(groupId, outputStream -> retrieveAttachment(avatar, outputStream));
2112 } catch (IOException e) {
2113 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2114 }
2115 }
2116
2117 private void downloadGroupAvatar(GroupId groupId, GroupSecretParams groupSecretParams, String cdnKey) {
2118 try {
2119 avatarStore.storeGroupAvatar(groupId,
2120 outputStream -> retrieveGroupV2Avatar(groupSecretParams, cdnKey, outputStream));
2121 } catch (IOException e) {
2122 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2123 }
2124 }
2125
2126 private void downloadProfileAvatar(
2127 SignalServiceAddress address, String avatarPath, ProfileKey profileKey
2128 ) {
2129 try {
2130 avatarStore.storeProfileAvatar(address,
2131 outputStream -> retrieveProfileAvatar(avatarPath, profileKey, outputStream));
2132 } catch (Throwable e) {
2133 logger.warn("Failed to download profile avatar, ignoring: {}", e.getMessage());
2134 }
2135 }
2136
2137 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
2138 return attachmentStore.getAttachmentFile(attachmentId);
2139 }
2140
2141 private void downloadAttachment(final SignalServiceAttachment attachment) {
2142 if (!attachment.isPointer()) {
2143 logger.warn("Invalid state, can't store an attachment stream.");
2144 }
2145
2146 var pointer = attachment.asPointer();
2147 if (pointer.getPreview().isPresent()) {
2148 final var preview = pointer.getPreview().get();
2149 try {
2150 attachmentStore.storeAttachmentPreview(pointer.getRemoteId(),
2151 outputStream -> outputStream.write(preview, 0, preview.length));
2152 } catch (IOException e) {
2153 logger.warn("Failed to download attachment preview, ignoring: {}", e.getMessage());
2154 }
2155 }
2156
2157 try {
2158 attachmentStore.storeAttachment(pointer.getRemoteId(),
2159 outputStream -> retrieveAttachmentPointer(pointer, outputStream));
2160 } catch (IOException e) {
2161 logger.warn("Failed to download attachment ({}), ignoring: {}", pointer.getRemoteId(), e.getMessage());
2162 }
2163 }
2164
2165 private void retrieveGroupV2Avatar(
2166 GroupSecretParams groupSecretParams, String cdnKey, OutputStream outputStream
2167 ) throws IOException {
2168 var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
2169
2170 var tmpFile = IOUtils.createTempFile();
2171 try (InputStream input = messageReceiver.retrieveGroupsV2ProfileAvatar(cdnKey,
2172 tmpFile,
2173 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2174 var encryptedData = IOUtils.readFully(input);
2175
2176 var decryptedData = groupOperations.decryptAvatar(encryptedData);
2177 outputStream.write(decryptedData);
2178 } finally {
2179 try {
2180 Files.delete(tmpFile.toPath());
2181 } catch (IOException e) {
2182 logger.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2183 tmpFile,
2184 e.getMessage());
2185 }
2186 }
2187 }
2188
2189 private void retrieveProfileAvatar(
2190 String avatarPath, ProfileKey profileKey, OutputStream outputStream
2191 ) throws IOException {
2192 var tmpFile = IOUtils.createTempFile();
2193 try (var input = messageReceiver.retrieveProfileAvatar(avatarPath,
2194 tmpFile,
2195 profileKey,
2196 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2197 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2198 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
2199 } finally {
2200 try {
2201 Files.delete(tmpFile.toPath());
2202 } catch (IOException e) {
2203 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2204 tmpFile,
2205 e.getMessage());
2206 }
2207 }
2208 }
2209
2210 private void retrieveAttachment(
2211 final SignalServiceAttachment attachment, final OutputStream outputStream
2212 ) throws IOException {
2213 if (attachment.isPointer()) {
2214 var pointer = attachment.asPointer();
2215 retrieveAttachmentPointer(pointer, outputStream);
2216 } else {
2217 var stream = attachment.asStream();
2218 IOUtils.copyStream(stream.getInputStream(), outputStream);
2219 }
2220 }
2221
2222 private void retrieveAttachmentPointer(
2223 SignalServiceAttachmentPointer pointer, OutputStream outputStream
2224 ) throws IOException {
2225 var tmpFile = IOUtils.createTempFile();
2226 try (var input = retrieveAttachmentAsStream(pointer, tmpFile)) {
2227 IOUtils.copyStream(input, outputStream);
2228 } catch (MissingConfigurationException | InvalidMessageException e) {
2229 throw new IOException(e);
2230 } finally {
2231 try {
2232 Files.delete(tmpFile.toPath());
2233 } catch (IOException e) {
2234 logger.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2235 tmpFile,
2236 e.getMessage());
2237 }
2238 }
2239 }
2240
2241 private InputStream retrieveAttachmentAsStream(
2242 SignalServiceAttachmentPointer pointer, File tmpFile
2243 ) throws IOException, InvalidMessageException, MissingConfigurationException {
2244 return messageReceiver.retrieveAttachment(pointer, tmpFile, ServiceConfig.MAX_ATTACHMENT_SIZE);
2245 }
2246
2247 void sendGroups() throws IOException, UntrustedIdentityException {
2248 var groupsFile = IOUtils.createTempFile();
2249
2250 try {
2251 try (OutputStream fos = new FileOutputStream(groupsFile)) {
2252 var out = new DeviceGroupsOutputStream(fos);
2253 for (var record : getGroups()) {
2254 if (record instanceof GroupInfoV1) {
2255 var groupInfo = (GroupInfoV1) record;
2256 out.write(new DeviceGroup(groupInfo.getGroupId().serialize(),
2257 Optional.fromNullable(groupInfo.name),
2258 new ArrayList<>(groupInfo.getMembers()),
2259 createGroupAvatarAttachment(groupInfo.getGroupId()),
2260 groupInfo.isMember(account.getSelfAddress()),
2261 Optional.of(groupInfo.messageExpirationTime),
2262 Optional.fromNullable(groupInfo.color),
2263 groupInfo.blocked,
2264 Optional.fromNullable(groupInfo.inboxPosition),
2265 groupInfo.archived));
2266 }
2267 }
2268 }
2269
2270 if (groupsFile.exists() && groupsFile.length() > 0) {
2271 try (var groupsFileStream = new FileInputStream(groupsFile)) {
2272 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2273 .withStream(groupsFileStream)
2274 .withContentType("application/octet-stream")
2275 .withLength(groupsFile.length())
2276 .build();
2277
2278 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
2279 }
2280 }
2281 } finally {
2282 try {
2283 Files.delete(groupsFile.toPath());
2284 } catch (IOException e) {
2285 logger.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile, e.getMessage());
2286 }
2287 }
2288 }
2289
2290 public void sendContacts() throws IOException, UntrustedIdentityException {
2291 var contactsFile = IOUtils.createTempFile();
2292
2293 try {
2294 try (OutputStream fos = new FileOutputStream(contactsFile)) {
2295 var out = new DeviceContactsOutputStream(fos);
2296 for (var record : account.getContactStore().getContacts()) {
2297 VerifiedMessage verifiedMessage = null;
2298 var currentIdentity = account.getIdentityKeyStore()
2299 .getIdentity(resolveRecipientTrusted(record.getAddress()));
2300 if (currentIdentity != null) {
2301 verifiedMessage = new VerifiedMessage(record.getAddress(),
2302 currentIdentity.getIdentityKey(),
2303 currentIdentity.getTrustLevel().toVerifiedState(),
2304 currentIdentity.getDateAdded().getTime());
2305 }
2306
2307 var profileKey = account.getProfileStore().getProfileKey(record.getAddress());
2308 out.write(new DeviceContact(record.getAddress(),
2309 Optional.fromNullable(record.name),
2310 createContactAvatarAttachment(record.getAddress()),
2311 Optional.fromNullable(record.color),
2312 Optional.fromNullable(verifiedMessage),
2313 Optional.fromNullable(profileKey),
2314 record.blocked,
2315 Optional.of(record.messageExpirationTime),
2316 Optional.fromNullable(record.inboxPosition),
2317 record.archived));
2318 }
2319
2320 if (account.getProfileKey() != null) {
2321 // Send our own profile key as well
2322 out.write(new DeviceContact(account.getSelfAddress(),
2323 Optional.absent(),
2324 Optional.absent(),
2325 Optional.absent(),
2326 Optional.absent(),
2327 Optional.of(account.getProfileKey()),
2328 false,
2329 Optional.absent(),
2330 Optional.absent(),
2331 false));
2332 }
2333 }
2334
2335 if (contactsFile.exists() && contactsFile.length() > 0) {
2336 try (var contactsFileStream = new FileInputStream(contactsFile)) {
2337 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2338 .withStream(contactsFileStream)
2339 .withContentType("application/octet-stream")
2340 .withLength(contactsFile.length())
2341 .build();
2342
2343 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
2344 }
2345 }
2346 } finally {
2347 try {
2348 Files.delete(contactsFile.toPath());
2349 } catch (IOException e) {
2350 logger.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile, e.getMessage());
2351 }
2352 }
2353 }
2354
2355 void sendBlockedList() throws IOException, UntrustedIdentityException {
2356 var addresses = new ArrayList<SignalServiceAddress>();
2357 for (var record : account.getContactStore().getContacts()) {
2358 if (record.blocked) {
2359 addresses.add(record.getAddress());
2360 }
2361 }
2362 var groupIds = new ArrayList<byte[]>();
2363 for (var record : getGroups()) {
2364 if (record.isBlocked()) {
2365 groupIds.add(record.getGroupId().serialize());
2366 }
2367 }
2368 sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
2369 }
2370
2371 private void sendVerifiedMessage(
2372 SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel
2373 ) throws IOException, UntrustedIdentityException {
2374 var verifiedMessage = new VerifiedMessage(destination,
2375 identityKey,
2376 trustLevel.toVerifiedState(),
2377 System.currentTimeMillis());
2378 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
2379 }
2380
2381 public List<ContactInfo> getContacts() {
2382 return account.getContactStore().getContacts();
2383 }
2384
2385 public String getContactOrProfileName(String number) {
2386 final var address = Utils.getSignalServiceAddressFromIdentifier(number);
2387
2388 final var contact = account.getContactStore().getContact(address);
2389 if (contact != null && !Util.isEmpty(contact.name)) {
2390 return contact.name;
2391 }
2392
2393 final var profileEntry = account.getProfileStore().getProfileEntry(address);
2394 if (profileEntry != null && profileEntry.getProfile() != null) {
2395 return profileEntry.getProfile().getDisplayName();
2396 }
2397 return null;
2398 }
2399
2400 public GroupInfo getGroup(GroupId groupId) {
2401 final var group = account.getGroupStore().getGroup(groupId);
2402 if (group instanceof GroupInfoV2 && ((GroupInfoV2) group).getGroup() == null) {
2403 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(((GroupInfoV2) group).getMasterKey());
2404 ((GroupInfoV2) group).setGroup(groupHelper.getDecryptedGroup(groupSecretParams));
2405 account.getGroupStore().updateGroup(group);
2406 }
2407 return group;
2408 }
2409
2410 public List<IdentityInfo> getIdentities() {
2411 return account.getIdentityKeyStore().getIdentities();
2412 }
2413
2414 public List<IdentityInfo> getIdentities(String number) throws InvalidNumberException {
2415 final var identity = account.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number));
2416 return identity == null ? List.of() : List.of(identity);
2417 }
2418
2419 /**
2420 * Trust this the identity with this fingerprint
2421 *
2422 * @param name username of the identity
2423 * @param fingerprint Fingerprint
2424 */
2425 public boolean trustIdentityVerified(String name, byte[] fingerprint) throws InvalidNumberException {
2426 var recipientId = canonicalizeAndResolveRecipient(name);
2427 return trustIdentity(recipientId,
2428 identityKey -> Arrays.equals(identityKey.serialize(), fingerprint),
2429 TrustLevel.TRUSTED_VERIFIED);
2430 }
2431
2432 /**
2433 * Trust this the identity with this safety number
2434 *
2435 * @param name username of the identity
2436 * @param safetyNumber Safety number
2437 */
2438 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) throws InvalidNumberException {
2439 var recipientId = canonicalizeAndResolveRecipient(name);
2440 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
2441 return trustIdentity(recipientId,
2442 identityKey -> safetyNumber.equals(computeSafetyNumber(address, identityKey)),
2443 TrustLevel.TRUSTED_VERIFIED);
2444 }
2445
2446 /**
2447 * Trust all keys of this identity without verification
2448 *
2449 * @param name username of the identity
2450 */
2451 public boolean trustIdentityAllKeys(String name) throws InvalidNumberException {
2452 var recipientId = canonicalizeAndResolveRecipient(name);
2453 return trustIdentity(recipientId, identityKey -> true, TrustLevel.TRUSTED_UNVERIFIED);
2454 }
2455
2456 private boolean trustIdentity(
2457 RecipientId recipientId, Function<IdentityKey, Boolean> verifier, TrustLevel trustLevel
2458 ) {
2459 var identity = account.getIdentityKeyStore().getIdentity(recipientId);
2460 if (identity == null) {
2461 return false;
2462 }
2463
2464 if (!verifier.apply(identity.getIdentityKey())) {
2465 return false;
2466 }
2467
2468 account.getIdentityKeyStore().setIdentityTrustLevel(recipientId, identity.getIdentityKey(), trustLevel);
2469 try {
2470 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
2471 sendVerifiedMessage(address, identity.getIdentityKey(), trustLevel);
2472 } catch (IOException | UntrustedIdentityException e) {
2473 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2474 }
2475
2476 return true;
2477 }
2478
2479 public String computeSafetyNumber(
2480 SignalServiceAddress theirAddress, IdentityKey theirIdentityKey
2481 ) {
2482 return Utils.computeSafetyNumber(ServiceConfig.capabilities.isUuid(),
2483 account.getSelfAddress(),
2484 getIdentityKeyPair().getPublicKey(),
2485 theirAddress,
2486 theirIdentityKey);
2487 }
2488
2489 @Deprecated
2490 public SignalServiceAddress canonicalizeAndResolveSignalServiceAddress(String identifier) throws InvalidNumberException {
2491 var canonicalizedNumber = UuidUtil.isUuid(identifier)
2492 ? identifier
2493 : PhoneNumberFormatter.formatNumber(identifier, account.getUsername());
2494 return resolveSignalServiceAddress(canonicalizedNumber);
2495 }
2496
2497 @Deprecated
2498 public SignalServiceAddress resolveSignalServiceAddress(String identifier) {
2499 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2500
2501 return resolveSignalServiceAddress(address);
2502 }
2503
2504 @Deprecated
2505 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
2506 if (address.matches(account.getSelfAddress())) {
2507 return account.getSelfAddress();
2508 }
2509
2510 return account.getRecipientStore().resolveServiceAddress(address);
2511 }
2512
2513 public SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
2514 return account.getRecipientStore().resolveServiceAddress(recipientId);
2515 }
2516
2517 public RecipientId canonicalizeAndResolveRecipient(String identifier) throws InvalidNumberException {
2518 var canonicalizedNumber = UuidUtil.isUuid(identifier)
2519 ? identifier
2520 : PhoneNumberFormatter.formatNumber(identifier, account.getUsername());
2521
2522 return resolveRecipient(canonicalizedNumber);
2523 }
2524
2525 private RecipientId resolveRecipient(final String identifier) {
2526 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2527
2528 return resolveRecipient(address);
2529 }
2530
2531 public RecipientId resolveRecipient(SignalServiceAddress address) {
2532 return account.getRecipientStore().resolveRecipientUntrusted(address);
2533 }
2534
2535 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
2536 return account.getRecipientStore().resolveRecipient(address);
2537 }
2538
2539 @Override
2540 public void close() throws IOException {
2541 close(true);
2542 }
2543
2544 void close(boolean closeAccount) throws IOException {
2545 executor.shutdown();
2546
2547 if (messagePipe != null) {
2548 messagePipe.shutdown();
2549 messagePipe = null;
2550 }
2551
2552 if (unidentifiedMessagePipe != null) {
2553 unidentifiedMessagePipe.shutdown();
2554 unidentifiedMessagePipe = null;
2555 }
2556
2557 if (closeAccount && account != null) {
2558 account.close();
2559 }
2560 account = null;
2561 }
2562
2563 public interface ReceiveMessageHandler {
2564
2565 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
2566 }
2567 }