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