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