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