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