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