]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/Manager.java
Refactor sessions store
[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.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.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>> sendRemoteDeleteMessage(
996 long targetSentTimestamp, List<String> recipients
997 ) throws IOException, InvalidNumberException {
998 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
999 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
1000 return sendMessage(messageBuilder, getSignalServiceAddresses(recipients));
1001 }
1002
1003 public Pair<Long, List<SendMessageResult>> sendGroupRemoteDeleteMessage(
1004 long targetSentTimestamp, GroupId groupId
1005 ) throws IOException, NotAGroupMemberException, GroupNotFoundException {
1006 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
1007 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
1008 return sendGroupMessage(messageBuilder, groupId);
1009 }
1010
1011 public Pair<Long, List<SendMessageResult>> sendMessageReaction(
1012 String emoji, boolean remove, String targetAuthor, long targetSentTimestamp, List<String> recipients
1013 ) throws IOException, InvalidNumberException {
1014 var reaction = new SignalServiceDataMessage.Reaction(emoji,
1015 remove,
1016 canonicalizeAndResolveSignalServiceAddress(targetAuthor),
1017 targetSentTimestamp);
1018 final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
1019 return sendMessage(messageBuilder, getSignalServiceAddresses(recipients));
1020 }
1021
1022 public Pair<Long, List<SendMessageResult>> sendEndSessionMessage(List<String> recipients) throws IOException, InvalidNumberException {
1023 var messageBuilder = SignalServiceDataMessage.newBuilder().asEndSessionMessage();
1024
1025 final var signalServiceAddresses = getSignalServiceAddresses(recipients);
1026 try {
1027 return sendMessage(messageBuilder, signalServiceAddresses);
1028 } catch (Exception e) {
1029 for (var address : signalServiceAddresses) {
1030 handleEndSession(address);
1031 }
1032 account.save();
1033 throw e;
1034 }
1035 }
1036
1037 public String getContactName(String number) throws InvalidNumberException {
1038 var contact = account.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number));
1039 if (contact == null) {
1040 return "";
1041 } else {
1042 return contact.name;
1043 }
1044 }
1045
1046 public void setContactName(String number, String name) throws InvalidNumberException {
1047 final var address = canonicalizeAndResolveSignalServiceAddress(number);
1048 var contact = account.getContactStore().getContact(address);
1049 if (contact == null) {
1050 contact = new ContactInfo(address);
1051 }
1052 contact.name = name;
1053 account.getContactStore().updateContact(contact);
1054 account.save();
1055 }
1056
1057 public void setContactBlocked(String number, boolean blocked) throws InvalidNumberException {
1058 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number), blocked);
1059 }
1060
1061 private void setContactBlocked(SignalServiceAddress address, boolean blocked) {
1062 var contact = account.getContactStore().getContact(address);
1063 if (contact == null) {
1064 contact = new ContactInfo(address);
1065 }
1066 contact.blocked = blocked;
1067 account.getContactStore().updateContact(contact);
1068 account.save();
1069 }
1070
1071 public void setGroupBlocked(final GroupId groupId, final boolean blocked) throws GroupNotFoundException {
1072 var group = getGroup(groupId);
1073 if (group == null) {
1074 throw new GroupNotFoundException(groupId);
1075 }
1076
1077 group.setBlocked(blocked);
1078 account.getGroupStore().updateGroup(group);
1079 account.save();
1080 }
1081
1082 /**
1083 * Change the expiration timer for a contact
1084 */
1085 public void setExpirationTimer(SignalServiceAddress address, int messageExpirationTimer) throws IOException {
1086 var contact = account.getContactStore().getContact(address);
1087 contact.messageExpirationTime = messageExpirationTimer;
1088 account.getContactStore().updateContact(contact);
1089 sendExpirationTimerUpdate(address);
1090 account.save();
1091 }
1092
1093 private void sendExpirationTimerUpdate(SignalServiceAddress address) throws IOException {
1094 final var messageBuilder = SignalServiceDataMessage.newBuilder().asExpirationUpdate();
1095 sendMessage(messageBuilder, List.of(address));
1096 }
1097
1098 /**
1099 * Change the expiration timer for a contact
1100 */
1101 public void setExpirationTimer(
1102 String number, int messageExpirationTimer
1103 ) throws IOException, InvalidNumberException {
1104 var address = canonicalizeAndResolveSignalServiceAddress(number);
1105 setExpirationTimer(address, messageExpirationTimer);
1106 }
1107
1108 /**
1109 * Change the expiration timer for a group
1110 */
1111 public void setExpirationTimer(GroupId groupId, int messageExpirationTimer) {
1112 var g = getGroup(groupId);
1113 if (g instanceof GroupInfoV1) {
1114 var groupInfoV1 = (GroupInfoV1) g;
1115 groupInfoV1.messageExpirationTime = messageExpirationTimer;
1116 account.getGroupStore().updateGroup(groupInfoV1);
1117 } else {
1118 throw new RuntimeException("TODO Not implemented!");
1119 }
1120 }
1121
1122 /**
1123 * Upload the sticker pack from path.
1124 *
1125 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1126 * @return if successful, returns the URL to install the sticker pack in the signal app
1127 */
1128 public String uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
1129 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
1130
1131 var messageSender = createMessageSender();
1132
1133 var packKey = KeyUtils.createStickerUploadKey();
1134 var packId = messageSender.uploadStickerManifest(manifest, packKey);
1135
1136 var sticker = new Sticker(Hex.fromStringCondensed(packId), packKey);
1137 account.getStickerStore().updateSticker(sticker);
1138 account.save();
1139
1140 try {
1141 return new URI("https",
1142 "signal.art",
1143 "/addstickers/",
1144 "pack_id=" + URLEncoder.encode(packId, StandardCharsets.UTF_8) + "&pack_key=" + URLEncoder.encode(
1145 Hex.toStringCondensed(packKey),
1146 StandardCharsets.UTF_8)).toString();
1147 } catch (URISyntaxException e) {
1148 throw new AssertionError(e);
1149 }
1150 }
1151
1152 void requestSyncGroups() throws IOException {
1153 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1154 .setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS)
1155 .build();
1156 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1157 try {
1158 sendSyncMessage(message);
1159 } catch (UntrustedIdentityException e) {
1160 throw new AssertionError(e);
1161 }
1162 }
1163
1164 void requestSyncContacts() throws IOException {
1165 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1166 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS)
1167 .build();
1168 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1169 try {
1170 sendSyncMessage(message);
1171 } catch (UntrustedIdentityException e) {
1172 throw new AssertionError(e);
1173 }
1174 }
1175
1176 void requestSyncBlocked() throws IOException {
1177 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1178 .setType(SignalServiceProtos.SyncMessage.Request.Type.BLOCKED)
1179 .build();
1180 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1181 try {
1182 sendSyncMessage(message);
1183 } catch (UntrustedIdentityException e) {
1184 throw new AssertionError(e);
1185 }
1186 }
1187
1188 void requestSyncConfiguration() throws IOException {
1189 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1190 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONFIGURATION)
1191 .build();
1192 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1193 try {
1194 sendSyncMessage(message);
1195 } catch (UntrustedIdentityException e) {
1196 throw new AssertionError(e);
1197 }
1198 }
1199
1200 void requestSyncKeys() throws IOException {
1201 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1202 .setType(SignalServiceProtos.SyncMessage.Request.Type.KEYS)
1203 .build();
1204 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1205 try {
1206 sendSyncMessage(message);
1207 } catch (UntrustedIdentityException e) {
1208 throw new AssertionError(e);
1209 }
1210 }
1211
1212 private byte[] getSenderCertificate() {
1213 // TODO support UUID capable sender certificates
1214 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1215 byte[] certificate;
1216 try {
1217 certificate = accountManager.getSenderCertificate();
1218 } catch (IOException e) {
1219 logger.warn("Failed to get sender certificate, ignoring: {}", e.getMessage());
1220 return null;
1221 }
1222 // TODO cache for a day
1223 return certificate;
1224 }
1225
1226 private void sendSyncMessage(SignalServiceSyncMessage message) throws IOException, UntrustedIdentityException {
1227 var messageSender = createMessageSender();
1228 try {
1229 messageSender.sendMessage(message, unidentifiedAccessHelper.getAccessForSync());
1230 } catch (UntrustedIdentityException e) {
1231 if (e.getIdentityKey() != null) {
1232 account.getSignalProtocolStore()
1233 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1234 e.getIdentityKey(),
1235 TrustLevel.UNTRUSTED);
1236 }
1237 throw e;
1238 }
1239 }
1240
1241 private Collection<SignalServiceAddress> getSignalServiceAddresses(Collection<String> numbers) throws InvalidNumberException {
1242 final var signalServiceAddresses = new HashSet<SignalServiceAddress>(numbers.size());
1243 final var addressesMissingUuid = new HashSet<SignalServiceAddress>();
1244
1245 for (var number : numbers) {
1246 final var resolvedAddress = canonicalizeAndResolveSignalServiceAddress(number);
1247 if (resolvedAddress.getUuid().isPresent()) {
1248 signalServiceAddresses.add(resolvedAddress);
1249 } else {
1250 addressesMissingUuid.add(resolvedAddress);
1251 }
1252 }
1253
1254 final var numbersMissingUuid = addressesMissingUuid.stream()
1255 .map(a -> a.getNumber().get())
1256 .collect(Collectors.toSet());
1257 Map<String, UUID> registeredUsers;
1258 try {
1259 registeredUsers = getRegisteredUsers(numbersMissingUuid);
1260 } catch (IOException e) {
1261 logger.warn("Failed to resolve uuids from server, ignoring: {}", e.getMessage());
1262 registeredUsers = Map.of();
1263 }
1264
1265 for (var address : addressesMissingUuid) {
1266 final var number = address.getNumber().get();
1267 if (registeredUsers.containsKey(number)) {
1268 final var newAddress = resolveSignalServiceAddress(new SignalServiceAddress(registeredUsers.get(number),
1269 number));
1270 signalServiceAddresses.add(newAddress);
1271 } else {
1272 signalServiceAddresses.add(address);
1273 }
1274 }
1275
1276 return signalServiceAddresses;
1277 }
1278
1279 private Map<String, UUID> getRegisteredUsers(final Set<String> numbersMissingUuid) throws IOException {
1280 try {
1281 return accountManager.getRegisteredUsers(ServiceConfig.getIasKeyStore(),
1282 numbersMissingUuid,
1283 serviceEnvironmentConfig.getCdsMrenclave());
1284 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
1285 throw new IOException(e);
1286 }
1287 }
1288
1289 private Pair<Long, List<SendMessageResult>> sendMessage(
1290 SignalServiceDataMessage.Builder messageBuilder, Collection<SignalServiceAddress> recipients
1291 ) throws IOException {
1292 recipients = recipients.stream().map(this::resolveSignalServiceAddress).collect(Collectors.toSet());
1293 final var timestamp = System.currentTimeMillis();
1294 messageBuilder.withTimestamp(timestamp);
1295 getOrCreateMessagePipe();
1296 getOrCreateUnidentifiedMessagePipe();
1297 SignalServiceDataMessage message = null;
1298 try {
1299 message = messageBuilder.build();
1300 if (message.getGroupContext().isPresent()) {
1301 try {
1302 var messageSender = createMessageSender();
1303 final var isRecipientUpdate = false;
1304 var result = messageSender.sendMessage(new ArrayList<>(recipients),
1305 unidentifiedAccessHelper.getAccessFor(recipients),
1306 isRecipientUpdate,
1307 message);
1308 for (var r : result) {
1309 if (r.getIdentityFailure() != null) {
1310 account.getSignalProtocolStore()
1311 .saveIdentity(r.getAddress(),
1312 r.getIdentityFailure().getIdentityKey(),
1313 TrustLevel.UNTRUSTED);
1314 }
1315 }
1316 return new Pair<>(timestamp, result);
1317 } catch (UntrustedIdentityException e) {
1318 if (e.getIdentityKey() != null) {
1319 account.getSignalProtocolStore()
1320 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1321 e.getIdentityKey(),
1322 TrustLevel.UNTRUSTED);
1323 }
1324 return new Pair<>(timestamp, List.of());
1325 }
1326 } else {
1327 // Send to all individually, so sync messages are sent correctly
1328 messageBuilder.withProfileKey(account.getProfileKey().serialize());
1329 var results = new ArrayList<SendMessageResult>(recipients.size());
1330 for (var address : recipients) {
1331 final var contact = account.getContactStore().getContact(address);
1332 final var expirationTime = contact != null ? contact.messageExpirationTime : 0;
1333 messageBuilder.withExpiration(expirationTime);
1334 message = messageBuilder.build();
1335 results.add(sendMessage(address, message));
1336 }
1337 return new Pair<>(timestamp, results);
1338 }
1339 } finally {
1340 if (message != null && message.isEndSession()) {
1341 for (var recipient : recipients) {
1342 handleEndSession(recipient);
1343 }
1344 }
1345 account.save();
1346 }
1347 }
1348
1349 private Pair<Long, SendMessageResult> sendSelfMessage(
1350 SignalServiceDataMessage.Builder messageBuilder
1351 ) throws IOException {
1352 final var timestamp = System.currentTimeMillis();
1353 messageBuilder.withTimestamp(timestamp);
1354 getOrCreateMessagePipe();
1355 getOrCreateUnidentifiedMessagePipe();
1356 try {
1357 final var address = getSelfAddress();
1358
1359 final var contact = account.getContactStore().getContact(address);
1360 final var expirationTime = contact != null ? contact.messageExpirationTime : 0;
1361 messageBuilder.withExpiration(expirationTime);
1362
1363 var message = messageBuilder.build();
1364 final var result = sendSelfMessage(message);
1365 return new Pair<>(timestamp, result);
1366 } finally {
1367 account.save();
1368 }
1369 }
1370
1371 private SendMessageResult sendSelfMessage(SignalServiceDataMessage message) throws IOException {
1372 var messageSender = createMessageSender();
1373
1374 var recipient = account.getSelfAddress();
1375
1376 final var unidentifiedAccess = unidentifiedAccessHelper.getAccessFor(recipient);
1377 var transcript = new SentTranscriptMessage(Optional.of(recipient),
1378 message.getTimestamp(),
1379 message,
1380 message.getExpiresInSeconds(),
1381 Map.of(recipient, unidentifiedAccess.isPresent()),
1382 false);
1383 var syncMessage = SignalServiceSyncMessage.forSentTranscript(transcript);
1384
1385 try {
1386 var startTime = System.currentTimeMillis();
1387 messageSender.sendMessage(syncMessage, unidentifiedAccess);
1388 return SendMessageResult.success(recipient,
1389 unidentifiedAccess.isPresent(),
1390 false,
1391 System.currentTimeMillis() - startTime);
1392 } catch (UntrustedIdentityException e) {
1393 if (e.getIdentityKey() != null) {
1394 account.getSignalProtocolStore()
1395 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1396 e.getIdentityKey(),
1397 TrustLevel.UNTRUSTED);
1398 }
1399 return SendMessageResult.identityFailure(recipient, e.getIdentityKey());
1400 }
1401 }
1402
1403 private SendMessageResult sendMessage(
1404 SignalServiceAddress address, SignalServiceDataMessage message
1405 ) throws IOException {
1406 var messageSender = createMessageSender();
1407
1408 try {
1409 return messageSender.sendMessage(address, unidentifiedAccessHelper.getAccessFor(address), message);
1410 } catch (UntrustedIdentityException e) {
1411 if (e.getIdentityKey() != null) {
1412 account.getSignalProtocolStore()
1413 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1414 e.getIdentityKey(),
1415 TrustLevel.UNTRUSTED);
1416 }
1417 return SendMessageResult.identityFailure(address, e.getIdentityKey());
1418 }
1419 }
1420
1421 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, SelfSendException, UnsupportedDataMessageException, org.whispersystems.libsignal.UntrustedIdentityException {
1422 var cipher = new SignalServiceCipher(account.getSelfAddress(),
1423 account.getSignalProtocolStore(),
1424 certificateValidator);
1425 try {
1426 return cipher.decrypt(envelope);
1427 } catch (ProtocolUntrustedIdentityException e) {
1428 if (e.getCause() instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
1429 var identityException = (org.whispersystems.libsignal.UntrustedIdentityException) e.getCause();
1430 final var untrustedIdentity = identityException.getUntrustedIdentity();
1431 if (untrustedIdentity != null) {
1432 account.getSignalProtocolStore()
1433 .saveIdentity(resolveSignalServiceAddress(identityException.getName()),
1434 untrustedIdentity,
1435 TrustLevel.UNTRUSTED);
1436 }
1437 throw identityException;
1438 }
1439 throw new AssertionError(e);
1440 }
1441 }
1442
1443 private void handleEndSession(SignalServiceAddress source) {
1444 account.getSessionStore().deleteAllSessions(source.getIdentifier());
1445 }
1446
1447 private List<HandleAction> handleSignalServiceDataMessage(
1448 SignalServiceDataMessage message,
1449 boolean isSync,
1450 SignalServiceAddress source,
1451 SignalServiceAddress destination,
1452 boolean ignoreAttachments
1453 ) {
1454 var actions = new ArrayList<HandleAction>();
1455 if (message.getGroupContext().isPresent()) {
1456 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1457 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1458 var groupId = GroupId.v1(groupInfo.getGroupId());
1459 var group = getGroup(groupId);
1460 if (group == null || group instanceof GroupInfoV1) {
1461 var groupV1 = (GroupInfoV1) group;
1462 switch (groupInfo.getType()) {
1463 case UPDATE: {
1464 if (groupV1 == null) {
1465 groupV1 = new GroupInfoV1(groupId);
1466 }
1467
1468 if (groupInfo.getAvatar().isPresent()) {
1469 var avatar = groupInfo.getAvatar().get();
1470 downloadGroupAvatar(avatar, groupV1.getGroupId());
1471 }
1472
1473 if (groupInfo.getName().isPresent()) {
1474 groupV1.name = groupInfo.getName().get();
1475 }
1476
1477 if (groupInfo.getMembers().isPresent()) {
1478 groupV1.addMembers(groupInfo.getMembers()
1479 .get()
1480 .stream()
1481 .map(this::resolveSignalServiceAddress)
1482 .collect(Collectors.toSet()));
1483 }
1484
1485 account.getGroupStore().updateGroup(groupV1);
1486 break;
1487 }
1488 case DELIVER:
1489 if (groupV1 == null && !isSync) {
1490 actions.add(new SendGroupInfoRequestAction(source, groupId));
1491 }
1492 break;
1493 case QUIT: {
1494 if (groupV1 != null) {
1495 groupV1.removeMember(source);
1496 account.getGroupStore().updateGroup(groupV1);
1497 }
1498 break;
1499 }
1500 case REQUEST_INFO:
1501 if (groupV1 != null && !isSync) {
1502 actions.add(new SendGroupInfoAction(source, groupV1.getGroupId()));
1503 }
1504 break;
1505 }
1506 } else {
1507 // Received a group v1 message for a v2 group
1508 }
1509 }
1510 if (message.getGroupContext().get().getGroupV2().isPresent()) {
1511 final var groupContext = message.getGroupContext().get().getGroupV2().get();
1512 final var groupMasterKey = groupContext.getMasterKey();
1513
1514 getOrMigrateGroup(groupMasterKey,
1515 groupContext.getRevision(),
1516 groupContext.hasSignedGroupChange() ? groupContext.getSignedGroupChange() : null);
1517 }
1518 }
1519
1520 final var conversationPartnerAddress = isSync ? destination : source;
1521 if (conversationPartnerAddress != null && message.isEndSession()) {
1522 handleEndSession(conversationPartnerAddress);
1523 }
1524 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
1525 if (message.getGroupContext().isPresent()) {
1526 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1527 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1528 var group = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(groupInfo.getGroupId()));
1529 if (group != null) {
1530 if (group.messageExpirationTime != message.getExpiresInSeconds()) {
1531 group.messageExpirationTime = message.getExpiresInSeconds();
1532 account.getGroupStore().updateGroup(group);
1533 }
1534 }
1535 } else if (message.getGroupContext().get().getGroupV2().isPresent()) {
1536 // disappearing message timer already stored in the DecryptedGroup
1537 }
1538 } else if (conversationPartnerAddress != null) {
1539 var contact = account.getContactStore().getContact(conversationPartnerAddress);
1540 if (contact == null) {
1541 contact = new ContactInfo(conversationPartnerAddress);
1542 }
1543 if (contact.messageExpirationTime != message.getExpiresInSeconds()) {
1544 contact.messageExpirationTime = message.getExpiresInSeconds();
1545 account.getContactStore().updateContact(contact);
1546 }
1547 }
1548 }
1549 if (!ignoreAttachments) {
1550 if (message.getAttachments().isPresent()) {
1551 for (var attachment : message.getAttachments().get()) {
1552 downloadAttachment(attachment);
1553 }
1554 }
1555 if (message.getSharedContacts().isPresent()) {
1556 for (var contact : message.getSharedContacts().get()) {
1557 if (contact.getAvatar().isPresent()) {
1558 downloadAttachment(contact.getAvatar().get().getAttachment());
1559 }
1560 }
1561 }
1562 }
1563 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
1564 final ProfileKey profileKey;
1565 try {
1566 profileKey = new ProfileKey(message.getProfileKey().get());
1567 } catch (InvalidInputException e) {
1568 throw new AssertionError(e);
1569 }
1570 if (source.matches(account.getSelfAddress())) {
1571 this.account.setProfileKey(profileKey);
1572 }
1573 this.account.getProfileStore().storeProfileKey(source, profileKey);
1574 }
1575 if (message.getPreviews().isPresent()) {
1576 final var previews = message.getPreviews().get();
1577 for (var preview : previews) {
1578 if (preview.getImage().isPresent()) {
1579 downloadAttachment(preview.getImage().get());
1580 }
1581 }
1582 }
1583 if (message.getQuote().isPresent()) {
1584 final var quote = message.getQuote().get();
1585
1586 for (var quotedAttachment : quote.getAttachments()) {
1587 final var thumbnail = quotedAttachment.getThumbnail();
1588 if (thumbnail != null) {
1589 downloadAttachment(thumbnail);
1590 }
1591 }
1592 }
1593 if (message.getSticker().isPresent()) {
1594 final var messageSticker = message.getSticker().get();
1595 var sticker = account.getStickerStore().getSticker(messageSticker.getPackId());
1596 if (sticker == null) {
1597 sticker = new Sticker(messageSticker.getPackId(), messageSticker.getPackKey());
1598 account.getStickerStore().updateSticker(sticker);
1599 }
1600 }
1601 return actions;
1602 }
1603
1604 private GroupInfoV2 getOrMigrateGroup(
1605 final GroupMasterKey groupMasterKey, final int revision, final byte[] signedGroupChange
1606 ) {
1607 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
1608
1609 var groupId = GroupUtils.getGroupIdV2(groupSecretParams);
1610 var groupInfo = getGroup(groupId);
1611 final GroupInfoV2 groupInfoV2;
1612 if (groupInfo instanceof GroupInfoV1) {
1613 // Received a v2 group message for a v1 group, we need to locally migrate the group
1614 account.getGroupStore().deleteGroup(groupInfo.getGroupId());
1615 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1616 logger.info("Locally migrated group {} to group v2, id: {}",
1617 groupInfo.getGroupId().toBase64(),
1618 groupInfoV2.getGroupId().toBase64());
1619 } else if (groupInfo instanceof GroupInfoV2) {
1620 groupInfoV2 = (GroupInfoV2) groupInfo;
1621 } else {
1622 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1623 }
1624
1625 if (groupInfoV2.getGroup() == null || groupInfoV2.getGroup().getRevision() < revision) {
1626 DecryptedGroup group = null;
1627 if (signedGroupChange != null
1628 && groupInfoV2.getGroup() != null
1629 && groupInfoV2.getGroup().getRevision() + 1 == revision) {
1630 group = groupHelper.getUpdatedDecryptedGroup(groupInfoV2.getGroup(), signedGroupChange, groupMasterKey);
1631 }
1632 if (group == null) {
1633 group = groupHelper.getDecryptedGroup(groupSecretParams);
1634 }
1635 if (group != null) {
1636 storeProfileKeysFromMembers(group);
1637 final var avatar = group.getAvatar();
1638 if (avatar != null && !avatar.isEmpty()) {
1639 downloadGroupAvatar(groupId, groupSecretParams, avatar);
1640 }
1641 }
1642 groupInfoV2.setGroup(group);
1643 account.getGroupStore().updateGroup(groupInfoV2);
1644 }
1645
1646 return groupInfoV2;
1647 }
1648
1649 private void storeProfileKeysFromMembers(final DecryptedGroup group) {
1650 for (var member : group.getMembersList()) {
1651 final var address = resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil.parseOrThrow(member.getUuid()
1652 .toByteArray()), null));
1653 try {
1654 account.getProfileStore()
1655 .storeProfileKey(address, new ProfileKey(member.getProfileKey().toByteArray()));
1656 } catch (InvalidInputException ignored) {
1657 }
1658 }
1659 }
1660
1661 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1662 for (var cachedMessage : account.getMessageCache().getCachedMessages()) {
1663 retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
1664 }
1665 }
1666
1667 private void retryFailedReceivedMessage(
1668 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
1669 ) {
1670 var envelope = cachedMessage.loadEnvelope();
1671 if (envelope == null) {
1672 return;
1673 }
1674 SignalServiceContent content = null;
1675 if (!envelope.isReceipt()) {
1676 try {
1677 content = decryptMessage(envelope);
1678 } catch (org.whispersystems.libsignal.UntrustedIdentityException e) {
1679 return;
1680 } catch (Exception er) {
1681 // All other errors are not recoverable, so delete the cached message
1682 cachedMessage.delete();
1683 return;
1684 }
1685 var actions = handleMessage(envelope, content, ignoreAttachments);
1686 for (var action : actions) {
1687 try {
1688 action.execute(this);
1689 } catch (Throwable e) {
1690 logger.warn("Message action failed.", e);
1691 }
1692 }
1693 }
1694 account.save();
1695 handler.handleMessage(envelope, content, null);
1696 cachedMessage.delete();
1697 }
1698
1699 public void receiveMessages(
1700 long timeout,
1701 TimeUnit unit,
1702 boolean returnOnTimeout,
1703 boolean ignoreAttachments,
1704 ReceiveMessageHandler handler
1705 ) throws IOException {
1706 retryFailedReceivedMessages(handler, ignoreAttachments);
1707
1708 Set<HandleAction> queuedActions = null;
1709
1710 final var messagePipe = getOrCreateMessagePipe();
1711
1712 var hasCaughtUpWithOldMessages = false;
1713
1714 while (true) {
1715 SignalServiceEnvelope envelope;
1716 SignalServiceContent content = null;
1717 Exception exception = null;
1718 final CachedMessage[] cachedMessage = {null};
1719 try {
1720 var result = messagePipe.readOrEmpty(timeout, unit, envelope1 -> {
1721 // store message on disk, before acknowledging receipt to the server
1722 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1);
1723 });
1724 if (result.isPresent()) {
1725 envelope = result.get();
1726 } else {
1727 // Received indicator that server queue is empty
1728 hasCaughtUpWithOldMessages = true;
1729
1730 if (queuedActions != null) {
1731 for (var action : queuedActions) {
1732 try {
1733 action.execute(this);
1734 } catch (Throwable e) {
1735 logger.warn("Message action failed.", e);
1736 }
1737 }
1738 account.save();
1739 queuedActions.clear();
1740 queuedActions = null;
1741 }
1742
1743 // Continue to wait another timeout for new messages
1744 continue;
1745 }
1746 } catch (TimeoutException e) {
1747 if (returnOnTimeout) return;
1748 continue;
1749 }
1750
1751 if (envelope.hasSource()) {
1752 // Store uuid if we don't have it already
1753 var source = envelope.getSourceAddress();
1754 resolveSignalServiceAddress(source);
1755 }
1756 if (!envelope.isReceipt()) {
1757 try {
1758 content = decryptMessage(envelope);
1759 } catch (Exception e) {
1760 exception = e;
1761 }
1762 var actions = handleMessage(envelope, content, ignoreAttachments);
1763 if (hasCaughtUpWithOldMessages) {
1764 for (var action : actions) {
1765 try {
1766 action.execute(this);
1767 } catch (Throwable e) {
1768 logger.warn("Message action failed.", e);
1769 }
1770 }
1771 } else {
1772 if (queuedActions == null) {
1773 queuedActions = new HashSet<>();
1774 }
1775 queuedActions.addAll(actions);
1776 }
1777 }
1778 account.save();
1779 if (isMessageBlocked(envelope, content)) {
1780 logger.info("Ignoring a message from blocked user/group: {}", envelope.getTimestamp());
1781 } else if (isNotAGroupMember(envelope, content)) {
1782 logger.info("Ignoring a message from a non group member: {}", envelope.getTimestamp());
1783 } else {
1784 handler.handleMessage(envelope, content, exception);
1785 }
1786 if (!(exception instanceof org.whispersystems.libsignal.UntrustedIdentityException)) {
1787 if (cachedMessage[0] != null) {
1788 cachedMessage[0].delete();
1789 }
1790 }
1791 }
1792 }
1793
1794 private boolean isMessageBlocked(
1795 SignalServiceEnvelope envelope, SignalServiceContent content
1796 ) {
1797 SignalServiceAddress source;
1798 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1799 source = envelope.getSourceAddress();
1800 } else if (content != null) {
1801 source = content.getSender();
1802 } else {
1803 return false;
1804 }
1805 var sourceContact = account.getContactStore().getContact(source);
1806 if (sourceContact != null && sourceContact.blocked) {
1807 return true;
1808 }
1809
1810 if (content != null && content.getDataMessage().isPresent()) {
1811 var message = content.getDataMessage().get();
1812 if (message.getGroupContext().isPresent()) {
1813 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1814 var group = getGroup(groupId);
1815 if (group != null && group.isBlocked()) {
1816 return true;
1817 }
1818 }
1819 }
1820 return false;
1821 }
1822
1823 private boolean isNotAGroupMember(
1824 SignalServiceEnvelope envelope, SignalServiceContent content
1825 ) {
1826 SignalServiceAddress source;
1827 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1828 source = envelope.getSourceAddress();
1829 } else if (content != null) {
1830 source = content.getSender();
1831 } else {
1832 return false;
1833 }
1834
1835 if (content != null && content.getDataMessage().isPresent()) {
1836 var message = content.getDataMessage().get();
1837 if (message.getGroupContext().isPresent()) {
1838 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1839 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1840 if (groupInfo.getType() == SignalServiceGroup.Type.QUIT) {
1841 return false;
1842 }
1843 }
1844 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1845 var group = getGroup(groupId);
1846 if (group != null && !group.isMember(source)) {
1847 return true;
1848 }
1849 }
1850 }
1851 return false;
1852 }
1853
1854 private List<HandleAction> handleMessage(
1855 SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments
1856 ) {
1857 var actions = new ArrayList<HandleAction>();
1858 if (content != null) {
1859 final SignalServiceAddress sender;
1860 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1861 sender = envelope.getSourceAddress();
1862 } else {
1863 sender = content.getSender();
1864 }
1865 // Store uuid if we don't have it already
1866 resolveSignalServiceAddress(sender);
1867
1868 if (content.getDataMessage().isPresent()) {
1869 var message = content.getDataMessage().get();
1870
1871 if (content.isNeedsReceipt()) {
1872 actions.add(new SendReceiptAction(sender, message.getTimestamp()));
1873 }
1874
1875 actions.addAll(handleSignalServiceDataMessage(message,
1876 false,
1877 sender,
1878 account.getSelfAddress(),
1879 ignoreAttachments));
1880 }
1881 if (content.getSyncMessage().isPresent()) {
1882 account.setMultiDevice(true);
1883 var syncMessage = content.getSyncMessage().get();
1884 if (syncMessage.getSent().isPresent()) {
1885 var message = syncMessage.getSent().get();
1886 final var destination = message.getDestination().orNull();
1887 actions.addAll(handleSignalServiceDataMessage(message.getMessage(),
1888 true,
1889 sender,
1890 destination,
1891 ignoreAttachments));
1892 }
1893 if (syncMessage.getRequest().isPresent()) {
1894 var rm = syncMessage.getRequest().get();
1895 if (rm.isContactsRequest()) {
1896 actions.add(SendSyncContactsAction.create());
1897 }
1898 if (rm.isGroupsRequest()) {
1899 actions.add(SendSyncGroupsAction.create());
1900 }
1901 if (rm.isBlockedListRequest()) {
1902 actions.add(SendSyncBlockedListAction.create());
1903 }
1904 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1905 }
1906 if (syncMessage.getGroups().isPresent()) {
1907 File tmpFile = null;
1908 try {
1909 tmpFile = IOUtils.createTempFile();
1910 final var groupsMessage = syncMessage.getGroups().get();
1911 try (var attachmentAsStream = retrieveAttachmentAsStream(groupsMessage.asPointer(), tmpFile)) {
1912 var s = new DeviceGroupsInputStream(attachmentAsStream);
1913 DeviceGroup g;
1914 while ((g = s.read()) != null) {
1915 var syncGroup = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(g.getId()));
1916 if (syncGroup != null) {
1917 if (g.getName().isPresent()) {
1918 syncGroup.name = g.getName().get();
1919 }
1920 syncGroup.addMembers(g.getMembers()
1921 .stream()
1922 .map(this::resolveSignalServiceAddress)
1923 .collect(Collectors.toSet()));
1924 if (!g.isActive()) {
1925 syncGroup.removeMember(account.getSelfAddress());
1926 } else {
1927 // Add ourself to the member set as it's marked as active
1928 syncGroup.addMembers(List.of(account.getSelfAddress()));
1929 }
1930 syncGroup.blocked = g.isBlocked();
1931 if (g.getColor().isPresent()) {
1932 syncGroup.color = g.getColor().get();
1933 }
1934
1935 if (g.getAvatar().isPresent()) {
1936 downloadGroupAvatar(g.getAvatar().get(), syncGroup.getGroupId());
1937 }
1938 syncGroup.inboxPosition = g.getInboxPosition().orNull();
1939 syncGroup.archived = g.isArchived();
1940 account.getGroupStore().updateGroup(syncGroup);
1941 }
1942 }
1943 }
1944 } catch (Exception e) {
1945 logger.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1946 tmpFile,
1947 e.getMessage());
1948 } finally {
1949 if (tmpFile != null) {
1950 try {
1951 Files.delete(tmpFile.toPath());
1952 } catch (IOException e) {
1953 logger.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1954 tmpFile,
1955 e.getMessage());
1956 }
1957 }
1958 }
1959 }
1960 if (syncMessage.getBlockedList().isPresent()) {
1961 final var blockedListMessage = syncMessage.getBlockedList().get();
1962 for (var address : blockedListMessage.getAddresses()) {
1963 setContactBlocked(resolveSignalServiceAddress(address), true);
1964 }
1965 for (var groupId : blockedListMessage.getGroupIds()
1966 .stream()
1967 .map(GroupId::unknownVersion)
1968 .collect(Collectors.toSet())) {
1969 try {
1970 setGroupBlocked(groupId, true);
1971 } catch (GroupNotFoundException e) {
1972 logger.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1973 groupId.toBase64());
1974 }
1975 }
1976 }
1977 if (syncMessage.getContacts().isPresent()) {
1978 File tmpFile = null;
1979 try {
1980 tmpFile = IOUtils.createTempFile();
1981 final var contactsMessage = syncMessage.getContacts().get();
1982 try (var attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream()
1983 .asPointer(), tmpFile)) {
1984 var s = new DeviceContactsInputStream(attachmentAsStream);
1985 if (contactsMessage.isComplete()) {
1986 account.getContactStore().clear();
1987 }
1988 DeviceContact c;
1989 while ((c = s.read()) != null) {
1990 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
1991 account.setProfileKey(c.getProfileKey().get());
1992 }
1993 final var address = resolveSignalServiceAddress(c.getAddress());
1994 var contact = account.getContactStore().getContact(address);
1995 if (contact == null) {
1996 contact = new ContactInfo(address);
1997 }
1998 if (c.getName().isPresent()) {
1999 contact.name = c.getName().get();
2000 }
2001 if (c.getColor().isPresent()) {
2002 contact.color = c.getColor().get();
2003 }
2004 if (c.getProfileKey().isPresent()) {
2005 account.getProfileStore().storeProfileKey(address, c.getProfileKey().get());
2006 }
2007 if (c.getVerified().isPresent()) {
2008 final var verifiedMessage = c.getVerified().get();
2009 account.getSignalProtocolStore()
2010 .setIdentityTrustLevel(verifiedMessage.getDestination(),
2011 verifiedMessage.getIdentityKey(),
2012 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2013 }
2014 if (c.getExpirationTimer().isPresent()) {
2015 contact.messageExpirationTime = c.getExpirationTimer().get();
2016 }
2017 contact.blocked = c.isBlocked();
2018 contact.inboxPosition = c.getInboxPosition().orNull();
2019 contact.archived = c.isArchived();
2020 account.getContactStore().updateContact(contact);
2021
2022 if (c.getAvatar().isPresent()) {
2023 downloadContactAvatar(c.getAvatar().get(), contact.getAddress());
2024 }
2025 }
2026 }
2027 } catch (Exception e) {
2028 logger.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2029 tmpFile,
2030 e.getMessage());
2031 } finally {
2032 if (tmpFile != null) {
2033 try {
2034 Files.delete(tmpFile.toPath());
2035 } catch (IOException e) {
2036 logger.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2037 tmpFile,
2038 e.getMessage());
2039 }
2040 }
2041 }
2042 }
2043 if (syncMessage.getVerified().isPresent()) {
2044 final var verifiedMessage = syncMessage.getVerified().get();
2045 account.getSignalProtocolStore()
2046 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage.getDestination()),
2047 verifiedMessage.getIdentityKey(),
2048 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2049 }
2050 if (syncMessage.getStickerPackOperations().isPresent()) {
2051 final var stickerPackOperationMessages = syncMessage.getStickerPackOperations().get();
2052 for (var m : stickerPackOperationMessages) {
2053 if (!m.getPackId().isPresent()) {
2054 continue;
2055 }
2056 var sticker = account.getStickerStore().getSticker(m.getPackId().get());
2057 if (sticker == null) {
2058 if (!m.getPackKey().isPresent()) {
2059 continue;
2060 }
2061 sticker = new Sticker(m.getPackId().get(), m.getPackKey().get());
2062 }
2063 sticker.setInstalled(!m.getType().isPresent()
2064 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL);
2065 account.getStickerStore().updateSticker(sticker);
2066 }
2067 }
2068 if (syncMessage.getFetchType().isPresent()) {
2069 switch (syncMessage.getFetchType().get()) {
2070 case LOCAL_PROFILE:
2071 getRecipientProfile(getSelfAddress(), true);
2072 case STORAGE_MANIFEST:
2073 // TODO
2074 }
2075 }
2076 if (syncMessage.getKeys().isPresent()) {
2077 final var keysMessage = syncMessage.getKeys().get();
2078 if (keysMessage.getStorageService().isPresent()) {
2079 final var storageKey = keysMessage.getStorageService().get();
2080 account.setStorageKey(storageKey);
2081 }
2082 }
2083 if (syncMessage.getConfiguration().isPresent()) {
2084 // TODO
2085 }
2086 }
2087 }
2088 return actions;
2089 }
2090
2091 private void downloadContactAvatar(SignalServiceAttachment avatar, SignalServiceAddress address) {
2092 try {
2093 avatarStore.storeContactAvatar(address, outputStream -> retrieveAttachment(avatar, outputStream));
2094 } catch (IOException e) {
2095 logger.warn("Failed to download avatar for contact {}, ignoring: {}", address, e.getMessage());
2096 }
2097 }
2098
2099 private void downloadGroupAvatar(SignalServiceAttachment avatar, GroupId groupId) {
2100 try {
2101 avatarStore.storeGroupAvatar(groupId, outputStream -> retrieveAttachment(avatar, outputStream));
2102 } catch (IOException e) {
2103 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2104 }
2105 }
2106
2107 private void downloadGroupAvatar(GroupId groupId, GroupSecretParams groupSecretParams, String cdnKey) {
2108 try {
2109 avatarStore.storeGroupAvatar(groupId,
2110 outputStream -> retrieveGroupV2Avatar(groupSecretParams, cdnKey, outputStream));
2111 } catch (IOException e) {
2112 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2113 }
2114 }
2115
2116 private void downloadProfileAvatar(
2117 SignalServiceAddress address, String avatarPath, ProfileKey profileKey
2118 ) {
2119 try {
2120 avatarStore.storeProfileAvatar(address,
2121 outputStream -> retrieveProfileAvatar(avatarPath, profileKey, outputStream));
2122 } catch (Throwable e) {
2123 logger.warn("Failed to download profile avatar, ignoring: {}", e.getMessage());
2124 }
2125 }
2126
2127 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
2128 return attachmentStore.getAttachmentFile(attachmentId);
2129 }
2130
2131 private void downloadAttachment(final SignalServiceAttachment attachment) {
2132 if (!attachment.isPointer()) {
2133 logger.warn("Invalid state, can't store an attachment stream.");
2134 }
2135
2136 var pointer = attachment.asPointer();
2137 if (pointer.getPreview().isPresent()) {
2138 final var preview = pointer.getPreview().get();
2139 try {
2140 attachmentStore.storeAttachmentPreview(pointer.getRemoteId(),
2141 outputStream -> outputStream.write(preview, 0, preview.length));
2142 } catch (IOException e) {
2143 logger.warn("Failed to download attachment preview, ignoring: {}", e.getMessage());
2144 }
2145 }
2146
2147 try {
2148 attachmentStore.storeAttachment(pointer.getRemoteId(),
2149 outputStream -> retrieveAttachmentPointer(pointer, outputStream));
2150 } catch (IOException e) {
2151 logger.warn("Failed to download attachment ({}), ignoring: {}", pointer.getRemoteId(), e.getMessage());
2152 }
2153 }
2154
2155 private void retrieveGroupV2Avatar(
2156 GroupSecretParams groupSecretParams, String cdnKey, OutputStream outputStream
2157 ) throws IOException {
2158 var groupOperations = groupsV2Operations.forGroup(groupSecretParams);
2159
2160 var tmpFile = IOUtils.createTempFile();
2161 try (InputStream input = messageReceiver.retrieveGroupsV2ProfileAvatar(cdnKey,
2162 tmpFile,
2163 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2164 var encryptedData = IOUtils.readFully(input);
2165
2166 var decryptedData = groupOperations.decryptAvatar(encryptedData);
2167 outputStream.write(decryptedData);
2168 } finally {
2169 try {
2170 Files.delete(tmpFile.toPath());
2171 } catch (IOException e) {
2172 logger.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2173 tmpFile,
2174 e.getMessage());
2175 }
2176 }
2177 }
2178
2179 private void retrieveProfileAvatar(
2180 String avatarPath, ProfileKey profileKey, OutputStream outputStream
2181 ) throws IOException {
2182 var tmpFile = IOUtils.createTempFile();
2183 try (var input = messageReceiver.retrieveProfileAvatar(avatarPath,
2184 tmpFile,
2185 profileKey,
2186 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2187 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2188 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
2189 } finally {
2190 try {
2191 Files.delete(tmpFile.toPath());
2192 } catch (IOException e) {
2193 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2194 tmpFile,
2195 e.getMessage());
2196 }
2197 }
2198 }
2199
2200 private void retrieveAttachment(
2201 final SignalServiceAttachment attachment, final OutputStream outputStream
2202 ) throws IOException {
2203 if (attachment.isPointer()) {
2204 var pointer = attachment.asPointer();
2205 retrieveAttachmentPointer(pointer, outputStream);
2206 } else {
2207 var stream = attachment.asStream();
2208 IOUtils.copyStream(stream.getInputStream(), outputStream);
2209 }
2210 }
2211
2212 private void retrieveAttachmentPointer(
2213 SignalServiceAttachmentPointer pointer, OutputStream outputStream
2214 ) throws IOException {
2215 var tmpFile = IOUtils.createTempFile();
2216 try (var input = retrieveAttachmentAsStream(pointer, tmpFile)) {
2217 IOUtils.copyStream(input, outputStream);
2218 } catch (MissingConfigurationException | InvalidMessageException e) {
2219 throw new IOException(e);
2220 } finally {
2221 try {
2222 Files.delete(tmpFile.toPath());
2223 } catch (IOException e) {
2224 logger.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2225 tmpFile,
2226 e.getMessage());
2227 }
2228 }
2229 }
2230
2231 private InputStream retrieveAttachmentAsStream(
2232 SignalServiceAttachmentPointer pointer, File tmpFile
2233 ) throws IOException, InvalidMessageException, MissingConfigurationException {
2234 return messageReceiver.retrieveAttachment(pointer, tmpFile, ServiceConfig.MAX_ATTACHMENT_SIZE);
2235 }
2236
2237 void sendGroups() throws IOException, UntrustedIdentityException {
2238 var groupsFile = IOUtils.createTempFile();
2239
2240 try {
2241 try (OutputStream fos = new FileOutputStream(groupsFile)) {
2242 var out = new DeviceGroupsOutputStream(fos);
2243 for (var record : getGroups()) {
2244 if (record instanceof GroupInfoV1) {
2245 var groupInfo = (GroupInfoV1) record;
2246 out.write(new DeviceGroup(groupInfo.getGroupId().serialize(),
2247 Optional.fromNullable(groupInfo.name),
2248 new ArrayList<>(groupInfo.getMembers()),
2249 createGroupAvatarAttachment(groupInfo.getGroupId()),
2250 groupInfo.isMember(account.getSelfAddress()),
2251 Optional.of(groupInfo.messageExpirationTime),
2252 Optional.fromNullable(groupInfo.color),
2253 groupInfo.blocked,
2254 Optional.fromNullable(groupInfo.inboxPosition),
2255 groupInfo.archived));
2256 }
2257 }
2258 }
2259
2260 if (groupsFile.exists() && groupsFile.length() > 0) {
2261 try (var groupsFileStream = new FileInputStream(groupsFile)) {
2262 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2263 .withStream(groupsFileStream)
2264 .withContentType("application/octet-stream")
2265 .withLength(groupsFile.length())
2266 .build();
2267
2268 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
2269 }
2270 }
2271 } finally {
2272 try {
2273 Files.delete(groupsFile.toPath());
2274 } catch (IOException e) {
2275 logger.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile, e.getMessage());
2276 }
2277 }
2278 }
2279
2280 public void sendContacts() throws IOException, UntrustedIdentityException {
2281 var contactsFile = IOUtils.createTempFile();
2282
2283 try {
2284 try (OutputStream fos = new FileOutputStream(contactsFile)) {
2285 var out = new DeviceContactsOutputStream(fos);
2286 for (var record : account.getContactStore().getContacts()) {
2287 VerifiedMessage verifiedMessage = null;
2288 var currentIdentity = account.getSignalProtocolStore().getIdentity(record.getAddress());
2289 if (currentIdentity != null) {
2290 verifiedMessage = new VerifiedMessage(record.getAddress(),
2291 currentIdentity.getIdentityKey(),
2292 currentIdentity.getTrustLevel().toVerifiedState(),
2293 currentIdentity.getDateAdded().getTime());
2294 }
2295
2296 var profileKey = account.getProfileStore().getProfileKey(record.getAddress());
2297 out.write(new DeviceContact(record.getAddress(),
2298 Optional.fromNullable(record.name),
2299 createContactAvatarAttachment(record.getAddress()),
2300 Optional.fromNullable(record.color),
2301 Optional.fromNullable(verifiedMessage),
2302 Optional.fromNullable(profileKey),
2303 record.blocked,
2304 Optional.of(record.messageExpirationTime),
2305 Optional.fromNullable(record.inboxPosition),
2306 record.archived));
2307 }
2308
2309 if (account.getProfileKey() != null) {
2310 // Send our own profile key as well
2311 out.write(new DeviceContact(account.getSelfAddress(),
2312 Optional.absent(),
2313 Optional.absent(),
2314 Optional.absent(),
2315 Optional.absent(),
2316 Optional.of(account.getProfileKey()),
2317 false,
2318 Optional.absent(),
2319 Optional.absent(),
2320 false));
2321 }
2322 }
2323
2324 if (contactsFile.exists() && contactsFile.length() > 0) {
2325 try (var contactsFileStream = new FileInputStream(contactsFile)) {
2326 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2327 .withStream(contactsFileStream)
2328 .withContentType("application/octet-stream")
2329 .withLength(contactsFile.length())
2330 .build();
2331
2332 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
2333 }
2334 }
2335 } finally {
2336 try {
2337 Files.delete(contactsFile.toPath());
2338 } catch (IOException e) {
2339 logger.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile, e.getMessage());
2340 }
2341 }
2342 }
2343
2344 void sendBlockedList() throws IOException, UntrustedIdentityException {
2345 var addresses = new ArrayList<SignalServiceAddress>();
2346 for (var record : account.getContactStore().getContacts()) {
2347 if (record.blocked) {
2348 addresses.add(record.getAddress());
2349 }
2350 }
2351 var groupIds = new ArrayList<byte[]>();
2352 for (var record : getGroups()) {
2353 if (record.isBlocked()) {
2354 groupIds.add(record.getGroupId().serialize());
2355 }
2356 }
2357 sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
2358 }
2359
2360 private void sendVerifiedMessage(
2361 SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel
2362 ) throws IOException, UntrustedIdentityException {
2363 var verifiedMessage = new VerifiedMessage(destination,
2364 identityKey,
2365 trustLevel.toVerifiedState(),
2366 System.currentTimeMillis());
2367 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
2368 }
2369
2370 public List<ContactInfo> getContacts() {
2371 return account.getContactStore().getContacts();
2372 }
2373
2374 public String getContactOrProfileName(String number) {
2375 final var address = Utils.getSignalServiceAddressFromIdentifier(number);
2376
2377 final var contact = account.getContactStore().getContact(address);
2378 if (contact != null && !Util.isEmpty(contact.name)) {
2379 return contact.name;
2380 }
2381
2382 final var profileEntry = account.getProfileStore().getProfileEntry(address);
2383 if (profileEntry != null && profileEntry.getProfile() != null) {
2384 return profileEntry.getProfile().getDisplayName();
2385 }
2386 return null;
2387 }
2388
2389 public GroupInfo getGroup(GroupId groupId) {
2390 final var group = account.getGroupStore().getGroup(groupId);
2391 if (group instanceof GroupInfoV2 && ((GroupInfoV2) group).getGroup() == null) {
2392 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(((GroupInfoV2) group).getMasterKey());
2393 ((GroupInfoV2) group).setGroup(groupHelper.getDecryptedGroup(groupSecretParams));
2394 account.getGroupStore().updateGroup(group);
2395 }
2396 return group;
2397 }
2398
2399 public List<IdentityInfo> getIdentities() {
2400 return account.getSignalProtocolStore().getIdentities();
2401 }
2402
2403 public List<IdentityInfo> getIdentities(String number) throws InvalidNumberException {
2404 return account.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number));
2405 }
2406
2407 /**
2408 * Trust this the identity with this fingerprint
2409 *
2410 * @param name username of the identity
2411 * @param fingerprint Fingerprint
2412 */
2413 public boolean trustIdentityVerified(String name, byte[] fingerprint) throws InvalidNumberException {
2414 var address = canonicalizeAndResolveSignalServiceAddress(name);
2415 return trustIdentity(address, (identityKey) -> Arrays.equals(identityKey.serialize(), fingerprint));
2416 }
2417
2418 /**
2419 * Trust this the identity with this safety number
2420 *
2421 * @param name username of the identity
2422 * @param safetyNumber Safety number
2423 */
2424 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) throws InvalidNumberException {
2425 var address = canonicalizeAndResolveSignalServiceAddress(name);
2426 return trustIdentity(address, (identityKey) -> safetyNumber.equals(computeSafetyNumber(address, identityKey)));
2427 }
2428
2429 private boolean trustIdentity(SignalServiceAddress address, Function<IdentityKey, Boolean> verifier) {
2430 var ids = account.getSignalProtocolStore().getIdentities(address);
2431 if (ids == null) {
2432 return false;
2433 }
2434
2435 IdentityInfo foundIdentity = null;
2436
2437 for (var id : ids) {
2438 if (verifier.apply(id.getIdentityKey())) {
2439 foundIdentity = id;
2440 break;
2441 }
2442 }
2443
2444 if (foundIdentity == null) {
2445 return false;
2446 }
2447
2448 account.getSignalProtocolStore()
2449 .setIdentityTrustLevel(address, foundIdentity.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2450 try {
2451 sendVerifiedMessage(address, foundIdentity.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2452 } catch (IOException | UntrustedIdentityException e) {
2453 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2454 }
2455
2456 // Successfully trusted the new identity, now remove all other identities for that number
2457 for (var id : ids) {
2458 if (id == foundIdentity) {
2459 continue;
2460 }
2461 account.getSignalProtocolStore().removeIdentity(address, id.getIdentityKey());
2462 }
2463
2464 account.save();
2465 return true;
2466 }
2467
2468 /**
2469 * Trust all keys of this identity without verification
2470 *
2471 * @param name username of the identity
2472 */
2473 public boolean trustIdentityAllKeys(String name) {
2474 var address = resolveSignalServiceAddress(name);
2475 var ids = account.getSignalProtocolStore().getIdentities(address);
2476 if (ids == null) {
2477 return false;
2478 }
2479 for (var id : ids) {
2480 if (id.getTrustLevel() == TrustLevel.UNTRUSTED) {
2481 account.getSignalProtocolStore()
2482 .setIdentityTrustLevel(address, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
2483 try {
2484 sendVerifiedMessage(address, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
2485 } catch (IOException | UntrustedIdentityException e) {
2486 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2487 }
2488 }
2489 }
2490 account.save();
2491 return true;
2492 }
2493
2494 public String computeSafetyNumber(
2495 SignalServiceAddress theirAddress, IdentityKey theirIdentityKey
2496 ) {
2497 return Utils.computeSafetyNumber(ServiceConfig.capabilities.isUuid(),
2498 account.getSelfAddress(),
2499 getIdentityKeyPair().getPublicKey(),
2500 theirAddress,
2501 theirIdentityKey);
2502 }
2503
2504 public SignalServiceAddress canonicalizeAndResolveSignalServiceAddress(String identifier) throws InvalidNumberException {
2505 var canonicalizedNumber = UuidUtil.isUuid(identifier)
2506 ? identifier
2507 : PhoneNumberFormatter.formatNumber(identifier, account.getUsername());
2508 return resolveSignalServiceAddress(canonicalizedNumber);
2509 }
2510
2511 public SignalServiceAddress resolveSignalServiceAddress(String identifier) {
2512 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2513
2514 return resolveSignalServiceAddress(address);
2515 }
2516
2517 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
2518 if (address.matches(account.getSelfAddress())) {
2519 return account.getSelfAddress();
2520 }
2521
2522 return account.getRecipientStore().resolveServiceAddress(address);
2523 }
2524
2525 @Override
2526 public void close() throws IOException {
2527 close(true);
2528 }
2529
2530 void close(boolean closeAccount) throws IOException {
2531 executor.shutdown();
2532
2533 if (messagePipe != null) {
2534 messagePipe.shutdown();
2535 messagePipe = null;
2536 }
2537
2538 if (unidentifiedMessagePipe != null) {
2539 unidentifiedMessagePipe.shutdown();
2540 unidentifiedMessagePipe = null;
2541 }
2542
2543 if (closeAccount && account != null) {
2544 account.close();
2545 }
2546 account = null;
2547 }
2548
2549 public interface ReceiveMessageHandler {
2550
2551 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
2552 }
2553 }