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