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