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