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