]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/manager/Manager.java
Use exit 4 when sending a single recipient message fails due to untrusted identity key
[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, SendMessageResult> sendSelfMessage(
957 String messageText, List<String> attachments
958 ) throws IOException, AttachmentInvalidException {
959 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
960 .withBody(messageText);
961 if (attachments != null) {
962 messageBuilder.withAttachments(AttachmentUtils.getSignalServiceAttachments(attachments));
963 }
964 return sendSelfMessage(messageBuilder);
965 }
966
967 public Pair<Long, List<SendMessageResult>> sendMessageReaction(
968 String emoji, boolean remove, String targetAuthor, long targetSentTimestamp, List<String> recipients
969 ) throws IOException, InvalidNumberException {
970 SignalServiceDataMessage.Reaction reaction = new SignalServiceDataMessage.Reaction(emoji,
971 remove,
972 canonicalizeAndResolveSignalServiceAddress(targetAuthor),
973 targetSentTimestamp);
974 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
975 .withReaction(reaction);
976 return sendMessage(messageBuilder, getSignalServiceAddresses(recipients));
977 }
978
979 public Pair<Long, List<SendMessageResult>> sendEndSessionMessage(List<String> recipients) throws IOException, InvalidNumberException {
980 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().asEndSessionMessage();
981
982 final Collection<SignalServiceAddress> signalServiceAddresses = getSignalServiceAddresses(recipients);
983 try {
984 return sendMessage(messageBuilder, signalServiceAddresses);
985 } catch (Exception e) {
986 for (SignalServiceAddress address : signalServiceAddresses) {
987 handleEndSession(address);
988 }
989 account.save();
990 throw e;
991 }
992 }
993
994 public String getContactName(String number) throws InvalidNumberException {
995 ContactInfo contact = account.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number));
996 if (contact == null) {
997 return "";
998 } else {
999 return contact.name;
1000 }
1001 }
1002
1003 public void setContactName(String number, String name) throws InvalidNumberException {
1004 final SignalServiceAddress address = canonicalizeAndResolveSignalServiceAddress(number);
1005 ContactInfo contact = account.getContactStore().getContact(address);
1006 if (contact == null) {
1007 contact = new ContactInfo(address);
1008 }
1009 contact.name = name;
1010 account.getContactStore().updateContact(contact);
1011 account.save();
1012 }
1013
1014 public void setContactBlocked(String number, boolean blocked) throws InvalidNumberException {
1015 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number), blocked);
1016 }
1017
1018 private void setContactBlocked(SignalServiceAddress address, boolean blocked) {
1019 ContactInfo contact = account.getContactStore().getContact(address);
1020 if (contact == null) {
1021 contact = new ContactInfo(address);
1022 }
1023 contact.blocked = blocked;
1024 account.getContactStore().updateContact(contact);
1025 account.save();
1026 }
1027
1028 public void setGroupBlocked(final GroupId groupId, final boolean blocked) throws GroupNotFoundException {
1029 GroupInfo group = getGroup(groupId);
1030 if (group == null) {
1031 throw new GroupNotFoundException(groupId);
1032 }
1033
1034 group.setBlocked(blocked);
1035 account.getGroupStore().updateGroup(group);
1036 account.save();
1037 }
1038
1039 /**
1040 * Change the expiration timer for a contact
1041 */
1042 public void setExpirationTimer(SignalServiceAddress address, int messageExpirationTimer) throws IOException {
1043 ContactInfo contact = account.getContactStore().getContact(address);
1044 contact.messageExpirationTime = messageExpirationTimer;
1045 account.getContactStore().updateContact(contact);
1046 sendExpirationTimerUpdate(address);
1047 account.save();
1048 }
1049
1050 private void sendExpirationTimerUpdate(SignalServiceAddress address) throws IOException {
1051 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
1052 .asExpirationUpdate();
1053 sendMessage(messageBuilder, List.of(address));
1054 }
1055
1056 /**
1057 * Change the expiration timer for a contact
1058 */
1059 public void setExpirationTimer(
1060 String number, int messageExpirationTimer
1061 ) throws IOException, InvalidNumberException {
1062 SignalServiceAddress address = canonicalizeAndResolveSignalServiceAddress(number);
1063 setExpirationTimer(address, messageExpirationTimer);
1064 }
1065
1066 /**
1067 * Change the expiration timer for a group
1068 */
1069 public void setExpirationTimer(GroupId groupId, int messageExpirationTimer) {
1070 GroupInfo g = getGroup(groupId);
1071 if (g instanceof GroupInfoV1) {
1072 GroupInfoV1 groupInfoV1 = (GroupInfoV1) g;
1073 groupInfoV1.messageExpirationTime = messageExpirationTimer;
1074 account.getGroupStore().updateGroup(groupInfoV1);
1075 } else {
1076 throw new RuntimeException("TODO Not implemented!");
1077 }
1078 }
1079
1080 /**
1081 * Upload the sticker pack from path.
1082 *
1083 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1084 * @return if successful, returns the URL to install the sticker pack in the signal app
1085 */
1086 public String uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
1087 SignalServiceStickerManifestUpload manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
1088
1089 SignalServiceMessageSender messageSender = createMessageSender();
1090
1091 byte[] packKey = KeyUtils.createStickerUploadKey();
1092 String packId = messageSender.uploadStickerManifest(manifest, packKey);
1093
1094 Sticker sticker = new Sticker(Hex.fromStringCondensed(packId), packKey);
1095 account.getStickerStore().updateSticker(sticker);
1096 account.save();
1097
1098 try {
1099 return new URI("https",
1100 "signal.art",
1101 "/addstickers/",
1102 "pack_id=" + URLEncoder.encode(packId, StandardCharsets.UTF_8) + "&pack_key=" + URLEncoder.encode(
1103 Hex.toStringCondensed(packKey),
1104 StandardCharsets.UTF_8)).toString();
1105 } catch (URISyntaxException e) {
1106 throw new AssertionError(e);
1107 }
1108 }
1109
1110 void requestSyncGroups() throws IOException {
1111 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1112 .setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS)
1113 .build();
1114 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1115 try {
1116 sendSyncMessage(message);
1117 } catch (UntrustedIdentityException e) {
1118 throw new AssertionError(e);
1119 }
1120 }
1121
1122 void requestSyncContacts() throws IOException {
1123 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1124 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS)
1125 .build();
1126 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1127 try {
1128 sendSyncMessage(message);
1129 } catch (UntrustedIdentityException e) {
1130 throw new AssertionError(e);
1131 }
1132 }
1133
1134 void requestSyncBlocked() throws IOException {
1135 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1136 .setType(SignalServiceProtos.SyncMessage.Request.Type.BLOCKED)
1137 .build();
1138 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1139 try {
1140 sendSyncMessage(message);
1141 } catch (UntrustedIdentityException e) {
1142 throw new AssertionError(e);
1143 }
1144 }
1145
1146 void requestSyncConfiguration() throws IOException {
1147 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1148 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONFIGURATION)
1149 .build();
1150 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1151 try {
1152 sendSyncMessage(message);
1153 } catch (UntrustedIdentityException e) {
1154 throw new AssertionError(e);
1155 }
1156 }
1157
1158 private byte[] getSenderCertificate() {
1159 // TODO support UUID capable sender certificates
1160 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1161 byte[] certificate;
1162 try {
1163 certificate = accountManager.getSenderCertificate();
1164 } catch (IOException e) {
1165 logger.warn("Failed to get sender certificate, ignoring: {}", e.getMessage());
1166 return null;
1167 }
1168 // TODO cache for a day
1169 return certificate;
1170 }
1171
1172 private void sendSyncMessage(SignalServiceSyncMessage message) throws IOException, UntrustedIdentityException {
1173 SignalServiceMessageSender messageSender = createMessageSender();
1174 try {
1175 messageSender.sendMessage(message, unidentifiedAccessHelper.getAccessForSync());
1176 } catch (UntrustedIdentityException e) {
1177 account.getSignalProtocolStore()
1178 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1179 e.getIdentityKey(),
1180 TrustLevel.UNTRUSTED);
1181 throw e;
1182 }
1183 }
1184
1185 private Collection<SignalServiceAddress> getSignalServiceAddresses(Collection<String> numbers) throws InvalidNumberException {
1186 final Set<SignalServiceAddress> signalServiceAddresses = new HashSet<>(numbers.size());
1187 final Set<SignalServiceAddress> missingUuids = new HashSet<>();
1188
1189 for (String number : numbers) {
1190 final SignalServiceAddress resolvedAddress = canonicalizeAndResolveSignalServiceAddress(number);
1191 if (resolvedAddress.getUuid().isPresent()) {
1192 signalServiceAddresses.add(resolvedAddress);
1193 } else {
1194 missingUuids.add(resolvedAddress);
1195 }
1196 }
1197
1198 Map<String, UUID> registeredUsers;
1199 try {
1200 registeredUsers = accountManager.getRegisteredUsers(getIasKeyStore(),
1201 missingUuids.stream().map(a -> a.getNumber().get()).collect(Collectors.toSet()),
1202 CDS_MRENCLAVE);
1203 } catch (IOException | Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException e) {
1204 logger.warn("Failed to resolve uuids from server, ignoring: {}", e.getMessage());
1205 registeredUsers = new HashMap<>();
1206 }
1207
1208 for (SignalServiceAddress address : missingUuids) {
1209 final String number = address.getNumber().get();
1210 if (registeredUsers.containsKey(number)) {
1211 final SignalServiceAddress newAddress = resolveSignalServiceAddress(new SignalServiceAddress(
1212 registeredUsers.get(number),
1213 number));
1214 signalServiceAddresses.add(newAddress);
1215 } else {
1216 signalServiceAddresses.add(address);
1217 }
1218 }
1219
1220 return signalServiceAddresses;
1221 }
1222
1223 private Pair<Long, List<SendMessageResult>> sendMessage(
1224 SignalServiceDataMessage.Builder messageBuilder, Collection<SignalServiceAddress> recipients
1225 ) throws IOException {
1226 recipients = recipients.stream().map(this::resolveSignalServiceAddress).collect(Collectors.toSet());
1227 final long timestamp = System.currentTimeMillis();
1228 messageBuilder.withTimestamp(timestamp);
1229 getOrCreateMessagePipe();
1230 getOrCreateUnidentifiedMessagePipe();
1231 SignalServiceDataMessage message = null;
1232 try {
1233 message = messageBuilder.build();
1234 if (message.getGroupContext().isPresent()) {
1235 try {
1236 SignalServiceMessageSender messageSender = createMessageSender();
1237 final boolean isRecipientUpdate = false;
1238 List<SendMessageResult> result = messageSender.sendMessage(new ArrayList<>(recipients),
1239 unidentifiedAccessHelper.getAccessFor(recipients),
1240 isRecipientUpdate,
1241 message);
1242 for (SendMessageResult r : result) {
1243 if (r.getIdentityFailure() != null) {
1244 account.getSignalProtocolStore()
1245 .saveIdentity(r.getAddress(),
1246 r.getIdentityFailure().getIdentityKey(),
1247 TrustLevel.UNTRUSTED);
1248 }
1249 }
1250 return new Pair<>(timestamp, result);
1251 } catch (UntrustedIdentityException e) {
1252 account.getSignalProtocolStore()
1253 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1254 e.getIdentityKey(),
1255 TrustLevel.UNTRUSTED);
1256 return new Pair<>(timestamp, List.of());
1257 }
1258 } else {
1259 // Send to all individually, so sync messages are sent correctly
1260 messageBuilder.withProfileKey(account.getProfileKey().serialize());
1261 List<SendMessageResult> results = new ArrayList<>(recipients.size());
1262 for (SignalServiceAddress address : recipients) {
1263 final ContactInfo contact = account.getContactStore().getContact(address);
1264 final int expirationTime = contact != null ? contact.messageExpirationTime : 0;
1265 messageBuilder.withExpiration(expirationTime);
1266 message = messageBuilder.build();
1267 results.add(sendMessage(address, message));
1268 }
1269 return new Pair<>(timestamp, results);
1270 }
1271 } finally {
1272 if (message != null && message.isEndSession()) {
1273 for (SignalServiceAddress recipient : recipients) {
1274 handleEndSession(recipient);
1275 }
1276 }
1277 account.save();
1278 }
1279 }
1280
1281 private Pair<Long, SendMessageResult> sendSelfMessage(
1282 SignalServiceDataMessage.Builder messageBuilder
1283 ) throws IOException {
1284 final long timestamp = System.currentTimeMillis();
1285 messageBuilder.withTimestamp(timestamp);
1286 getOrCreateMessagePipe();
1287 getOrCreateUnidentifiedMessagePipe();
1288 try {
1289 final SignalServiceAddress address = getSelfAddress();
1290
1291 final ContactInfo contact = account.getContactStore().getContact(address);
1292 final int expirationTime = contact != null ? contact.messageExpirationTime : 0;
1293 messageBuilder.withExpiration(expirationTime);
1294
1295 SignalServiceDataMessage message = messageBuilder.build();
1296 final SendMessageResult result = sendSelfMessage(message);
1297 return new Pair<>(timestamp, result);
1298 } finally {
1299 account.save();
1300 }
1301 }
1302
1303 private SendMessageResult sendSelfMessage(SignalServiceDataMessage message) throws IOException {
1304 SignalServiceMessageSender messageSender = createMessageSender();
1305
1306 SignalServiceAddress recipient = account.getSelfAddress();
1307
1308 final Optional<UnidentifiedAccessPair> unidentifiedAccess = unidentifiedAccessHelper.getAccessFor(recipient);
1309 SentTranscriptMessage transcript = new SentTranscriptMessage(Optional.of(recipient),
1310 message.getTimestamp(),
1311 message,
1312 message.getExpiresInSeconds(),
1313 Map.of(recipient, unidentifiedAccess.isPresent()),
1314 false);
1315 SignalServiceSyncMessage syncMessage = SignalServiceSyncMessage.forSentTranscript(transcript);
1316
1317 try {
1318 long startTime = System.currentTimeMillis();
1319 messageSender.sendMessage(syncMessage, unidentifiedAccess);
1320 return SendMessageResult.success(recipient,
1321 unidentifiedAccess.isPresent(),
1322 false,
1323 System.currentTimeMillis() - startTime);
1324 } catch (UntrustedIdentityException e) {
1325 account.getSignalProtocolStore()
1326 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1327 e.getIdentityKey(),
1328 TrustLevel.UNTRUSTED);
1329 return SendMessageResult.identityFailure(recipient, e.getIdentityKey());
1330 }
1331 }
1332
1333 private SendMessageResult sendMessage(
1334 SignalServiceAddress address, SignalServiceDataMessage message
1335 ) throws IOException {
1336 SignalServiceMessageSender messageSender = createMessageSender();
1337
1338 try {
1339 return messageSender.sendMessage(address, unidentifiedAccessHelper.getAccessFor(address), message);
1340 } catch (UntrustedIdentityException e) {
1341 account.getSignalProtocolStore()
1342 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1343 e.getIdentityKey(),
1344 TrustLevel.UNTRUSTED);
1345 return SendMessageResult.identityFailure(address, e.getIdentityKey());
1346 }
1347 }
1348
1349 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, SelfSendException, UnsupportedDataMessageException, org.whispersystems.libsignal.UntrustedIdentityException {
1350 SignalServiceCipher cipher = new SignalServiceCipher(account.getSelfAddress(),
1351 account.getSignalProtocolStore(),
1352 certificateValidator);
1353 try {
1354 return cipher.decrypt(envelope);
1355 } catch (ProtocolUntrustedIdentityException e) {
1356 if (e.getCause() instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
1357 org.whispersystems.libsignal.UntrustedIdentityException identityException = (org.whispersystems.libsignal.UntrustedIdentityException) e
1358 .getCause();
1359 account.getSignalProtocolStore()
1360 .saveIdentity(resolveSignalServiceAddress(identityException.getName()),
1361 identityException.getUntrustedIdentity(),
1362 TrustLevel.UNTRUSTED);
1363 throw identityException;
1364 }
1365 throw new AssertionError(e);
1366 }
1367 }
1368
1369 private void handleEndSession(SignalServiceAddress source) {
1370 account.getSignalProtocolStore().deleteAllSessions(source);
1371 }
1372
1373 private List<HandleAction> handleSignalServiceDataMessage(
1374 SignalServiceDataMessage message,
1375 boolean isSync,
1376 SignalServiceAddress source,
1377 SignalServiceAddress destination,
1378 boolean ignoreAttachments
1379 ) {
1380 List<HandleAction> actions = new ArrayList<>();
1381 if (message.getGroupContext().isPresent()) {
1382 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1383 SignalServiceGroup groupInfo = message.getGroupContext().get().getGroupV1().get();
1384 GroupIdV1 groupId = GroupId.v1(groupInfo.getGroupId());
1385 GroupInfo group = getGroup(groupId);
1386 if (group == null || group instanceof GroupInfoV1) {
1387 GroupInfoV1 groupV1 = (GroupInfoV1) group;
1388 switch (groupInfo.getType()) {
1389 case UPDATE: {
1390 if (groupV1 == null) {
1391 groupV1 = new GroupInfoV1(groupId);
1392 }
1393
1394 if (groupInfo.getAvatar().isPresent()) {
1395 SignalServiceAttachment avatar = groupInfo.getAvatar().get();
1396 downloadGroupAvatar(avatar, groupV1.getGroupId());
1397 }
1398
1399 if (groupInfo.getName().isPresent()) {
1400 groupV1.name = groupInfo.getName().get();
1401 }
1402
1403 if (groupInfo.getMembers().isPresent()) {
1404 groupV1.addMembers(groupInfo.getMembers()
1405 .get()
1406 .stream()
1407 .map(this::resolveSignalServiceAddress)
1408 .collect(Collectors.toSet()));
1409 }
1410
1411 account.getGroupStore().updateGroup(groupV1);
1412 break;
1413 }
1414 case DELIVER:
1415 if (groupV1 == null && !isSync) {
1416 actions.add(new SendGroupInfoRequestAction(source, groupId));
1417 }
1418 break;
1419 case QUIT: {
1420 if (groupV1 != null) {
1421 groupV1.removeMember(source);
1422 account.getGroupStore().updateGroup(groupV1);
1423 }
1424 break;
1425 }
1426 case REQUEST_INFO:
1427 if (groupV1 != null && !isSync) {
1428 actions.add(new SendGroupInfoAction(source, groupV1.getGroupId()));
1429 }
1430 break;
1431 }
1432 } else {
1433 // Received a group v1 message for a v2 group
1434 }
1435 }
1436 if (message.getGroupContext().get().getGroupV2().isPresent()) {
1437 final SignalServiceGroupV2 groupContext = message.getGroupContext().get().getGroupV2().get();
1438 final GroupMasterKey groupMasterKey = groupContext.getMasterKey();
1439
1440 getOrMigrateGroup(groupMasterKey,
1441 groupContext.getRevision(),
1442 groupContext.hasSignedGroupChange() ? groupContext.getSignedGroupChange() : null);
1443 }
1444 }
1445
1446 final SignalServiceAddress conversationPartnerAddress = isSync ? destination : source;
1447 if (conversationPartnerAddress != null && message.isEndSession()) {
1448 handleEndSession(conversationPartnerAddress);
1449 }
1450 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
1451 if (message.getGroupContext().isPresent()) {
1452 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1453 SignalServiceGroup groupInfo = message.getGroupContext().get().getGroupV1().get();
1454 GroupInfoV1 group = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(groupInfo.getGroupId()));
1455 if (group != null) {
1456 if (group.messageExpirationTime != message.getExpiresInSeconds()) {
1457 group.messageExpirationTime = message.getExpiresInSeconds();
1458 account.getGroupStore().updateGroup(group);
1459 }
1460 }
1461 } else if (message.getGroupContext().get().getGroupV2().isPresent()) {
1462 // disappearing message timer already stored in the DecryptedGroup
1463 }
1464 } else if (conversationPartnerAddress != null) {
1465 ContactInfo contact = account.getContactStore().getContact(conversationPartnerAddress);
1466 if (contact == null) {
1467 contact = new ContactInfo(conversationPartnerAddress);
1468 }
1469 if (contact.messageExpirationTime != message.getExpiresInSeconds()) {
1470 contact.messageExpirationTime = message.getExpiresInSeconds();
1471 account.getContactStore().updateContact(contact);
1472 }
1473 }
1474 }
1475 if (message.getAttachments().isPresent() && !ignoreAttachments) {
1476 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1477 downloadAttachment(attachment);
1478 }
1479 }
1480 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
1481 final ProfileKey profileKey;
1482 try {
1483 profileKey = new ProfileKey(message.getProfileKey().get());
1484 } catch (InvalidInputException e) {
1485 throw new AssertionError(e);
1486 }
1487 if (source.matches(account.getSelfAddress())) {
1488 this.account.setProfileKey(profileKey);
1489 }
1490 this.account.getProfileStore().storeProfileKey(source, profileKey);
1491 }
1492 if (message.getPreviews().isPresent()) {
1493 final List<SignalServiceDataMessage.Preview> previews = message.getPreviews().get();
1494 for (SignalServiceDataMessage.Preview preview : previews) {
1495 if (preview.getImage().isPresent()) {
1496 downloadAttachment(preview.getImage().get());
1497 }
1498 }
1499 }
1500 if (message.getQuote().isPresent()) {
1501 final SignalServiceDataMessage.Quote quote = message.getQuote().get();
1502
1503 for (SignalServiceDataMessage.Quote.QuotedAttachment quotedAttachment : quote.getAttachments()) {
1504 final SignalServiceAttachment thumbnail = quotedAttachment.getThumbnail();
1505 if (thumbnail != null) {
1506 downloadAttachment(thumbnail);
1507 }
1508 }
1509 }
1510 if (message.getSticker().isPresent()) {
1511 final SignalServiceDataMessage.Sticker messageSticker = message.getSticker().get();
1512 Sticker sticker = account.getStickerStore().getSticker(messageSticker.getPackId());
1513 if (sticker == null) {
1514 sticker = new Sticker(messageSticker.getPackId(), messageSticker.getPackKey());
1515 account.getStickerStore().updateSticker(sticker);
1516 }
1517 }
1518 return actions;
1519 }
1520
1521 private GroupInfoV2 getOrMigrateGroup(
1522 final GroupMasterKey groupMasterKey, final int revision, final byte[] signedGroupChange
1523 ) {
1524 final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
1525
1526 GroupIdV2 groupId = GroupUtils.getGroupIdV2(groupSecretParams);
1527 GroupInfo groupInfo = getGroup(groupId);
1528 final GroupInfoV2 groupInfoV2;
1529 if (groupInfo instanceof GroupInfoV1) {
1530 // Received a v2 group message for a v1 group, we need to locally migrate the group
1531 account.getGroupStore().deleteGroup(groupInfo.getGroupId());
1532 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1533 logger.info("Locally migrated group {} to group v2, id: {}",
1534 groupInfo.getGroupId().toBase64(),
1535 groupInfoV2.getGroupId().toBase64());
1536 } else if (groupInfo instanceof GroupInfoV2) {
1537 groupInfoV2 = (GroupInfoV2) groupInfo;
1538 } else {
1539 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1540 }
1541
1542 if (groupInfoV2.getGroup() == null || groupInfoV2.getGroup().getRevision() < revision) {
1543 DecryptedGroup group = null;
1544 if (signedGroupChange != null
1545 && groupInfoV2.getGroup() != null
1546 && groupInfoV2.getGroup().getRevision() + 1 == revision) {
1547 group = groupHelper.getUpdatedDecryptedGroup(groupInfoV2.getGroup(), signedGroupChange, groupMasterKey);
1548 }
1549 if (group == null) {
1550 group = groupHelper.getDecryptedGroup(groupSecretParams);
1551 }
1552 if (group != null) {
1553 storeProfileKeysFromMembers(group);
1554 final String avatar = group.getAvatar();
1555 if (avatar != null && !avatar.isEmpty()) {
1556 downloadGroupAvatar(groupId, groupSecretParams, avatar);
1557 }
1558 }
1559 groupInfoV2.setGroup(group);
1560 account.getGroupStore().updateGroup(groupInfoV2);
1561 }
1562
1563 return groupInfoV2;
1564 }
1565
1566 private void storeProfileKeysFromMembers(final DecryptedGroup group) {
1567 for (DecryptedMember member : group.getMembersList()) {
1568 final SignalServiceAddress address = resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil.parseOrThrow(
1569 member.getUuid().toByteArray()), null));
1570 try {
1571 account.getProfileStore()
1572 .storeProfileKey(address, new ProfileKey(member.getProfileKey().toByteArray()));
1573 } catch (InvalidInputException ignored) {
1574 }
1575 }
1576 }
1577
1578 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1579 for (CachedMessage cachedMessage : account.getMessageCache().getCachedMessages()) {
1580 retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
1581 }
1582 }
1583
1584 private void retryFailedReceivedMessage(
1585 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
1586 ) {
1587 SignalServiceEnvelope envelope = cachedMessage.loadEnvelope();
1588 if (envelope == null) {
1589 return;
1590 }
1591 SignalServiceContent content = null;
1592 if (!envelope.isReceipt()) {
1593 try {
1594 content = decryptMessage(envelope);
1595 } catch (org.whispersystems.libsignal.UntrustedIdentityException e) {
1596 return;
1597 } catch (Exception er) {
1598 // All other errors are not recoverable, so delete the cached message
1599 cachedMessage.delete();
1600 return;
1601 }
1602 List<HandleAction> actions = handleMessage(envelope, content, ignoreAttachments);
1603 for (HandleAction action : actions) {
1604 try {
1605 action.execute(this);
1606 } catch (Throwable e) {
1607 logger.warn("Message action failed.", e);
1608 }
1609 }
1610 }
1611 account.save();
1612 handler.handleMessage(envelope, content, null);
1613 cachedMessage.delete();
1614 }
1615
1616 public void receiveMessages(
1617 long timeout,
1618 TimeUnit unit,
1619 boolean returnOnTimeout,
1620 boolean ignoreAttachments,
1621 ReceiveMessageHandler handler
1622 ) throws IOException {
1623 retryFailedReceivedMessages(handler, ignoreAttachments);
1624
1625 Set<HandleAction> queuedActions = null;
1626
1627 final SignalServiceMessagePipe messagePipe = getOrCreateMessagePipe();
1628
1629 boolean hasCaughtUpWithOldMessages = false;
1630
1631 while (true) {
1632 SignalServiceEnvelope envelope;
1633 SignalServiceContent content = null;
1634 Exception exception = null;
1635 final CachedMessage[] cachedMessage = {null};
1636 try {
1637 Optional<SignalServiceEnvelope> result = messagePipe.readOrEmpty(timeout, unit, envelope1 -> {
1638 // store message on disk, before acknowledging receipt to the server
1639 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1);
1640 });
1641 if (result.isPresent()) {
1642 envelope = result.get();
1643 } else {
1644 // Received indicator that server queue is empty
1645 hasCaughtUpWithOldMessages = true;
1646
1647 if (queuedActions != null) {
1648 for (HandleAction action : queuedActions) {
1649 try {
1650 action.execute(this);
1651 } catch (Throwable e) {
1652 logger.warn("Message action failed.", e);
1653 }
1654 }
1655 account.save();
1656 queuedActions.clear();
1657 queuedActions = null;
1658 }
1659
1660 // Continue to wait another timeout for new messages
1661 continue;
1662 }
1663 } catch (TimeoutException e) {
1664 if (returnOnTimeout) return;
1665 continue;
1666 } catch (InvalidVersionException e) {
1667 logger.warn("Error while receiving messages, ignoring: {}", e.getMessage());
1668 continue;
1669 }
1670
1671 if (envelope.hasSource()) {
1672 // Store uuid if we don't have it already
1673 SignalServiceAddress source = envelope.getSourceAddress();
1674 resolveSignalServiceAddress(source);
1675 }
1676 if (!envelope.isReceipt()) {
1677 try {
1678 content = decryptMessage(envelope);
1679 } catch (Exception e) {
1680 exception = e;
1681 }
1682 List<HandleAction> actions = handleMessage(envelope, content, ignoreAttachments);
1683 if (hasCaughtUpWithOldMessages) {
1684 for (HandleAction action : actions) {
1685 try {
1686 action.execute(this);
1687 } catch (Throwable e) {
1688 logger.warn("Message action failed.", e);
1689 }
1690 }
1691 } else {
1692 if (queuedActions == null) {
1693 queuedActions = new HashSet<>();
1694 }
1695 queuedActions.addAll(actions);
1696 }
1697 }
1698 account.save();
1699 if (isMessageBlocked(envelope, content)) {
1700 logger.info("Ignoring a message from blocked user/group: {}", envelope.getTimestamp());
1701 } else if (isNotAGroupMember(envelope, content)) {
1702 logger.info("Ignoring a message from a non group member: {}", envelope.getTimestamp());
1703 } else {
1704 handler.handleMessage(envelope, content, exception);
1705 }
1706 if (!(exception instanceof org.whispersystems.libsignal.UntrustedIdentityException)) {
1707 if (cachedMessage[0] != null) {
1708 cachedMessage[0].delete();
1709 }
1710 }
1711 }
1712 }
1713
1714 private boolean isMessageBlocked(
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 ContactInfo sourceContact = account.getContactStore().getContact(source);
1726 if (sourceContact != null && sourceContact.blocked) {
1727 return true;
1728 }
1729
1730 if (content != null && content.getDataMessage().isPresent()) {
1731 SignalServiceDataMessage message = content.getDataMessage().get();
1732 if (message.getGroupContext().isPresent()) {
1733 GroupId groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1734 GroupInfo group = getGroup(groupId);
1735 if (group != null && group.isBlocked()) {
1736 return true;
1737 }
1738 }
1739 }
1740 return false;
1741 }
1742
1743 private boolean isNotAGroupMember(
1744 SignalServiceEnvelope envelope, SignalServiceContent content
1745 ) {
1746 SignalServiceAddress source;
1747 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1748 source = envelope.getSourceAddress();
1749 } else if (content != null) {
1750 source = content.getSender();
1751 } else {
1752 return false;
1753 }
1754
1755 if (content != null && content.getDataMessage().isPresent()) {
1756 SignalServiceDataMessage message = content.getDataMessage().get();
1757 if (message.getGroupContext().isPresent()) {
1758 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1759 SignalServiceGroup groupInfo = message.getGroupContext().get().getGroupV1().get();
1760 if (groupInfo.getType() == SignalServiceGroup.Type.QUIT) {
1761 return false;
1762 }
1763 }
1764 GroupId groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1765 GroupInfo group = getGroup(groupId);
1766 if (group != null && !group.isMember(source)) {
1767 return true;
1768 }
1769 }
1770 }
1771 return false;
1772 }
1773
1774 private List<HandleAction> handleMessage(
1775 SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments
1776 ) {
1777 List<HandleAction> actions = new ArrayList<>();
1778 if (content != null) {
1779 final SignalServiceAddress sender;
1780 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1781 sender = envelope.getSourceAddress();
1782 } else {
1783 sender = content.getSender();
1784 }
1785 // Store uuid if we don't have it already
1786 resolveSignalServiceAddress(sender);
1787
1788 if (content.getDataMessage().isPresent()) {
1789 SignalServiceDataMessage message = content.getDataMessage().get();
1790
1791 if (content.isNeedsReceipt()) {
1792 actions.add(new SendReceiptAction(sender, message.getTimestamp()));
1793 }
1794
1795 actions.addAll(handleSignalServiceDataMessage(message,
1796 false,
1797 sender,
1798 account.getSelfAddress(),
1799 ignoreAttachments));
1800 }
1801 if (content.getSyncMessage().isPresent()) {
1802 account.setMultiDevice(true);
1803 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
1804 if (syncMessage.getSent().isPresent()) {
1805 SentTranscriptMessage message = syncMessage.getSent().get();
1806 final SignalServiceAddress destination = message.getDestination().orNull();
1807 actions.addAll(handleSignalServiceDataMessage(message.getMessage(),
1808 true,
1809 sender,
1810 destination,
1811 ignoreAttachments));
1812 }
1813 if (syncMessage.getRequest().isPresent()) {
1814 RequestMessage rm = syncMessage.getRequest().get();
1815 if (rm.isContactsRequest()) {
1816 actions.add(SendSyncContactsAction.create());
1817 }
1818 if (rm.isGroupsRequest()) {
1819 actions.add(SendSyncGroupsAction.create());
1820 }
1821 if (rm.isBlockedListRequest()) {
1822 actions.add(SendSyncBlockedListAction.create());
1823 }
1824 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1825 }
1826 if (syncMessage.getGroups().isPresent()) {
1827 File tmpFile = null;
1828 try {
1829 tmpFile = IOUtils.createTempFile();
1830 final SignalServiceAttachment groupsMessage = syncMessage.getGroups().get();
1831 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(groupsMessage.asPointer(),
1832 tmpFile)) {
1833 DeviceGroupsInputStream s = new DeviceGroupsInputStream(attachmentAsStream);
1834 DeviceGroup g;
1835 while ((g = s.read()) != null) {
1836 GroupInfoV1 syncGroup = account.getGroupStore()
1837 .getOrCreateGroupV1(GroupId.v1(g.getId()));
1838 if (syncGroup != null) {
1839 if (g.getName().isPresent()) {
1840 syncGroup.name = g.getName().get();
1841 }
1842 syncGroup.addMembers(g.getMembers()
1843 .stream()
1844 .map(this::resolveSignalServiceAddress)
1845 .collect(Collectors.toSet()));
1846 if (!g.isActive()) {
1847 syncGroup.removeMember(account.getSelfAddress());
1848 } else {
1849 // Add ourself to the member set as it's marked as active
1850 syncGroup.addMembers(List.of(account.getSelfAddress()));
1851 }
1852 syncGroup.blocked = g.isBlocked();
1853 if (g.getColor().isPresent()) {
1854 syncGroup.color = g.getColor().get();
1855 }
1856
1857 if (g.getAvatar().isPresent()) {
1858 downloadGroupAvatar(g.getAvatar().get(), syncGroup.getGroupId());
1859 }
1860 syncGroup.inboxPosition = g.getInboxPosition().orNull();
1861 syncGroup.archived = g.isArchived();
1862 account.getGroupStore().updateGroup(syncGroup);
1863 }
1864 }
1865 }
1866 } catch (Exception e) {
1867 logger.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1868 tmpFile,
1869 e.getMessage());
1870 } finally {
1871 if (tmpFile != null) {
1872 try {
1873 Files.delete(tmpFile.toPath());
1874 } catch (IOException e) {
1875 logger.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1876 tmpFile,
1877 e.getMessage());
1878 }
1879 }
1880 }
1881 }
1882 if (syncMessage.getBlockedList().isPresent()) {
1883 final BlockedListMessage blockedListMessage = syncMessage.getBlockedList().get();
1884 for (SignalServiceAddress address : blockedListMessage.getAddresses()) {
1885 setContactBlocked(resolveSignalServiceAddress(address), true);
1886 }
1887 for (GroupId groupId : blockedListMessage.getGroupIds()
1888 .stream()
1889 .map(GroupId::unknownVersion)
1890 .collect(Collectors.toSet())) {
1891 try {
1892 setGroupBlocked(groupId, true);
1893 } catch (GroupNotFoundException e) {
1894 logger.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1895 groupId.toBase64());
1896 }
1897 }
1898 }
1899 if (syncMessage.getContacts().isPresent()) {
1900 File tmpFile = null;
1901 try {
1902 tmpFile = IOUtils.createTempFile();
1903 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
1904 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream()
1905 .asPointer(), tmpFile)) {
1906 DeviceContactsInputStream s = new DeviceContactsInputStream(attachmentAsStream);
1907 if (contactsMessage.isComplete()) {
1908 account.getContactStore().clear();
1909 }
1910 DeviceContact c;
1911 while ((c = s.read()) != null) {
1912 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
1913 account.setProfileKey(c.getProfileKey().get());
1914 }
1915 final SignalServiceAddress address = resolveSignalServiceAddress(c.getAddress());
1916 ContactInfo contact = account.getContactStore().getContact(address);
1917 if (contact == null) {
1918 contact = new ContactInfo(address);
1919 }
1920 if (c.getName().isPresent()) {
1921 contact.name = c.getName().get();
1922 }
1923 if (c.getColor().isPresent()) {
1924 contact.color = c.getColor().get();
1925 }
1926 if (c.getProfileKey().isPresent()) {
1927 account.getProfileStore().storeProfileKey(address, c.getProfileKey().get());
1928 }
1929 if (c.getVerified().isPresent()) {
1930 final VerifiedMessage verifiedMessage = c.getVerified().get();
1931 account.getSignalProtocolStore()
1932 .setIdentityTrustLevel(verifiedMessage.getDestination(),
1933 verifiedMessage.getIdentityKey(),
1934 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1935 }
1936 if (c.getExpirationTimer().isPresent()) {
1937 contact.messageExpirationTime = c.getExpirationTimer().get();
1938 }
1939 contact.blocked = c.isBlocked();
1940 contact.inboxPosition = c.getInboxPosition().orNull();
1941 contact.archived = c.isArchived();
1942 account.getContactStore().updateContact(contact);
1943
1944 if (c.getAvatar().isPresent()) {
1945 downloadContactAvatar(c.getAvatar().get(), contact.getAddress());
1946 }
1947 }
1948 }
1949 } catch (Exception e) {
1950 logger.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1951 tmpFile,
1952 e.getMessage());
1953 } finally {
1954 if (tmpFile != null) {
1955 try {
1956 Files.delete(tmpFile.toPath());
1957 } catch (IOException e) {
1958 logger.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1959 tmpFile,
1960 e.getMessage());
1961 }
1962 }
1963 }
1964 }
1965 if (syncMessage.getVerified().isPresent()) {
1966 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
1967 account.getSignalProtocolStore()
1968 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage.getDestination()),
1969 verifiedMessage.getIdentityKey(),
1970 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1971 }
1972 if (syncMessage.getStickerPackOperations().isPresent()) {
1973 final List<StickerPackOperationMessage> stickerPackOperationMessages = syncMessage.getStickerPackOperations()
1974 .get();
1975 for (StickerPackOperationMessage m : stickerPackOperationMessages) {
1976 if (!m.getPackId().isPresent()) {
1977 continue;
1978 }
1979 Sticker sticker = account.getStickerStore().getSticker(m.getPackId().get());
1980 if (sticker == null) {
1981 if (!m.getPackKey().isPresent()) {
1982 continue;
1983 }
1984 sticker = new Sticker(m.getPackId().get(), m.getPackKey().get());
1985 }
1986 sticker.setInstalled(!m.getType().isPresent()
1987 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL);
1988 account.getStickerStore().updateSticker(sticker);
1989 }
1990 }
1991 if (syncMessage.getConfiguration().isPresent()) {
1992 // TODO
1993 }
1994 }
1995 }
1996 return actions;
1997 }
1998
1999 private void downloadContactAvatar(SignalServiceAttachment avatar, SignalServiceAddress address) {
2000 try {
2001 avatarStore.storeContactAvatar(address, outputStream -> retrieveAttachment(avatar, outputStream));
2002 } catch (IOException e) {
2003 logger.warn("Failed to download avatar for contact {}, ignoring: {}", address, e.getMessage());
2004 }
2005 }
2006
2007 private void downloadGroupAvatar(SignalServiceAttachment avatar, GroupId groupId) {
2008 try {
2009 avatarStore.storeGroupAvatar(groupId, outputStream -> retrieveAttachment(avatar, outputStream));
2010 } catch (IOException e) {
2011 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2012 }
2013 }
2014
2015 private void downloadGroupAvatar(GroupId groupId, GroupSecretParams groupSecretParams, String cdnKey) {
2016 try {
2017 avatarStore.storeGroupAvatar(groupId,
2018 outputStream -> retrieveGroupV2Avatar(groupSecretParams, cdnKey, outputStream));
2019 } catch (IOException e) {
2020 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2021 }
2022 }
2023
2024 private void downloadProfileAvatar(
2025 SignalServiceAddress address, String avatarPath, ProfileKey profileKey
2026 ) {
2027 try {
2028 avatarStore.storeProfileAvatar(address,
2029 outputStream -> retrieveProfileAvatar(avatarPath, profileKey, outputStream));
2030 } catch (Throwable e) {
2031 logger.warn("Failed to download profile avatar, ignoring: {}", e.getMessage());
2032 }
2033 }
2034
2035 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
2036 return attachmentStore.getAttachmentFile(attachmentId);
2037 }
2038
2039 private void downloadAttachment(final SignalServiceAttachment attachment) {
2040 if (!attachment.isPointer()) {
2041 logger.warn("Invalid state, can't store an attachment stream.");
2042 }
2043
2044 SignalServiceAttachmentPointer pointer = attachment.asPointer();
2045 if (pointer.getPreview().isPresent()) {
2046 final byte[] preview = pointer.getPreview().get();
2047 try {
2048 attachmentStore.storeAttachmentPreview(pointer.getRemoteId(),
2049 outputStream -> outputStream.write(preview, 0, preview.length));
2050 } catch (IOException e) {
2051 logger.warn("Failed to download attachment preview, ignoring: {}", e.getMessage());
2052 }
2053 }
2054
2055 try {
2056 attachmentStore.storeAttachment(pointer.getRemoteId(),
2057 outputStream -> retrieveAttachmentPointer(pointer, outputStream));
2058 } catch (IOException e) {
2059 logger.warn("Failed to download attachment ({}), ignoring: {}", pointer.getRemoteId(), e.getMessage());
2060 }
2061 }
2062
2063 private void retrieveGroupV2Avatar(
2064 GroupSecretParams groupSecretParams, String cdnKey, OutputStream outputStream
2065 ) throws IOException {
2066 GroupsV2Operations.GroupOperations groupOperations = groupsV2Operations.forGroup(groupSecretParams);
2067
2068 File tmpFile = IOUtils.createTempFile();
2069 try (InputStream input = messageReceiver.retrieveGroupsV2ProfileAvatar(cdnKey,
2070 tmpFile,
2071 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2072 byte[] encryptedData = IOUtils.readFully(input);
2073
2074 byte[] decryptedData = groupOperations.decryptAvatar(encryptedData);
2075 outputStream.write(decryptedData);
2076 } finally {
2077 try {
2078 Files.delete(tmpFile.toPath());
2079 } catch (IOException e) {
2080 logger.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2081 tmpFile,
2082 e.getMessage());
2083 }
2084 }
2085 }
2086
2087 private void retrieveProfileAvatar(
2088 String avatarPath, ProfileKey profileKey, OutputStream outputStream
2089 ) throws IOException {
2090 File tmpFile = IOUtils.createTempFile();
2091 try (InputStream input = messageReceiver.retrieveProfileAvatar(avatarPath,
2092 tmpFile,
2093 profileKey,
2094 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2095 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2096 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
2097 } finally {
2098 try {
2099 Files.delete(tmpFile.toPath());
2100 } catch (IOException e) {
2101 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2102 tmpFile,
2103 e.getMessage());
2104 }
2105 }
2106 }
2107
2108 private void retrieveAttachment(
2109 final SignalServiceAttachment attachment, final OutputStream outputStream
2110 ) throws IOException {
2111 if (attachment.isPointer()) {
2112 SignalServiceAttachmentPointer pointer = attachment.asPointer();
2113 retrieveAttachmentPointer(pointer, outputStream);
2114 } else {
2115 SignalServiceAttachmentStream stream = attachment.asStream();
2116 IOUtils.copyStream(stream.getInputStream(), outputStream);
2117 }
2118 }
2119
2120 private void retrieveAttachmentPointer(
2121 SignalServiceAttachmentPointer pointer, OutputStream outputStream
2122 ) throws IOException {
2123 File tmpFile = IOUtils.createTempFile();
2124 try (InputStream input = retrieveAttachmentAsStream(pointer, tmpFile)) {
2125 IOUtils.copyStream(input, outputStream);
2126 } catch (MissingConfigurationException | InvalidMessageException e) {
2127 throw new IOException(e);
2128 } finally {
2129 try {
2130 Files.delete(tmpFile.toPath());
2131 } catch (IOException e) {
2132 logger.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2133 tmpFile,
2134 e.getMessage());
2135 }
2136 }
2137 }
2138
2139 private InputStream retrieveAttachmentAsStream(
2140 SignalServiceAttachmentPointer pointer, File tmpFile
2141 ) throws IOException, InvalidMessageException, MissingConfigurationException {
2142 return messageReceiver.retrieveAttachment(pointer, tmpFile, ServiceConfig.MAX_ATTACHMENT_SIZE);
2143 }
2144
2145 void sendGroups() throws IOException, UntrustedIdentityException {
2146 File groupsFile = IOUtils.createTempFile();
2147
2148 try {
2149 try (OutputStream fos = new FileOutputStream(groupsFile)) {
2150 DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(fos);
2151 for (GroupInfo record : getGroups()) {
2152 if (record instanceof GroupInfoV1) {
2153 GroupInfoV1 groupInfo = (GroupInfoV1) record;
2154 out.write(new DeviceGroup(groupInfo.getGroupId().serialize(),
2155 Optional.fromNullable(groupInfo.name),
2156 new ArrayList<>(groupInfo.getMembers()),
2157 createGroupAvatarAttachment(groupInfo.getGroupId()),
2158 groupInfo.isMember(account.getSelfAddress()),
2159 Optional.of(groupInfo.messageExpirationTime),
2160 Optional.fromNullable(groupInfo.color),
2161 groupInfo.blocked,
2162 Optional.fromNullable(groupInfo.inboxPosition),
2163 groupInfo.archived));
2164 }
2165 }
2166 }
2167
2168 if (groupsFile.exists() && groupsFile.length() > 0) {
2169 try (FileInputStream groupsFileStream = new FileInputStream(groupsFile)) {
2170 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
2171 .withStream(groupsFileStream)
2172 .withContentType("application/octet-stream")
2173 .withLength(groupsFile.length())
2174 .build();
2175
2176 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
2177 }
2178 }
2179 } finally {
2180 try {
2181 Files.delete(groupsFile.toPath());
2182 } catch (IOException e) {
2183 logger.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile, e.getMessage());
2184 }
2185 }
2186 }
2187
2188 public void sendContacts() throws IOException, UntrustedIdentityException {
2189 File contactsFile = IOUtils.createTempFile();
2190
2191 try {
2192 try (OutputStream fos = new FileOutputStream(contactsFile)) {
2193 DeviceContactsOutputStream out = new DeviceContactsOutputStream(fos);
2194 for (ContactInfo record : account.getContactStore().getContacts()) {
2195 VerifiedMessage verifiedMessage = null;
2196 IdentityInfo currentIdentity = account.getSignalProtocolStore().getIdentity(record.getAddress());
2197 if (currentIdentity != null) {
2198 verifiedMessage = new VerifiedMessage(record.getAddress(),
2199 currentIdentity.getIdentityKey(),
2200 currentIdentity.getTrustLevel().toVerifiedState(),
2201 currentIdentity.getDateAdded().getTime());
2202 }
2203
2204 ProfileKey profileKey = account.getProfileStore().getProfileKey(record.getAddress());
2205 out.write(new DeviceContact(record.getAddress(),
2206 Optional.fromNullable(record.name),
2207 createContactAvatarAttachment(record.getAddress()),
2208 Optional.fromNullable(record.color),
2209 Optional.fromNullable(verifiedMessage),
2210 Optional.fromNullable(profileKey),
2211 record.blocked,
2212 Optional.of(record.messageExpirationTime),
2213 Optional.fromNullable(record.inboxPosition),
2214 record.archived));
2215 }
2216
2217 if (account.getProfileKey() != null) {
2218 // Send our own profile key as well
2219 out.write(new DeviceContact(account.getSelfAddress(),
2220 Optional.absent(),
2221 Optional.absent(),
2222 Optional.absent(),
2223 Optional.absent(),
2224 Optional.of(account.getProfileKey()),
2225 false,
2226 Optional.absent(),
2227 Optional.absent(),
2228 false));
2229 }
2230 }
2231
2232 if (contactsFile.exists() && contactsFile.length() > 0) {
2233 try (FileInputStream contactsFileStream = new FileInputStream(contactsFile)) {
2234 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
2235 .withStream(contactsFileStream)
2236 .withContentType("application/octet-stream")
2237 .withLength(contactsFile.length())
2238 .build();
2239
2240 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
2241 }
2242 }
2243 } finally {
2244 try {
2245 Files.delete(contactsFile.toPath());
2246 } catch (IOException e) {
2247 logger.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile, e.getMessage());
2248 }
2249 }
2250 }
2251
2252 void sendBlockedList() throws IOException, UntrustedIdentityException {
2253 List<SignalServiceAddress> addresses = new ArrayList<>();
2254 for (ContactInfo record : account.getContactStore().getContacts()) {
2255 if (record.blocked) {
2256 addresses.add(record.getAddress());
2257 }
2258 }
2259 List<byte[]> groupIds = new ArrayList<>();
2260 for (GroupInfo record : getGroups()) {
2261 if (record.isBlocked()) {
2262 groupIds.add(record.getGroupId().serialize());
2263 }
2264 }
2265 sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
2266 }
2267
2268 private void sendVerifiedMessage(
2269 SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel
2270 ) throws IOException, UntrustedIdentityException {
2271 VerifiedMessage verifiedMessage = new VerifiedMessage(destination,
2272 identityKey,
2273 trustLevel.toVerifiedState(),
2274 System.currentTimeMillis());
2275 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
2276 }
2277
2278 public List<ContactInfo> getContacts() {
2279 return account.getContactStore().getContacts();
2280 }
2281
2282 public ContactInfo getContact(String number) {
2283 return account.getContactStore().getContact(Utils.getSignalServiceAddressFromIdentifier(number));
2284 }
2285
2286 public GroupInfo getGroup(GroupId groupId) {
2287 final GroupInfo group = account.getGroupStore().getGroup(groupId);
2288 if (group instanceof GroupInfoV2 && ((GroupInfoV2) group).getGroup() == null) {
2289 final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(((GroupInfoV2) group).getMasterKey());
2290 ((GroupInfoV2) group).setGroup(groupHelper.getDecryptedGroup(groupSecretParams));
2291 account.getGroupStore().updateGroup(group);
2292 }
2293 return group;
2294 }
2295
2296 public List<IdentityInfo> getIdentities() {
2297 return account.getSignalProtocolStore().getIdentities();
2298 }
2299
2300 public List<IdentityInfo> getIdentities(String number) throws InvalidNumberException {
2301 return account.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number));
2302 }
2303
2304 /**
2305 * Trust this the identity with this fingerprint
2306 *
2307 * @param name username of the identity
2308 * @param fingerprint Fingerprint
2309 */
2310 public boolean trustIdentityVerified(String name, byte[] fingerprint) throws InvalidNumberException {
2311 SignalServiceAddress address = canonicalizeAndResolveSignalServiceAddress(name);
2312 List<IdentityInfo> ids = account.getSignalProtocolStore().getIdentities(address);
2313 if (ids == null) {
2314 return false;
2315 }
2316 for (IdentityInfo id : ids) {
2317 if (!Arrays.equals(id.getIdentityKey().serialize(), fingerprint)) {
2318 continue;
2319 }
2320
2321 account.getSignalProtocolStore()
2322 .setIdentityTrustLevel(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2323 try {
2324 sendVerifiedMessage(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2325 } catch (IOException | UntrustedIdentityException e) {
2326 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2327 }
2328 account.save();
2329 return true;
2330 }
2331 return false;
2332 }
2333
2334 /**
2335 * Trust this the identity with this safety number
2336 *
2337 * @param name username of the identity
2338 * @param safetyNumber Safety number
2339 */
2340 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) throws InvalidNumberException {
2341 SignalServiceAddress address = canonicalizeAndResolveSignalServiceAddress(name);
2342 List<IdentityInfo> ids = account.getSignalProtocolStore().getIdentities(address);
2343 if (ids == null) {
2344 return false;
2345 }
2346 for (IdentityInfo id : ids) {
2347 if (!safetyNumber.equals(computeSafetyNumber(address, id.getIdentityKey()))) {
2348 continue;
2349 }
2350
2351 account.getSignalProtocolStore()
2352 .setIdentityTrustLevel(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2353 try {
2354 sendVerifiedMessage(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2355 } catch (IOException | UntrustedIdentityException e) {
2356 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2357 }
2358 account.save();
2359 return true;
2360 }
2361 return false;
2362 }
2363
2364 /**
2365 * Trust all keys of this identity without verification
2366 *
2367 * @param name username of the identity
2368 */
2369 public boolean trustIdentityAllKeys(String name) {
2370 SignalServiceAddress address = resolveSignalServiceAddress(name);
2371 List<IdentityInfo> ids = account.getSignalProtocolStore().getIdentities(address);
2372 if (ids == null) {
2373 return false;
2374 }
2375 for (IdentityInfo id : ids) {
2376 if (id.getTrustLevel() == TrustLevel.UNTRUSTED) {
2377 account.getSignalProtocolStore()
2378 .setIdentityTrustLevel(address, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
2379 try {
2380 sendVerifiedMessage(address, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
2381 } catch (IOException | UntrustedIdentityException e) {
2382 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2383 }
2384 }
2385 }
2386 account.save();
2387 return true;
2388 }
2389
2390 public String computeSafetyNumber(
2391 SignalServiceAddress theirAddress, IdentityKey theirIdentityKey
2392 ) {
2393 return Utils.computeSafetyNumber(ServiceConfig.capabilities.isUuid(),
2394 account.getSelfAddress(),
2395 getIdentityKeyPair().getPublicKey(),
2396 theirAddress,
2397 theirIdentityKey);
2398 }
2399
2400 public SignalServiceAddress canonicalizeAndResolveSignalServiceAddress(String identifier) throws InvalidNumberException {
2401 String canonicalizedNumber = UuidUtil.isUuid(identifier)
2402 ? identifier
2403 : PhoneNumberFormatter.formatNumber(identifier, account.getUsername());
2404 return resolveSignalServiceAddress(canonicalizedNumber);
2405 }
2406
2407 public SignalServiceAddress resolveSignalServiceAddress(String identifier) {
2408 SignalServiceAddress address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2409
2410 return resolveSignalServiceAddress(address);
2411 }
2412
2413 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
2414 if (address.matches(account.getSelfAddress())) {
2415 return account.getSelfAddress();
2416 }
2417
2418 return account.getRecipientStore().resolveServiceAddress(address);
2419 }
2420
2421 @Override
2422 public void close() throws IOException {
2423 close(true);
2424 }
2425
2426 void close(boolean closeAccount) throws IOException {
2427 if (messagePipe != null) {
2428 messagePipe.shutdown();
2429 messagePipe = null;
2430 }
2431
2432 if (unidentifiedMessagePipe != null) {
2433 unidentifiedMessagePipe.shutdown();
2434 unidentifiedMessagePipe = null;
2435 }
2436
2437 if (closeAccount && account != null) {
2438 account.close();
2439 }
2440 account = null;
2441 }
2442
2443 public interface ReceiveMessageHandler {
2444
2445 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
2446 }
2447 }