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