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