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