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