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