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