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