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