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