]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/Manager.java
Move more profile functionality to ProfileHelper
[signal-cli] / lib / 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.api.Device;
20 import org.asamk.signal.manager.api.Message;
21 import org.asamk.signal.manager.api.RecipientIdentifier;
22 import org.asamk.signal.manager.api.SendGroupMessageResults;
23 import org.asamk.signal.manager.api.SendMessageResults;
24 import org.asamk.signal.manager.api.TypingAction;
25 import org.asamk.signal.manager.config.ServiceConfig;
26 import org.asamk.signal.manager.config.ServiceEnvironment;
27 import org.asamk.signal.manager.config.ServiceEnvironmentConfig;
28 import org.asamk.signal.manager.groups.GroupId;
29 import org.asamk.signal.manager.groups.GroupIdV1;
30 import org.asamk.signal.manager.groups.GroupInviteLinkUrl;
31 import org.asamk.signal.manager.groups.GroupLinkState;
32 import org.asamk.signal.manager.groups.GroupNotFoundException;
33 import org.asamk.signal.manager.groups.GroupPermission;
34 import org.asamk.signal.manager.groups.GroupSendingNotAllowedException;
35 import org.asamk.signal.manager.groups.GroupUtils;
36 import org.asamk.signal.manager.groups.LastGroupAdminException;
37 import org.asamk.signal.manager.groups.NotAGroupMemberException;
38 import org.asamk.signal.manager.helper.GroupHelper;
39 import org.asamk.signal.manager.helper.GroupV2Helper;
40 import org.asamk.signal.manager.helper.PinHelper;
41 import org.asamk.signal.manager.helper.ProfileHelper;
42 import org.asamk.signal.manager.helper.SendHelper;
43 import org.asamk.signal.manager.helper.UnidentifiedAccessHelper;
44 import org.asamk.signal.manager.jobs.Context;
45 import org.asamk.signal.manager.jobs.Job;
46 import org.asamk.signal.manager.jobs.RetrieveStickerPackJob;
47 import org.asamk.signal.manager.storage.SignalAccount;
48 import org.asamk.signal.manager.storage.groups.GroupInfo;
49 import org.asamk.signal.manager.storage.groups.GroupInfoV1;
50 import org.asamk.signal.manager.storage.identities.IdentityInfo;
51 import org.asamk.signal.manager.storage.identities.TrustNewIdentity;
52 import org.asamk.signal.manager.storage.messageCache.CachedMessage;
53 import org.asamk.signal.manager.storage.recipients.Contact;
54 import org.asamk.signal.manager.storage.recipients.Profile;
55 import org.asamk.signal.manager.storage.recipients.RecipientId;
56 import org.asamk.signal.manager.storage.stickers.Sticker;
57 import org.asamk.signal.manager.storage.stickers.StickerPackId;
58 import org.asamk.signal.manager.util.AttachmentUtils;
59 import org.asamk.signal.manager.util.IOUtils;
60 import org.asamk.signal.manager.util.KeyUtils;
61 import org.asamk.signal.manager.util.StickerUtils;
62 import org.asamk.signal.manager.util.Utils;
63 import org.signal.libsignal.metadata.ProtocolInvalidMessageException;
64 import org.signal.libsignal.metadata.ProtocolUntrustedIdentityException;
65 import org.signal.zkgroup.InvalidInputException;
66 import org.signal.zkgroup.profiles.ProfileKey;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69 import org.whispersystems.libsignal.IdentityKey;
70 import org.whispersystems.libsignal.IdentityKeyPair;
71 import org.whispersystems.libsignal.InvalidKeyException;
72 import org.whispersystems.libsignal.InvalidMessageException;
73 import org.whispersystems.libsignal.ecc.ECPublicKey;
74 import org.whispersystems.libsignal.fingerprint.Fingerprint;
75 import org.whispersystems.libsignal.fingerprint.FingerprintParsingException;
76 import org.whispersystems.libsignal.fingerprint.FingerprintVersionMismatchException;
77 import org.whispersystems.libsignal.state.PreKeyRecord;
78 import org.whispersystems.libsignal.state.SignedPreKeyRecord;
79 import org.whispersystems.libsignal.util.Pair;
80 import org.whispersystems.libsignal.util.guava.Optional;
81 import org.whispersystems.signalservice.api.SignalSessionLock;
82 import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
83 import org.whispersystems.signalservice.api.groupsv2.GroupLinkNotActiveException;
84 import org.whispersystems.signalservice.api.messages.SendMessageResult;
85 import org.whispersystems.signalservice.api.messages.SignalServiceAttachment;
86 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentPointer;
87 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentRemoteId;
88 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentStream;
89 import org.whispersystems.signalservice.api.messages.SignalServiceContent;
90 import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
91 import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
92 import org.whispersystems.signalservice.api.messages.SignalServiceGroup;
93 import org.whispersystems.signalservice.api.messages.SignalServiceReceiptMessage;
94 import org.whispersystems.signalservice.api.messages.SignalServiceTypingMessage;
95 import org.whispersystems.signalservice.api.messages.multidevice.BlockedListMessage;
96 import org.whispersystems.signalservice.api.messages.multidevice.ContactsMessage;
97 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContact;
98 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsInputStream;
99 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsOutputStream;
100 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroup;
101 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroupsInputStream;
102 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroupsOutputStream;
103 import org.whispersystems.signalservice.api.messages.multidevice.RequestMessage;
104 import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage;
105 import org.whispersystems.signalservice.api.messages.multidevice.StickerPackOperationMessage;
106 import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage;
107 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
108 import org.whispersystems.signalservice.api.push.exceptions.MissingConfigurationException;
109 import org.whispersystems.signalservice.api.util.DeviceNameUtil;
110 import org.whispersystems.signalservice.api.util.InvalidNumberException;
111 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
112 import org.whispersystems.signalservice.api.websocket.WebSocketUnavailableException;
113 import org.whispersystems.signalservice.internal.contacts.crypto.Quote;
114 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedQuoteException;
115 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedResponseException;
116 import org.whispersystems.signalservice.internal.push.SignalServiceProtos;
117 import org.whispersystems.signalservice.internal.util.DynamicCredentialsProvider;
118 import org.whispersystems.signalservice.internal.util.Hex;
119 import org.whispersystems.signalservice.internal.util.Util;
120
121 import java.io.Closeable;
122 import java.io.File;
123 import java.io.FileInputStream;
124 import java.io.FileOutputStream;
125 import java.io.IOException;
126 import java.io.InputStream;
127 import java.io.OutputStream;
128 import java.net.URI;
129 import java.net.URISyntaxException;
130 import java.net.URLEncoder;
131 import java.nio.charset.StandardCharsets;
132 import java.nio.file.Files;
133 import java.security.SignatureException;
134 import java.util.ArrayList;
135 import java.util.Arrays;
136 import java.util.Collection;
137 import java.util.Date;
138 import java.util.HashMap;
139 import java.util.HashSet;
140 import java.util.List;
141 import java.util.Map;
142 import java.util.Set;
143 import java.util.UUID;
144 import java.util.concurrent.ExecutorService;
145 import java.util.concurrent.Executors;
146 import java.util.concurrent.TimeUnit;
147 import java.util.concurrent.TimeoutException;
148 import java.util.concurrent.locks.ReentrantLock;
149 import java.util.function.Function;
150 import java.util.stream.Collectors;
151
152 import static org.asamk.signal.manager.config.ServiceConfig.capabilities;
153
154 public class Manager implements Closeable {
155
156 private final static Logger logger = LoggerFactory.getLogger(Manager.class);
157
158 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
159 private final SignalDependencies dependencies;
160
161 private SignalAccount account;
162
163 private final ExecutorService executor = Executors.newCachedThreadPool();
164
165 private final ProfileHelper profileHelper;
166 private final PinHelper pinHelper;
167 private final SendHelper sendHelper;
168 private final GroupHelper groupHelper;
169
170 private final AvatarStore avatarStore;
171 private final AttachmentStore attachmentStore;
172 private final StickerPackStore stickerPackStore;
173 private final SignalSessionLock sessionLock = new SignalSessionLock() {
174 private final ReentrantLock LEGACY_LOCK = new ReentrantLock();
175
176 @Override
177 public Lock acquire() {
178 LEGACY_LOCK.lock();
179 return LEGACY_LOCK::unlock;
180 }
181 };
182
183 Manager(
184 SignalAccount account,
185 PathConfig pathConfig,
186 ServiceEnvironmentConfig serviceEnvironmentConfig,
187 String userAgent
188 ) {
189 this.account = account;
190 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
191
192 final var credentialsProvider = new DynamicCredentialsProvider(account.getUuid(),
193 account.getUsername(),
194 account.getPassword(),
195 account.getDeviceId());
196 this.dependencies = new SignalDependencies(account.getSelfAddress(),
197 serviceEnvironmentConfig,
198 userAgent,
199 credentialsProvider,
200 account.getSignalProtocolStore(),
201 executor,
202 sessionLock);
203 this.avatarStore = new AvatarStore(pathConfig.getAvatarsPath());
204 this.attachmentStore = new AttachmentStore(pathConfig.getAttachmentsPath());
205 this.stickerPackStore = new StickerPackStore(pathConfig.getStickerPacksPath());
206
207 this.pinHelper = new PinHelper(dependencies.getKeyBackupService());
208 final var unidentifiedAccessHelper = new UnidentifiedAccessHelper(account::getProfileKey,
209 account.getProfileStore()::getProfileKey,
210 this::getRecipientProfile,
211 this::getSenderCertificate);
212 this.profileHelper = new ProfileHelper(account,
213 dependencies,
214 avatarStore,
215 account.getProfileStore()::getProfileKey,
216 unidentifiedAccessHelper::getAccessFor,
217 dependencies::getProfileService,
218 dependencies::getMessageReceiver,
219 this::resolveSignalServiceAddress);
220 final GroupV2Helper groupV2Helper = new GroupV2Helper(profileHelper::getRecipientProfileKeyCredential,
221 this::getRecipientProfile,
222 account::getSelfRecipientId,
223 dependencies.getGroupsV2Operations(),
224 dependencies.getGroupsV2Api(),
225 this::resolveSignalServiceAddress);
226 this.sendHelper = new SendHelper(account,
227 dependencies,
228 unidentifiedAccessHelper,
229 this::resolveSignalServiceAddress,
230 this::resolveRecipient,
231 this::handleIdentityFailure,
232 this::getGroup,
233 this::refreshRegisteredUser);
234 this.groupHelper = new GroupHelper(account,
235 dependencies,
236 sendHelper,
237 groupV2Helper,
238 avatarStore,
239 this::resolveSignalServiceAddress,
240 this::resolveRecipient);
241 }
242
243 public String getUsername() {
244 return account.getUsername();
245 }
246
247 private SignalServiceAddress getSelfAddress() {
248 return account.getSelfAddress();
249 }
250
251 public RecipientId getSelfRecipientId() {
252 return account.getSelfRecipientId();
253 }
254
255 private IdentityKeyPair getIdentityKeyPair() {
256 return account.getIdentityKeyPair();
257 }
258
259 public int getDeviceId() {
260 return account.getDeviceId();
261 }
262
263 public static Manager init(
264 String username,
265 File settingsPath,
266 ServiceEnvironment serviceEnvironment,
267 String userAgent,
268 final TrustNewIdentity trustNewIdentity
269 ) throws IOException, NotRegisteredException {
270 var pathConfig = PathConfig.createDefault(settingsPath);
271
272 if (!SignalAccount.userExists(pathConfig.getDataPath(), username)) {
273 throw new NotRegisteredException();
274 }
275
276 var account = SignalAccount.load(pathConfig.getDataPath(), username, true, trustNewIdentity);
277
278 if (!account.isRegistered()) {
279 throw new NotRegisteredException();
280 }
281
282 final var serviceEnvironmentConfig = ServiceConfig.getServiceEnvironmentConfig(serviceEnvironment, userAgent);
283
284 return new Manager(account, pathConfig, serviceEnvironmentConfig, userAgent);
285 }
286
287 public static List<String> getAllLocalUsernames(File settingsPath) {
288 var pathConfig = PathConfig.createDefault(settingsPath);
289 final var dataPath = pathConfig.getDataPath();
290 final var files = dataPath.listFiles();
291
292 if (files == null) {
293 return List.of();
294 }
295
296 return Arrays.stream(files)
297 .filter(File::isFile)
298 .map(File::getName)
299 .filter(file -> PhoneNumberFormatter.isValidNumber(file, null))
300 .collect(Collectors.toList());
301 }
302
303 public void checkAccountState() throws IOException {
304 if (account.getLastReceiveTimestamp() == 0) {
305 logger.info("The Signal protocol expects that incoming messages are regularly received.");
306 } else {
307 var diffInMilliseconds = System.currentTimeMillis() - account.getLastReceiveTimestamp();
308 long days = TimeUnit.DAYS.convert(diffInMilliseconds, TimeUnit.MILLISECONDS);
309 if (days > 7) {
310 logger.warn(
311 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
312 days);
313 }
314 }
315 if (dependencies.getAccountManager().getPreKeysCount() < ServiceConfig.PREKEY_MINIMUM_COUNT) {
316 refreshPreKeys();
317 }
318 if (account.getUuid() == null) {
319 account.setUuid(dependencies.getAccountManager().getOwnUuid());
320 }
321 updateAccountAttributes();
322 }
323
324 /**
325 * This is used for checking a set of phone numbers for registration on Signal
326 *
327 * @param numbers The set of phone number in question
328 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
329 * @throws IOException if its unable to get the contacts to check if they're registered
330 */
331 public Map<String, Pair<String, UUID>> areUsersRegistered(Set<String> numbers) throws IOException {
332 Map<String, String> canonicalizedNumbers = numbers.stream().collect(Collectors.toMap(n -> n, n -> {
333 try {
334 return canonicalizePhoneNumber(n);
335 } catch (InvalidNumberException e) {
336 return "";
337 }
338 }));
339
340 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
341 var contactDetails = getRegisteredUsers(canonicalizedNumbers.values()
342 .stream()
343 .filter(s -> !s.isEmpty())
344 .collect(Collectors.toSet()));
345
346 return numbers.stream().collect(Collectors.toMap(n -> n, n -> {
347 final var number = canonicalizedNumbers.get(n);
348 final var uuid = contactDetails.get(number);
349 return new Pair<>(number.isEmpty() ? null : number, uuid);
350 }));
351 }
352
353 public void updateAccountAttributes() throws IOException {
354 dependencies.getAccountManager()
355 .setAccountAttributes(account.getEncryptedDeviceName(),
356 null,
357 account.getLocalRegistrationId(),
358 true,
359 // set legacy pin only if no KBS master key is set
360 account.getPinMasterKey() == null ? account.getRegistrationLockPin() : null,
361 account.getPinMasterKey() == null ? null : account.getPinMasterKey().deriveRegistrationLock(),
362 account.getSelfUnidentifiedAccessKey(),
363 account.isUnrestrictedUnidentifiedAccess(),
364 capabilities,
365 account.isDiscoverableByPhoneNumber());
366 }
367
368 /**
369 * @param givenName if null, the previous givenName will be kept
370 * @param familyName if null, the previous familyName will be kept
371 * @param about if null, the previous about text will be kept
372 * @param aboutEmoji if null, the previous about emoji will be kept
373 * @param avatar if avatar is null the image from the local avatar store is used (if present),
374 */
375 public void setProfile(
376 String givenName, final String familyName, String about, String aboutEmoji, Optional<File> avatar
377 ) throws IOException {
378 profileHelper.setProfile(givenName, familyName, about, aboutEmoji, avatar);
379
380 sendSyncFetchProfileMessage();
381 }
382
383 private void sendSyncFetchProfileMessage() throws IOException {
384 sendHelper.sendSyncMessage(SignalServiceSyncMessage.forFetchLatest(SignalServiceSyncMessage.FetchType.LOCAL_PROFILE));
385 }
386
387 public void unregister() throws IOException {
388 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
389 // If this is the master device, other users can't send messages to this number anymore.
390 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
391 dependencies.getAccountManager().setGcmId(Optional.absent());
392
393 account.setRegistered(false);
394 }
395
396 public void deleteAccount() throws IOException {
397 dependencies.getAccountManager().deleteAccount();
398
399 account.setRegistered(false);
400 }
401
402 public List<Device> getLinkedDevices() throws IOException {
403 var devices = dependencies.getAccountManager().getDevices();
404 account.setMultiDevice(devices.size() > 1);
405 var identityKey = account.getIdentityKeyPair().getPrivateKey();
406 return devices.stream().map(d -> {
407 String deviceName = d.getName();
408 if (deviceName != null) {
409 try {
410 deviceName = DeviceNameUtil.decryptDeviceName(deviceName, identityKey);
411 } catch (IOException e) {
412 logger.debug("Failed to decrypt device name, maybe plain text?", e);
413 }
414 }
415 return new Device(d.getId(), deviceName, d.getCreated(), d.getLastSeen());
416 }).collect(Collectors.toList());
417 }
418
419 public void removeLinkedDevices(int deviceId) throws IOException {
420 dependencies.getAccountManager().removeDevice(deviceId);
421 var devices = dependencies.getAccountManager().getDevices();
422 account.setMultiDevice(devices.size() > 1);
423 }
424
425 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
426 var info = DeviceLinkInfo.parseDeviceLinkUri(linkUri);
427
428 addDevice(info.deviceIdentifier, info.deviceKey);
429 }
430
431 private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
432 var identityKeyPair = getIdentityKeyPair();
433 var verificationCode = dependencies.getAccountManager().getNewDeviceVerificationCode();
434
435 dependencies.getAccountManager()
436 .addDevice(deviceIdentifier,
437 deviceKey,
438 identityKeyPair,
439 Optional.of(account.getProfileKey().serialize()),
440 verificationCode);
441 account.setMultiDevice(true);
442 }
443
444 public void setRegistrationLockPin(Optional<String> pin) throws IOException, UnauthenticatedResponseException {
445 if (!account.isMasterDevice()) {
446 throw new RuntimeException("Only master device can set a PIN");
447 }
448 if (pin.isPresent()) {
449 final var masterKey = account.getPinMasterKey() != null
450 ? account.getPinMasterKey()
451 : KeyUtils.createMasterKey();
452
453 pinHelper.setRegistrationLockPin(pin.get(), masterKey);
454
455 account.setRegistrationLockPin(pin.get(), masterKey);
456 } else {
457 // Remove KBS Pin
458 pinHelper.removeRegistrationLockPin();
459
460 account.setRegistrationLockPin(null, null);
461 }
462 }
463
464 void refreshPreKeys() throws IOException {
465 var oneTimePreKeys = generatePreKeys();
466 final var identityKeyPair = getIdentityKeyPair();
467 var signedPreKeyRecord = generateSignedPreKey(identityKeyPair);
468
469 dependencies.getAccountManager().setPreKeys(identityKeyPair.getPublicKey(), signedPreKeyRecord, oneTimePreKeys);
470 }
471
472 private List<PreKeyRecord> generatePreKeys() {
473 final var offset = account.getPreKeyIdOffset();
474
475 var records = KeyUtils.generatePreKeyRecords(offset, ServiceConfig.PREKEY_BATCH_SIZE);
476 account.addPreKeys(records);
477
478 return records;
479 }
480
481 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
482 final var signedPreKeyId = account.getNextSignedPreKeyId();
483
484 var record = KeyUtils.generateSignedPreKeyRecord(identityKeyPair, signedPreKeyId);
485 account.addSignedPreKey(record);
486
487 return record;
488 }
489
490 public Profile getRecipientProfile(RecipientId recipientId) {
491 return profileHelper.getRecipientProfile(recipientId);
492 }
493
494 public void refreshRecipientProfile(RecipientId recipientId) {
495 profileHelper.refreshRecipientProfile(recipientId);
496 }
497
498 private Optional<SignalServiceAttachmentStream> createContactAvatarAttachment(SignalServiceAddress address) throws IOException {
499 final var streamDetails = avatarStore.retrieveContactAvatar(address);
500 if (streamDetails == null) {
501 return Optional.absent();
502 }
503
504 return Optional.of(AttachmentUtils.createAttachment(streamDetails, Optional.absent()));
505 }
506
507 public List<GroupInfo> getGroups() {
508 return account.getGroupStore().getGroups();
509 }
510
511 public SendGroupMessageResults quitGroup(
512 GroupId groupId, Set<RecipientIdentifier.Single> groupAdmins
513 ) throws GroupNotFoundException, IOException, NotAGroupMemberException, LastGroupAdminException {
514 final var newAdmins = getRecipientIds(groupAdmins);
515 return groupHelper.quitGroup(groupId, newAdmins);
516 }
517
518 public void deleteGroup(GroupId groupId) throws IOException {
519 account.getGroupStore().deleteGroup(groupId);
520 avatarStore.deleteGroupAvatar(groupId);
521 }
522
523 public Pair<GroupId, SendGroupMessageResults> createGroup(
524 String name, Set<RecipientIdentifier.Single> members, File avatarFile
525 ) throws IOException, AttachmentInvalidException {
526 return groupHelper.createGroup(name, members == null ? null : getRecipientIds(members), avatarFile);
527 }
528
529 public SendGroupMessageResults updateGroup(
530 GroupId groupId,
531 String name,
532 String description,
533 Set<RecipientIdentifier.Single> members,
534 Set<RecipientIdentifier.Single> removeMembers,
535 Set<RecipientIdentifier.Single> admins,
536 Set<RecipientIdentifier.Single> removeAdmins,
537 boolean resetGroupLink,
538 GroupLinkState groupLinkState,
539 GroupPermission addMemberPermission,
540 GroupPermission editDetailsPermission,
541 File avatarFile,
542 Integer expirationTimer,
543 Boolean isAnnouncementGroup
544 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException, GroupSendingNotAllowedException {
545 return groupHelper.updateGroup(groupId,
546 name,
547 description,
548 members == null ? null : getRecipientIds(members),
549 removeMembers == null ? null : getRecipientIds(removeMembers),
550 admins == null ? null : getRecipientIds(admins),
551 removeAdmins == null ? null : getRecipientIds(removeAdmins),
552 resetGroupLink,
553 groupLinkState,
554 addMemberPermission,
555 editDetailsPermission,
556 avatarFile,
557 expirationTimer,
558 isAnnouncementGroup);
559 }
560
561 public Pair<GroupId, SendGroupMessageResults> joinGroup(
562 GroupInviteLinkUrl inviteLinkUrl
563 ) throws IOException, GroupLinkNotActiveException {
564 return groupHelper.joinGroup(inviteLinkUrl);
565 }
566
567 public SendMessageResults sendMessage(
568 SignalServiceDataMessage.Builder messageBuilder, Set<RecipientIdentifier> recipients
569 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
570 var results = new HashMap<RecipientIdentifier, List<SendMessageResult>>();
571 long timestamp = System.currentTimeMillis();
572 messageBuilder.withTimestamp(timestamp);
573 for (final var recipient : recipients) {
574 if (recipient instanceof RecipientIdentifier.Single) {
575 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
576 final var result = sendHelper.sendMessage(messageBuilder, recipientId);
577 results.put(recipient, List.of(result));
578 } else if (recipient instanceof RecipientIdentifier.NoteToSelf) {
579 final var result = sendHelper.sendSelfMessage(messageBuilder);
580 results.put(recipient, List.of(result));
581 } else if (recipient instanceof RecipientIdentifier.Group) {
582 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
583 final var result = sendHelper.sendAsGroupMessage(messageBuilder, groupId);
584 results.put(recipient, result);
585 }
586 }
587 return new SendMessageResults(timestamp, results);
588 }
589
590 public void sendTypingMessage(
591 SignalServiceTypingMessage.Action action, Set<RecipientIdentifier> recipients
592 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
593 final var timestamp = System.currentTimeMillis();
594 for (var recipient : recipients) {
595 if (recipient instanceof RecipientIdentifier.Single) {
596 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.absent());
597 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
598 sendHelper.sendTypingMessage(message, recipientId);
599 } else if (recipient instanceof RecipientIdentifier.Group) {
600 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
601 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.of(groupId.serialize()));
602 sendHelper.sendGroupTypingMessage(message, groupId);
603 }
604 }
605 }
606
607 SendGroupMessageResults sendGroupInfoMessage(
608 GroupIdV1 groupId, SignalServiceAddress recipient
609 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, AttachmentInvalidException {
610 final var recipientId = resolveRecipient(recipient);
611 return groupHelper.sendGroupInfoMessage(groupId, recipientId);
612 }
613
614 SendGroupMessageResults sendGroupInfoRequest(
615 GroupIdV1 groupId, SignalServiceAddress recipient
616 ) throws IOException {
617 final var recipientId = resolveRecipient(recipient);
618 return groupHelper.sendGroupInfoRequest(groupId, recipientId);
619 }
620
621 public void sendReadReceipt(
622 RecipientIdentifier.Single sender, List<Long> messageIds
623 ) throws IOException, UntrustedIdentityException {
624 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.READ,
625 messageIds,
626 System.currentTimeMillis());
627
628 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
629 }
630
631 public void sendViewedReceipt(
632 RecipientIdentifier.Single sender, List<Long> messageIds
633 ) throws IOException, UntrustedIdentityException {
634 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.VIEWED,
635 messageIds,
636 System.currentTimeMillis());
637
638 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
639 }
640
641 void sendDeliveryReceipt(
642 SignalServiceAddress remoteAddress, List<Long> messageIds
643 ) throws IOException, UntrustedIdentityException {
644 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.DELIVERY,
645 messageIds,
646 System.currentTimeMillis());
647
648 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(remoteAddress));
649 }
650
651 public SendMessageResults sendMessage(
652 Message message, Set<RecipientIdentifier> recipients
653 ) throws IOException, AttachmentInvalidException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
654 final var messageBuilder = SignalServiceDataMessage.newBuilder();
655 applyMessage(messageBuilder, message);
656 return sendMessage(messageBuilder, recipients);
657 }
658
659 private void applyMessage(
660 final SignalServiceDataMessage.Builder messageBuilder, final Message message
661 ) throws AttachmentInvalidException, IOException {
662 messageBuilder.withBody(message.getMessageText());
663 if (message.getAttachments() != null) {
664 var attachmentStreams = AttachmentUtils.getSignalServiceAttachments(message.getAttachments());
665
666 // Upload attachments here, so we only upload once even for multiple recipients
667 var messageSender = dependencies.getMessageSender();
668 var attachmentPointers = new ArrayList<SignalServiceAttachment>(attachmentStreams.size());
669 for (var attachment : attachmentStreams) {
670 if (attachment.isStream()) {
671 attachmentPointers.add(messageSender.uploadAttachment(attachment.asStream()));
672 } else if (attachment.isPointer()) {
673 attachmentPointers.add(attachment.asPointer());
674 }
675 }
676
677 messageBuilder.withAttachments(attachmentPointers);
678 }
679 }
680
681 public SendMessageResults sendRemoteDeleteMessage(
682 long targetSentTimestamp, Set<RecipientIdentifier> recipients
683 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
684 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
685 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
686 return sendMessage(messageBuilder, recipients);
687 }
688
689 public SendMessageResults sendMessageReaction(
690 String emoji,
691 boolean remove,
692 RecipientIdentifier.Single targetAuthor,
693 long targetSentTimestamp,
694 Set<RecipientIdentifier> recipients
695 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
696 var targetAuthorRecipientId = resolveRecipient(targetAuthor);
697 var reaction = new SignalServiceDataMessage.Reaction(emoji,
698 remove,
699 resolveSignalServiceAddress(targetAuthorRecipientId),
700 targetSentTimestamp);
701 final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
702 return sendMessage(messageBuilder, recipients);
703 }
704
705 public SendMessageResults sendEndSessionMessage(Set<RecipientIdentifier.Single> recipients) throws IOException {
706 var messageBuilder = SignalServiceDataMessage.newBuilder().asEndSessionMessage();
707
708 try {
709 return sendMessage(messageBuilder,
710 recipients.stream().map(RecipientIdentifier.class::cast).collect(Collectors.toSet()));
711 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
712 throw new AssertionError(e);
713 } finally {
714 for (var recipient : recipients) {
715 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
716 handleEndSession(recipientId);
717 }
718 }
719 }
720
721 void renewSession(RecipientId recipientId) throws IOException {
722 account.getSessionStore().archiveSessions(recipientId);
723 if (!recipientId.equals(getSelfRecipientId())) {
724 sendHelper.sendNullMessage(recipientId);
725 }
726 }
727
728 public void setContactName(
729 RecipientIdentifier.Single recipient, String name
730 ) throws NotMasterDeviceException {
731 if (!account.isMasterDevice()) {
732 throw new NotMasterDeviceException();
733 }
734 final var recipientId = resolveRecipient(recipient);
735 var contact = account.getContactStore().getContact(recipientId);
736 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
737 account.getContactStore().storeContact(recipientId, builder.withName(name).build());
738 }
739
740 public void setContactBlocked(
741 RecipientIdentifier.Single recipient, boolean blocked
742 ) throws NotMasterDeviceException {
743 if (!account.isMasterDevice()) {
744 throw new NotMasterDeviceException();
745 }
746 setContactBlocked(resolveRecipient(recipient), blocked);
747 }
748
749 private void setContactBlocked(RecipientId recipientId, boolean blocked) {
750 var contact = account.getContactStore().getContact(recipientId);
751 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
752 // TODO cycle our profile key
753 account.getContactStore().storeContact(recipientId, builder.withBlocked(blocked).build());
754 }
755
756 public void setGroupBlocked(final GroupId groupId, final boolean blocked) throws GroupNotFoundException {
757 var group = getGroup(groupId);
758 if (group == null) {
759 throw new GroupNotFoundException(groupId);
760 }
761
762 group.setBlocked(blocked);
763 // TODO cycle our profile key
764 account.getGroupStore().updateGroup(group);
765 }
766
767 /**
768 * Change the expiration timer for a contact
769 */
770 public void setExpirationTimer(
771 RecipientIdentifier.Single recipient, int messageExpirationTimer
772 ) throws IOException {
773 var recipientId = resolveRecipient(recipient);
774 setExpirationTimer(recipientId, messageExpirationTimer);
775 final var messageBuilder = SignalServiceDataMessage.newBuilder().asExpirationUpdate();
776 try {
777 sendMessage(messageBuilder, Set.of(recipient));
778 } catch (NotAGroupMemberException | GroupNotFoundException | GroupSendingNotAllowedException e) {
779 throw new AssertionError(e);
780 }
781 }
782
783 private void setExpirationTimer(RecipientId recipientId, int messageExpirationTimer) {
784 var contact = account.getContactStore().getContact(recipientId);
785 if (contact != null && contact.getMessageExpirationTime() == messageExpirationTimer) {
786 return;
787 }
788 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
789 account.getContactStore()
790 .storeContact(recipientId, builder.withMessageExpirationTime(messageExpirationTimer).build());
791 }
792
793 /**
794 * Upload the sticker pack from path.
795 *
796 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
797 * @return if successful, returns the URL to install the sticker pack in the signal app
798 */
799 public URI uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
800 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
801
802 var messageSender = dependencies.getMessageSender();
803
804 var packKey = KeyUtils.createStickerUploadKey();
805 var packIdString = messageSender.uploadStickerManifest(manifest, packKey);
806 var packId = StickerPackId.deserialize(Hex.fromStringCondensed(packIdString));
807
808 var sticker = new Sticker(packId, packKey);
809 account.getStickerStore().updateSticker(sticker);
810
811 try {
812 return new URI("https",
813 "signal.art",
814 "/addstickers/",
815 "pack_id="
816 + URLEncoder.encode(Hex.toStringCondensed(packId.serialize()), StandardCharsets.UTF_8)
817 + "&pack_key="
818 + URLEncoder.encode(Hex.toStringCondensed(packKey), StandardCharsets.UTF_8));
819 } catch (URISyntaxException e) {
820 throw new AssertionError(e);
821 }
822 }
823
824 public void requestAllSyncData() throws IOException {
825 requestSyncGroups();
826 requestSyncContacts();
827 requestSyncBlocked();
828 requestSyncConfiguration();
829 requestSyncKeys();
830 }
831
832 private void requestSyncGroups() throws IOException {
833 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
834 .setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS)
835 .build();
836 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
837 sendHelper.sendSyncMessage(message);
838 }
839
840 private void requestSyncContacts() throws IOException {
841 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
842 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS)
843 .build();
844 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
845 sendHelper.sendSyncMessage(message);
846 }
847
848 private void requestSyncBlocked() throws IOException {
849 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
850 .setType(SignalServiceProtos.SyncMessage.Request.Type.BLOCKED)
851 .build();
852 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
853 sendHelper.sendSyncMessage(message);
854 }
855
856 private void requestSyncConfiguration() throws IOException {
857 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
858 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONFIGURATION)
859 .build();
860 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
861 sendHelper.sendSyncMessage(message);
862 }
863
864 private void requestSyncKeys() throws IOException {
865 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
866 .setType(SignalServiceProtos.SyncMessage.Request.Type.KEYS)
867 .build();
868 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
869 sendHelper.sendSyncMessage(message);
870 }
871
872 private byte[] getSenderCertificate() {
873 byte[] certificate;
874 try {
875 if (account.isPhoneNumberShared()) {
876 certificate = dependencies.getAccountManager().getSenderCertificate();
877 } else {
878 certificate = dependencies.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
879 }
880 } catch (IOException e) {
881 logger.warn("Failed to get sender certificate, ignoring: {}", e.getMessage());
882 return null;
883 }
884 // TODO cache for a day
885 return certificate;
886 }
887
888 private Set<RecipientId> getRecipientIds(Collection<RecipientIdentifier.Single> recipients) {
889 final var signalServiceAddresses = new HashSet<SignalServiceAddress>(recipients.size());
890 final var addressesMissingUuid = new HashSet<SignalServiceAddress>();
891
892 for (var number : recipients) {
893 final var resolvedAddress = resolveSignalServiceAddress(resolveRecipient(number));
894 if (resolvedAddress.getUuid().isPresent()) {
895 signalServiceAddresses.add(resolvedAddress);
896 } else {
897 addressesMissingUuid.add(resolvedAddress);
898 }
899 }
900
901 final var numbersMissingUuid = addressesMissingUuid.stream()
902 .map(a -> a.getNumber().get())
903 .collect(Collectors.toSet());
904 Map<String, UUID> registeredUsers;
905 try {
906 registeredUsers = getRegisteredUsers(numbersMissingUuid);
907 } catch (IOException e) {
908 logger.warn("Failed to resolve uuids from server, ignoring: {}", e.getMessage());
909 registeredUsers = Map.of();
910 }
911
912 for (var address : addressesMissingUuid) {
913 final var number = address.getNumber().get();
914 if (registeredUsers.containsKey(number)) {
915 final var newAddress = resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
916 registeredUsers.get(number),
917 number)));
918 signalServiceAddresses.add(newAddress);
919 } else {
920 signalServiceAddresses.add(address);
921 }
922 }
923
924 return signalServiceAddresses.stream().map(this::resolveRecipient).collect(Collectors.toSet());
925 }
926
927 private RecipientId refreshRegisteredUser(RecipientId recipientId) throws IOException {
928 final var address = resolveSignalServiceAddress(recipientId);
929 if (!address.getNumber().isPresent()) {
930 return recipientId;
931 }
932 final var number = address.getNumber().get();
933 final var uuidMap = getRegisteredUsers(Set.of(number));
934 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap.getOrDefault(number, null), number));
935 }
936
937 private Map<String, UUID> getRegisteredUsers(final Set<String> numbers) throws IOException {
938 final Map<String, UUID> registeredUsers;
939 try {
940 registeredUsers = dependencies.getAccountManager()
941 .getRegisteredUsers(ServiceConfig.getIasKeyStore(),
942 numbers,
943 serviceEnvironmentConfig.getCdsMrenclave());
944 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
945 throw new IOException(e);
946 }
947
948 // Store numbers as recipients so we have the number/uuid association
949 registeredUsers.forEach((number, uuid) -> resolveRecipientTrusted(new SignalServiceAddress(uuid, number)));
950
951 return registeredUsers;
952 }
953
954 public void sendTypingMessage(
955 TypingAction action, Set<RecipientIdentifier> recipients
956 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
957 sendTypingMessage(action.toSignalService(), recipients);
958 }
959
960 private void handleEndSession(RecipientId recipientId) {
961 account.getSessionStore().deleteAllSessions(recipientId);
962 }
963
964 private List<HandleAction> handleSignalServiceDataMessage(
965 SignalServiceDataMessage message,
966 boolean isSync,
967 SignalServiceAddress source,
968 SignalServiceAddress destination,
969 boolean ignoreAttachments
970 ) {
971 var actions = new ArrayList<HandleAction>();
972 if (message.getGroupContext().isPresent()) {
973 if (message.getGroupContext().get().getGroupV1().isPresent()) {
974 var groupInfo = message.getGroupContext().get().getGroupV1().get();
975 var groupId = GroupId.v1(groupInfo.getGroupId());
976 var group = getGroup(groupId);
977 if (group == null || group instanceof GroupInfoV1) {
978 var groupV1 = (GroupInfoV1) group;
979 switch (groupInfo.getType()) {
980 case UPDATE: {
981 if (groupV1 == null) {
982 groupV1 = new GroupInfoV1(groupId);
983 }
984
985 if (groupInfo.getAvatar().isPresent()) {
986 var avatar = groupInfo.getAvatar().get();
987 downloadGroupAvatar(groupV1.getGroupId(), avatar);
988 }
989
990 if (groupInfo.getName().isPresent()) {
991 groupV1.name = groupInfo.getName().get();
992 }
993
994 if (groupInfo.getMembers().isPresent()) {
995 groupV1.addMembers(groupInfo.getMembers()
996 .get()
997 .stream()
998 .map(this::resolveRecipient)
999 .collect(Collectors.toSet()));
1000 }
1001
1002 account.getGroupStore().updateGroup(groupV1);
1003 break;
1004 }
1005 case DELIVER:
1006 if (groupV1 == null && !isSync) {
1007 actions.add(new SendGroupInfoRequestAction(source, groupId));
1008 }
1009 break;
1010 case QUIT: {
1011 if (groupV1 != null) {
1012 groupV1.removeMember(resolveRecipient(source));
1013 account.getGroupStore().updateGroup(groupV1);
1014 }
1015 break;
1016 }
1017 case REQUEST_INFO:
1018 if (groupV1 != null && !isSync) {
1019 actions.add(new SendGroupInfoAction(source, groupV1.getGroupId()));
1020 }
1021 break;
1022 }
1023 } else {
1024 // Received a group v1 message for a v2 group
1025 }
1026 }
1027 if (message.getGroupContext().get().getGroupV2().isPresent()) {
1028 final var groupContext = message.getGroupContext().get().getGroupV2().get();
1029 final var groupMasterKey = groupContext.getMasterKey();
1030
1031 groupHelper.getOrMigrateGroup(groupMasterKey,
1032 groupContext.getRevision(),
1033 groupContext.hasSignedGroupChange() ? groupContext.getSignedGroupChange() : null);
1034 }
1035 }
1036
1037 final var conversationPartnerAddress = isSync ? destination : source;
1038 if (conversationPartnerAddress != null && message.isEndSession()) {
1039 handleEndSession(resolveRecipient(conversationPartnerAddress));
1040 }
1041 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
1042 if (message.getGroupContext().isPresent()) {
1043 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1044 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1045 var group = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(groupInfo.getGroupId()));
1046 if (group != null) {
1047 if (group.messageExpirationTime != message.getExpiresInSeconds()) {
1048 group.messageExpirationTime = message.getExpiresInSeconds();
1049 account.getGroupStore().updateGroup(group);
1050 }
1051 }
1052 } else if (message.getGroupContext().get().getGroupV2().isPresent()) {
1053 // disappearing message timer already stored in the DecryptedGroup
1054 }
1055 } else if (conversationPartnerAddress != null) {
1056 setExpirationTimer(resolveRecipient(conversationPartnerAddress), message.getExpiresInSeconds());
1057 }
1058 }
1059 if (!ignoreAttachments) {
1060 if (message.getAttachments().isPresent()) {
1061 for (var attachment : message.getAttachments().get()) {
1062 downloadAttachment(attachment);
1063 }
1064 }
1065 if (message.getSharedContacts().isPresent()) {
1066 for (var contact : message.getSharedContacts().get()) {
1067 if (contact.getAvatar().isPresent()) {
1068 downloadAttachment(contact.getAvatar().get().getAttachment());
1069 }
1070 }
1071 }
1072 }
1073 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
1074 final ProfileKey profileKey;
1075 try {
1076 profileKey = new ProfileKey(message.getProfileKey().get());
1077 } catch (InvalidInputException e) {
1078 throw new AssertionError(e);
1079 }
1080 if (source.matches(account.getSelfAddress())) {
1081 this.account.setProfileKey(profileKey);
1082 }
1083 this.account.getProfileStore().storeProfileKey(resolveRecipient(source), profileKey);
1084 }
1085 if (message.getPreviews().isPresent()) {
1086 final var previews = message.getPreviews().get();
1087 for (var preview : previews) {
1088 if (preview.getImage().isPresent()) {
1089 downloadAttachment(preview.getImage().get());
1090 }
1091 }
1092 }
1093 if (message.getQuote().isPresent()) {
1094 final var quote = message.getQuote().get();
1095
1096 for (var quotedAttachment : quote.getAttachments()) {
1097 final var thumbnail = quotedAttachment.getThumbnail();
1098 if (thumbnail != null) {
1099 downloadAttachment(thumbnail);
1100 }
1101 }
1102 }
1103 if (message.getSticker().isPresent()) {
1104 final var messageSticker = message.getSticker().get();
1105 final var stickerPackId = StickerPackId.deserialize(messageSticker.getPackId());
1106 var sticker = account.getStickerStore().getSticker(stickerPackId);
1107 if (sticker == null) {
1108 sticker = new Sticker(stickerPackId, messageSticker.getPackKey());
1109 account.getStickerStore().updateSticker(sticker);
1110 }
1111 enqueueJob(new RetrieveStickerPackJob(stickerPackId, messageSticker.getPackKey()));
1112 }
1113 return actions;
1114 }
1115
1116 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1117 Set<HandleAction> queuedActions = new HashSet<>();
1118 for (var cachedMessage : account.getMessageCache().getCachedMessages()) {
1119 var actions = retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
1120 if (actions != null) {
1121 queuedActions.addAll(actions);
1122 }
1123 }
1124 handleQueuedActions(queuedActions);
1125 }
1126
1127 private List<HandleAction> retryFailedReceivedMessage(
1128 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
1129 ) {
1130 var envelope = cachedMessage.loadEnvelope();
1131 if (envelope == null) {
1132 return null;
1133 }
1134 SignalServiceContent content = null;
1135 List<HandleAction> actions = null;
1136 if (!envelope.isReceipt()) {
1137 try {
1138 content = dependencies.getCipher().decrypt(envelope);
1139 } catch (ProtocolUntrustedIdentityException e) {
1140 if (!envelope.hasSource()) {
1141 final var identifier = e.getSender();
1142 final var recipientId = resolveRecipient(identifier);
1143 try {
1144 account.getMessageCache().replaceSender(cachedMessage, recipientId);
1145 } catch (IOException ioException) {
1146 logger.warn("Failed to move cached message to recipient folder: {}", ioException.getMessage());
1147 }
1148 }
1149 return null;
1150 } catch (Exception er) {
1151 // All other errors are not recoverable, so delete the cached message
1152 cachedMessage.delete();
1153 return null;
1154 }
1155 actions = handleMessage(envelope, content, ignoreAttachments);
1156 }
1157 handler.handleMessage(envelope, content, null);
1158 cachedMessage.delete();
1159 return actions;
1160 }
1161
1162 public void receiveMessages(
1163 long timeout,
1164 TimeUnit unit,
1165 boolean returnOnTimeout,
1166 boolean ignoreAttachments,
1167 ReceiveMessageHandler handler
1168 ) throws IOException {
1169 retryFailedReceivedMessages(handler, ignoreAttachments);
1170
1171 Set<HandleAction> queuedActions = new HashSet<>();
1172
1173 final var signalWebSocket = dependencies.getSignalWebSocket();
1174 signalWebSocket.connect();
1175
1176 var hasCaughtUpWithOldMessages = false;
1177
1178 while (!Thread.interrupted()) {
1179 SignalServiceEnvelope envelope;
1180 SignalServiceContent content = null;
1181 Exception exception = null;
1182 final CachedMessage[] cachedMessage = {null};
1183 account.setLastReceiveTimestamp(System.currentTimeMillis());
1184 logger.debug("Checking for new message from server");
1185 try {
1186 var result = signalWebSocket.readOrEmpty(unit.toMillis(timeout), envelope1 -> {
1187 final var recipientId = envelope1.hasSource()
1188 ? resolveRecipient(envelope1.getSourceIdentifier())
1189 : null;
1190 // store message on disk, before acknowledging receipt to the server
1191 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
1192 });
1193 logger.debug("New message received from server");
1194 if (result.isPresent()) {
1195 envelope = result.get();
1196 } else {
1197 // Received indicator that server queue is empty
1198 hasCaughtUpWithOldMessages = true;
1199
1200 handleQueuedActions(queuedActions);
1201 queuedActions.clear();
1202
1203 // Continue to wait another timeout for new messages
1204 continue;
1205 }
1206 } catch (AssertionError e) {
1207 if (e.getCause() instanceof InterruptedException) {
1208 Thread.currentThread().interrupt();
1209 break;
1210 } else {
1211 throw e;
1212 }
1213 } catch (WebSocketUnavailableException e) {
1214 logger.debug("Pipe unexpectedly unavailable, connecting");
1215 signalWebSocket.connect();
1216 continue;
1217 } catch (TimeoutException e) {
1218 if (returnOnTimeout) return;
1219 continue;
1220 }
1221
1222 if (envelope.hasSource()) {
1223 // Store uuid if we don't have it already
1224 // address/uuid in envelope is sent by server
1225 resolveRecipientTrusted(envelope.getSourceAddress());
1226 }
1227 if (!envelope.isReceipt()) {
1228 try {
1229 content = dependencies.getCipher().decrypt(envelope);
1230 } catch (Exception e) {
1231 exception = e;
1232 }
1233 if (!envelope.hasSource() && content != null) {
1234 // Store uuid if we don't have it already
1235 // address/uuid is validated by unidentified sender certificate
1236 resolveRecipientTrusted(content.getSender());
1237 }
1238 var actions = handleMessage(envelope, content, ignoreAttachments);
1239 if (exception instanceof ProtocolInvalidMessageException) {
1240 final var sender = resolveRecipient(((ProtocolInvalidMessageException) exception).getSender());
1241 logger.debug("Received invalid message, queuing renew session action.");
1242 actions.add(new RenewSessionAction(sender));
1243 }
1244 if (hasCaughtUpWithOldMessages) {
1245 for (var action : actions) {
1246 try {
1247 action.execute(this);
1248 } catch (Throwable e) {
1249 if (e instanceof AssertionError && e.getCause() instanceof InterruptedException) {
1250 Thread.currentThread().interrupt();
1251 }
1252 logger.warn("Message action failed.", e);
1253 }
1254 }
1255 } else {
1256 queuedActions.addAll(actions);
1257 }
1258 }
1259 final var notAllowedToSendToGroup = isNotAllowedToSendToGroup(envelope, content);
1260 if (isMessageBlocked(envelope, content)) {
1261 logger.info("Ignoring a message from blocked user/group: {}", envelope.getTimestamp());
1262 } else if (notAllowedToSendToGroup) {
1263 logger.info("Ignoring a group message from an unauthorized sender (no member or admin): {} {}",
1264 (envelope.hasSource() ? envelope.getSourceAddress() : content.getSender()).getIdentifier(),
1265 envelope.getTimestamp());
1266 } else {
1267 handler.handleMessage(envelope, content, exception);
1268 }
1269 if (cachedMessage[0] != null) {
1270 if (exception instanceof ProtocolUntrustedIdentityException) {
1271 final var identifier = ((ProtocolUntrustedIdentityException) exception).getSender();
1272 final var recipientId = resolveRecipient(identifier);
1273 queuedActions.add(new RetrieveProfileAction(recipientId));
1274 if (!envelope.hasSource()) {
1275 try {
1276 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
1277 } catch (IOException ioException) {
1278 logger.warn("Failed to move cached message to recipient folder: {}",
1279 ioException.getMessage());
1280 }
1281 }
1282 } else {
1283 cachedMessage[0].delete();
1284 }
1285 }
1286 }
1287 handleQueuedActions(queuedActions);
1288 }
1289
1290 private void handleQueuedActions(final Set<HandleAction> queuedActions) {
1291 for (var action : queuedActions) {
1292 try {
1293 action.execute(this);
1294 } catch (Throwable e) {
1295 if (e instanceof AssertionError && e.getCause() instanceof InterruptedException) {
1296 Thread.currentThread().interrupt();
1297 }
1298 logger.warn("Message action failed.", e);
1299 }
1300 }
1301 }
1302
1303 private boolean isMessageBlocked(
1304 SignalServiceEnvelope envelope, SignalServiceContent content
1305 ) {
1306 SignalServiceAddress source;
1307 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1308 source = envelope.getSourceAddress();
1309 } else if (content != null) {
1310 source = content.getSender();
1311 } else {
1312 return false;
1313 }
1314 final var recipientId = resolveRecipient(source);
1315 if (isContactBlocked(recipientId)) {
1316 return true;
1317 }
1318
1319 if (content != null && content.getDataMessage().isPresent()) {
1320 var message = content.getDataMessage().get();
1321 if (message.getGroupContext().isPresent()) {
1322 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1323 var group = getGroup(groupId);
1324 if (group != null && group.isBlocked()) {
1325 return true;
1326 }
1327 }
1328 }
1329 return false;
1330 }
1331
1332 public boolean isContactBlocked(final RecipientIdentifier.Single recipient) {
1333 final var recipientId = resolveRecipient(recipient);
1334 return isContactBlocked(recipientId);
1335 }
1336
1337 private boolean isContactBlocked(final RecipientId recipientId) {
1338 var sourceContact = account.getContactStore().getContact(recipientId);
1339 return sourceContact != null && sourceContact.isBlocked();
1340 }
1341
1342 private boolean isNotAllowedToSendToGroup(
1343 SignalServiceEnvelope envelope, SignalServiceContent content
1344 ) {
1345 SignalServiceAddress source;
1346 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1347 source = envelope.getSourceAddress();
1348 } else if (content != null) {
1349 source = content.getSender();
1350 } else {
1351 return false;
1352 }
1353
1354 if (content == null || !content.getDataMessage().isPresent()) {
1355 return false;
1356 }
1357
1358 var message = content.getDataMessage().get();
1359 if (!message.getGroupContext().isPresent()) {
1360 return false;
1361 }
1362
1363 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1364 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1365 if (groupInfo.getType() == SignalServiceGroup.Type.QUIT) {
1366 return false;
1367 }
1368 }
1369
1370 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1371 var group = getGroup(groupId);
1372 if (group == null) {
1373 return false;
1374 }
1375
1376 final var recipientId = resolveRecipient(source);
1377 if (!group.isMember(recipientId)) {
1378 return true;
1379 }
1380
1381 if (group.isAnnouncementGroup() && !group.isAdmin(recipientId)) {
1382 return message.getBody().isPresent()
1383 || message.getAttachments().isPresent()
1384 || message.getQuote()
1385 .isPresent()
1386 || message.getPreviews().isPresent()
1387 || message.getMentions().isPresent()
1388 || message.getSticker().isPresent();
1389 }
1390 return false;
1391 }
1392
1393 private List<HandleAction> handleMessage(
1394 SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments
1395 ) {
1396 var actions = new ArrayList<HandleAction>();
1397 if (content != null) {
1398 final SignalServiceAddress sender;
1399 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1400 sender = envelope.getSourceAddress();
1401 } else {
1402 sender = content.getSender();
1403 }
1404
1405 if (content.getDataMessage().isPresent()) {
1406 var message = content.getDataMessage().get();
1407
1408 if (content.isNeedsReceipt()) {
1409 actions.add(new SendReceiptAction(sender, message.getTimestamp()));
1410 }
1411
1412 actions.addAll(handleSignalServiceDataMessage(message,
1413 false,
1414 sender,
1415 account.getSelfAddress(),
1416 ignoreAttachments));
1417 }
1418 if (content.getSyncMessage().isPresent()) {
1419 account.setMultiDevice(true);
1420 var syncMessage = content.getSyncMessage().get();
1421 if (syncMessage.getSent().isPresent()) {
1422 var message = syncMessage.getSent().get();
1423 final var destination = message.getDestination().orNull();
1424 actions.addAll(handleSignalServiceDataMessage(message.getMessage(),
1425 true,
1426 sender,
1427 destination,
1428 ignoreAttachments));
1429 }
1430 if (syncMessage.getRequest().isPresent() && account.isMasterDevice()) {
1431 var rm = syncMessage.getRequest().get();
1432 if (rm.isContactsRequest()) {
1433 actions.add(SendSyncContactsAction.create());
1434 }
1435 if (rm.isGroupsRequest()) {
1436 actions.add(SendSyncGroupsAction.create());
1437 }
1438 if (rm.isBlockedListRequest()) {
1439 actions.add(SendSyncBlockedListAction.create());
1440 }
1441 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1442 }
1443 if (syncMessage.getGroups().isPresent()) {
1444 File tmpFile = null;
1445 try {
1446 tmpFile = IOUtils.createTempFile();
1447 final var groupsMessage = syncMessage.getGroups().get();
1448 try (var attachmentAsStream = retrieveAttachmentAsStream(groupsMessage.asPointer(), tmpFile)) {
1449 var s = new DeviceGroupsInputStream(attachmentAsStream);
1450 DeviceGroup g;
1451 while (true) {
1452 try {
1453 g = s.read();
1454 } catch (IOException e) {
1455 logger.warn("Sync groups contained invalid group, ignoring: {}", e.getMessage());
1456 continue;
1457 }
1458 if (g == null) {
1459 break;
1460 }
1461 var syncGroup = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(g.getId()));
1462 if (syncGroup != null) {
1463 if (g.getName().isPresent()) {
1464 syncGroup.name = g.getName().get();
1465 }
1466 syncGroup.addMembers(g.getMembers()
1467 .stream()
1468 .map(this::resolveRecipient)
1469 .collect(Collectors.toSet()));
1470 if (!g.isActive()) {
1471 syncGroup.removeMember(account.getSelfRecipientId());
1472 } else {
1473 // Add ourself to the member set as it's marked as active
1474 syncGroup.addMembers(List.of(account.getSelfRecipientId()));
1475 }
1476 syncGroup.blocked = g.isBlocked();
1477 if (g.getColor().isPresent()) {
1478 syncGroup.color = g.getColor().get();
1479 }
1480
1481 if (g.getAvatar().isPresent()) {
1482 downloadGroupAvatar(syncGroup.getGroupId(), g.getAvatar().get());
1483 }
1484 syncGroup.archived = g.isArchived();
1485 account.getGroupStore().updateGroup(syncGroup);
1486 }
1487 }
1488 }
1489 } catch (Exception e) {
1490 logger.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1491 tmpFile,
1492 e.getMessage());
1493 } finally {
1494 if (tmpFile != null) {
1495 try {
1496 Files.delete(tmpFile.toPath());
1497 } catch (IOException e) {
1498 logger.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1499 tmpFile,
1500 e.getMessage());
1501 }
1502 }
1503 }
1504 }
1505 if (syncMessage.getBlockedList().isPresent()) {
1506 final var blockedListMessage = syncMessage.getBlockedList().get();
1507 for (var address : blockedListMessage.getAddresses()) {
1508 setContactBlocked(resolveRecipient(address), true);
1509 }
1510 for (var groupId : blockedListMessage.getGroupIds()
1511 .stream()
1512 .map(GroupId::unknownVersion)
1513 .collect(Collectors.toSet())) {
1514 try {
1515 setGroupBlocked(groupId, true);
1516 } catch (GroupNotFoundException e) {
1517 logger.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1518 groupId.toBase64());
1519 }
1520 }
1521 }
1522 if (syncMessage.getContacts().isPresent()) {
1523 File tmpFile = null;
1524 try {
1525 tmpFile = IOUtils.createTempFile();
1526 final var contactsMessage = syncMessage.getContacts().get();
1527 try (var attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream()
1528 .asPointer(), tmpFile)) {
1529 var s = new DeviceContactsInputStream(attachmentAsStream);
1530 DeviceContact c;
1531 while (true) {
1532 try {
1533 c = s.read();
1534 } catch (IOException e) {
1535 logger.warn("Sync contacts contained invalid contact, ignoring: {}",
1536 e.getMessage());
1537 continue;
1538 }
1539 if (c == null) {
1540 break;
1541 }
1542 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
1543 account.setProfileKey(c.getProfileKey().get());
1544 }
1545 final var recipientId = resolveRecipientTrusted(c.getAddress());
1546 var contact = account.getContactStore().getContact(recipientId);
1547 final var builder = contact == null
1548 ? Contact.newBuilder()
1549 : Contact.newBuilder(contact);
1550 if (c.getName().isPresent()) {
1551 builder.withName(c.getName().get());
1552 }
1553 if (c.getColor().isPresent()) {
1554 builder.withColor(c.getColor().get());
1555 }
1556 if (c.getProfileKey().isPresent()) {
1557 account.getProfileStore().storeProfileKey(recipientId, c.getProfileKey().get());
1558 }
1559 if (c.getVerified().isPresent()) {
1560 final var verifiedMessage = c.getVerified().get();
1561 account.getIdentityKeyStore()
1562 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
1563 verifiedMessage.getIdentityKey(),
1564 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1565 }
1566 if (c.getExpirationTimer().isPresent()) {
1567 builder.withMessageExpirationTime(c.getExpirationTimer().get());
1568 }
1569 builder.withBlocked(c.isBlocked());
1570 builder.withArchived(c.isArchived());
1571 account.getContactStore().storeContact(recipientId, builder.build());
1572
1573 if (c.getAvatar().isPresent()) {
1574 downloadContactAvatar(c.getAvatar().get(), c.getAddress());
1575 }
1576 }
1577 }
1578 } catch (Exception e) {
1579 logger.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
1580 tmpFile,
1581 e.getMessage());
1582 } finally {
1583 if (tmpFile != null) {
1584 try {
1585 Files.delete(tmpFile.toPath());
1586 } catch (IOException e) {
1587 logger.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
1588 tmpFile,
1589 e.getMessage());
1590 }
1591 }
1592 }
1593 }
1594 if (syncMessage.getVerified().isPresent()) {
1595 final var verifiedMessage = syncMessage.getVerified().get();
1596 account.getIdentityKeyStore()
1597 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
1598 verifiedMessage.getIdentityKey(),
1599 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1600 }
1601 if (syncMessage.getStickerPackOperations().isPresent()) {
1602 final var stickerPackOperationMessages = syncMessage.getStickerPackOperations().get();
1603 for (var m : stickerPackOperationMessages) {
1604 if (!m.getPackId().isPresent()) {
1605 continue;
1606 }
1607 final var stickerPackId = StickerPackId.deserialize(m.getPackId().get());
1608 final var installed = !m.getType().isPresent()
1609 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL;
1610
1611 var sticker = account.getStickerStore().getSticker(stickerPackId);
1612 if (m.getPackKey().isPresent()) {
1613 if (sticker == null) {
1614 sticker = new Sticker(stickerPackId, m.getPackKey().get());
1615 }
1616 if (installed) {
1617 enqueueJob(new RetrieveStickerPackJob(stickerPackId, m.getPackKey().get()));
1618 }
1619 }
1620
1621 if (sticker != null) {
1622 sticker.setInstalled(installed);
1623 account.getStickerStore().updateSticker(sticker);
1624 }
1625 }
1626 }
1627 if (syncMessage.getFetchType().isPresent()) {
1628 switch (syncMessage.getFetchType().get()) {
1629 case LOCAL_PROFILE:
1630 actions.add(new RetrieveProfileAction(account.getSelfRecipientId()));
1631 case STORAGE_MANIFEST:
1632 // TODO
1633 }
1634 }
1635 if (syncMessage.getKeys().isPresent()) {
1636 final var keysMessage = syncMessage.getKeys().get();
1637 if (keysMessage.getStorageService().isPresent()) {
1638 final var storageKey = keysMessage.getStorageService().get();
1639 account.setStorageKey(storageKey);
1640 }
1641 }
1642 if (syncMessage.getConfiguration().isPresent()) {
1643 // TODO
1644 }
1645 }
1646 }
1647 return actions;
1648 }
1649
1650 private void downloadContactAvatar(SignalServiceAttachment avatar, SignalServiceAddress address) {
1651 try {
1652 avatarStore.storeContactAvatar(address, outputStream -> retrieveAttachment(avatar, outputStream));
1653 } catch (IOException e) {
1654 logger.warn("Failed to download avatar for contact {}, ignoring: {}", address, e.getMessage());
1655 }
1656 }
1657
1658 private void downloadGroupAvatar(GroupIdV1 groupId, SignalServiceAttachment avatar) {
1659 try {
1660 avatarStore.storeGroupAvatar(groupId, outputStream -> retrieveAttachment(avatar, outputStream));
1661 } catch (IOException e) {
1662 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
1663 }
1664 }
1665
1666 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
1667 return attachmentStore.getAttachmentFile(attachmentId);
1668 }
1669
1670 private void downloadAttachment(final SignalServiceAttachment attachment) {
1671 if (!attachment.isPointer()) {
1672 logger.warn("Invalid state, can't store an attachment stream.");
1673 }
1674
1675 var pointer = attachment.asPointer();
1676 if (pointer.getPreview().isPresent()) {
1677 final var preview = pointer.getPreview().get();
1678 try {
1679 attachmentStore.storeAttachmentPreview(pointer.getRemoteId(),
1680 outputStream -> outputStream.write(preview, 0, preview.length));
1681 } catch (IOException e) {
1682 logger.warn("Failed to download attachment preview, ignoring: {}", e.getMessage());
1683 }
1684 }
1685
1686 try {
1687 attachmentStore.storeAttachment(pointer.getRemoteId(),
1688 outputStream -> retrieveAttachmentPointer(pointer, outputStream));
1689 } catch (IOException e) {
1690 logger.warn("Failed to download attachment ({}), ignoring: {}", pointer.getRemoteId(), e.getMessage());
1691 }
1692 }
1693
1694 private void retrieveAttachment(
1695 final SignalServiceAttachment attachment, final OutputStream outputStream
1696 ) throws IOException {
1697 if (attachment.isPointer()) {
1698 var pointer = attachment.asPointer();
1699 retrieveAttachmentPointer(pointer, outputStream);
1700 } else {
1701 var stream = attachment.asStream();
1702 IOUtils.copyStream(stream.getInputStream(), outputStream);
1703 }
1704 }
1705
1706 private void retrieveAttachmentPointer(
1707 SignalServiceAttachmentPointer pointer, OutputStream outputStream
1708 ) throws IOException {
1709 var tmpFile = IOUtils.createTempFile();
1710 try (var input = retrieveAttachmentAsStream(pointer, tmpFile)) {
1711 IOUtils.copyStream(input, outputStream);
1712 } catch (MissingConfigurationException | InvalidMessageException e) {
1713 throw new IOException(e);
1714 } finally {
1715 try {
1716 Files.delete(tmpFile.toPath());
1717 } catch (IOException e) {
1718 logger.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
1719 tmpFile,
1720 e.getMessage());
1721 }
1722 }
1723 }
1724
1725 private InputStream retrieveAttachmentAsStream(
1726 SignalServiceAttachmentPointer pointer, File tmpFile
1727 ) throws IOException, InvalidMessageException, MissingConfigurationException {
1728 return dependencies.getMessageReceiver()
1729 .retrieveAttachment(pointer, tmpFile, ServiceConfig.MAX_ATTACHMENT_SIZE);
1730 }
1731
1732 void sendGroups() throws IOException {
1733 var groupsFile = IOUtils.createTempFile();
1734
1735 try {
1736 try (OutputStream fos = new FileOutputStream(groupsFile)) {
1737 var out = new DeviceGroupsOutputStream(fos);
1738 for (var record : getGroups()) {
1739 if (record instanceof GroupInfoV1) {
1740 var groupInfo = (GroupInfoV1) record;
1741 out.write(new DeviceGroup(groupInfo.getGroupId().serialize(),
1742 Optional.fromNullable(groupInfo.name),
1743 groupInfo.getMembers()
1744 .stream()
1745 .map(this::resolveSignalServiceAddress)
1746 .collect(Collectors.toList()),
1747 groupHelper.createGroupAvatarAttachment(groupInfo.getGroupId()),
1748 groupInfo.isMember(account.getSelfRecipientId()),
1749 Optional.of(groupInfo.messageExpirationTime),
1750 Optional.fromNullable(groupInfo.color),
1751 groupInfo.blocked,
1752 Optional.absent(),
1753 groupInfo.archived));
1754 }
1755 }
1756 }
1757
1758 if (groupsFile.exists() && groupsFile.length() > 0) {
1759 try (var groupsFileStream = new FileInputStream(groupsFile)) {
1760 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
1761 .withStream(groupsFileStream)
1762 .withContentType("application/octet-stream")
1763 .withLength(groupsFile.length())
1764 .build();
1765
1766 sendHelper.sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
1767 }
1768 }
1769 } finally {
1770 try {
1771 Files.delete(groupsFile.toPath());
1772 } catch (IOException e) {
1773 logger.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile, e.getMessage());
1774 }
1775 }
1776 }
1777
1778 public void sendContacts() throws IOException {
1779 var contactsFile = IOUtils.createTempFile();
1780
1781 try {
1782 try (OutputStream fos = new FileOutputStream(contactsFile)) {
1783 var out = new DeviceContactsOutputStream(fos);
1784 for (var contactPair : account.getContactStore().getContacts()) {
1785 final var recipientId = contactPair.first();
1786 final var contact = contactPair.second();
1787 final var address = resolveSignalServiceAddress(recipientId);
1788
1789 var currentIdentity = account.getIdentityKeyStore().getIdentity(recipientId);
1790 VerifiedMessage verifiedMessage = null;
1791 if (currentIdentity != null) {
1792 verifiedMessage = new VerifiedMessage(address,
1793 currentIdentity.getIdentityKey(),
1794 currentIdentity.getTrustLevel().toVerifiedState(),
1795 currentIdentity.getDateAdded().getTime());
1796 }
1797
1798 var profileKey = account.getProfileStore().getProfileKey(recipientId);
1799 out.write(new DeviceContact(address,
1800 Optional.fromNullable(contact.getName()),
1801 createContactAvatarAttachment(address),
1802 Optional.fromNullable(contact.getColor()),
1803 Optional.fromNullable(verifiedMessage),
1804 Optional.fromNullable(profileKey),
1805 contact.isBlocked(),
1806 Optional.of(contact.getMessageExpirationTime()),
1807 Optional.absent(),
1808 contact.isArchived()));
1809 }
1810
1811 if (account.getProfileKey() != null) {
1812 // Send our own profile key as well
1813 out.write(new DeviceContact(account.getSelfAddress(),
1814 Optional.absent(),
1815 Optional.absent(),
1816 Optional.absent(),
1817 Optional.absent(),
1818 Optional.of(account.getProfileKey()),
1819 false,
1820 Optional.absent(),
1821 Optional.absent(),
1822 false));
1823 }
1824 }
1825
1826 if (contactsFile.exists() && contactsFile.length() > 0) {
1827 try (var contactsFileStream = new FileInputStream(contactsFile)) {
1828 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
1829 .withStream(contactsFileStream)
1830 .withContentType("application/octet-stream")
1831 .withLength(contactsFile.length())
1832 .build();
1833
1834 sendHelper.sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream,
1835 true)));
1836 }
1837 }
1838 } finally {
1839 try {
1840 Files.delete(contactsFile.toPath());
1841 } catch (IOException e) {
1842 logger.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile, e.getMessage());
1843 }
1844 }
1845 }
1846
1847 void sendBlockedList() throws IOException {
1848 var addresses = new ArrayList<SignalServiceAddress>();
1849 for (var record : account.getContactStore().getContacts()) {
1850 if (record.second().isBlocked()) {
1851 addresses.add(resolveSignalServiceAddress(record.first()));
1852 }
1853 }
1854 var groupIds = new ArrayList<byte[]>();
1855 for (var record : getGroups()) {
1856 if (record.isBlocked()) {
1857 groupIds.add(record.getGroupId().serialize());
1858 }
1859 }
1860 sendHelper.sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
1861 }
1862
1863 private void sendVerifiedMessage(
1864 SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel
1865 ) throws IOException {
1866 var verifiedMessage = new VerifiedMessage(destination,
1867 identityKey,
1868 trustLevel.toVerifiedState(),
1869 System.currentTimeMillis());
1870 sendHelper.sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
1871 }
1872
1873 public List<Pair<RecipientId, Contact>> getContacts() {
1874 return account.getContactStore().getContacts();
1875 }
1876
1877 public String getContactOrProfileName(RecipientIdentifier.Single recipientIdentifier) {
1878 final var recipientId = resolveRecipient(recipientIdentifier);
1879
1880 final var contact = account.getRecipientStore().getContact(recipientId);
1881 if (contact != null && !Util.isEmpty(contact.getName())) {
1882 return contact.getName();
1883 }
1884
1885 final var profile = getRecipientProfile(recipientId);
1886 if (profile != null) {
1887 return profile.getDisplayName();
1888 }
1889
1890 return null;
1891 }
1892
1893 public GroupInfo getGroup(GroupId groupId) {
1894 return groupHelper.getGroup(groupId);
1895 }
1896
1897 public List<IdentityInfo> getIdentities() {
1898 return account.getIdentityKeyStore().getIdentities();
1899 }
1900
1901 public List<IdentityInfo> getIdentities(RecipientIdentifier.Single recipient) {
1902 final var identity = account.getIdentityKeyStore().getIdentity(resolveRecipient(recipient));
1903 return identity == null ? List.of() : List.of(identity);
1904 }
1905
1906 /**
1907 * Trust this the identity with this fingerprint
1908 *
1909 * @param recipient username of the identity
1910 * @param fingerprint Fingerprint
1911 */
1912 public boolean trustIdentityVerified(RecipientIdentifier.Single recipient, byte[] fingerprint) {
1913 var recipientId = resolveRecipient(recipient);
1914 return trustIdentity(recipientId,
1915 identityKey -> Arrays.equals(identityKey.serialize(), fingerprint),
1916 TrustLevel.TRUSTED_VERIFIED);
1917 }
1918
1919 /**
1920 * Trust this the identity with this safety number
1921 *
1922 * @param recipient username of the identity
1923 * @param safetyNumber Safety number
1924 */
1925 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, String safetyNumber) {
1926 var recipientId = resolveRecipient(recipient);
1927 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
1928 return trustIdentity(recipientId,
1929 identityKey -> safetyNumber.equals(computeSafetyNumber(address, identityKey)),
1930 TrustLevel.TRUSTED_VERIFIED);
1931 }
1932
1933 /**
1934 * Trust this the identity with this scannable safety number
1935 *
1936 * @param recipient username of the identity
1937 * @param safetyNumber Scannable safety number
1938 */
1939 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, byte[] safetyNumber) {
1940 var recipientId = resolveRecipient(recipient);
1941 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
1942 return trustIdentity(recipientId, identityKey -> {
1943 final var fingerprint = computeSafetyNumberFingerprint(address, identityKey);
1944 try {
1945 return fingerprint != null && fingerprint.getScannableFingerprint().compareTo(safetyNumber);
1946 } catch (FingerprintVersionMismatchException | FingerprintParsingException e) {
1947 return false;
1948 }
1949 }, TrustLevel.TRUSTED_VERIFIED);
1950 }
1951
1952 /**
1953 * Trust all keys of this identity without verification
1954 *
1955 * @param recipient username of the identity
1956 */
1957 public boolean trustIdentityAllKeys(RecipientIdentifier.Single recipient) {
1958 var recipientId = resolveRecipient(recipient);
1959 return trustIdentity(recipientId, identityKey -> true, TrustLevel.TRUSTED_UNVERIFIED);
1960 }
1961
1962 private boolean trustIdentity(
1963 RecipientId recipientId, Function<IdentityKey, Boolean> verifier, TrustLevel trustLevel
1964 ) {
1965 var identity = account.getIdentityKeyStore().getIdentity(recipientId);
1966 if (identity == null) {
1967 return false;
1968 }
1969
1970 if (!verifier.apply(identity.getIdentityKey())) {
1971 return false;
1972 }
1973
1974 account.getIdentityKeyStore().setIdentityTrustLevel(recipientId, identity.getIdentityKey(), trustLevel);
1975 try {
1976 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
1977 sendVerifiedMessage(address, identity.getIdentityKey(), trustLevel);
1978 } catch (IOException e) {
1979 logger.warn("Failed to send verification sync message: {}", e.getMessage());
1980 }
1981
1982 return true;
1983 }
1984
1985 private void handleIdentityFailure(
1986 final RecipientId recipientId, final SendMessageResult.IdentityFailure identityFailure
1987 ) {
1988 final var identityKey = identityFailure.getIdentityKey();
1989 if (identityKey != null) {
1990 final var newIdentity = account.getIdentityKeyStore().saveIdentity(recipientId, identityKey, new Date());
1991 if (newIdentity) {
1992 account.getSessionStore().archiveSessions(recipientId);
1993 }
1994 } else {
1995 // Retrieve profile to get the current identity key from the server
1996 refreshRecipientProfile(recipientId);
1997 }
1998 }
1999
2000 public String computeSafetyNumber(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
2001 final Fingerprint fingerprint = computeSafetyNumberFingerprint(theirAddress, theirIdentityKey);
2002 return fingerprint == null ? null : fingerprint.getDisplayableFingerprint().getDisplayText();
2003 }
2004
2005 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
2006 final Fingerprint fingerprint = computeSafetyNumberFingerprint(theirAddress, theirIdentityKey);
2007 return fingerprint == null ? null : fingerprint.getScannableFingerprint().getSerialized();
2008 }
2009
2010 private Fingerprint computeSafetyNumberFingerprint(
2011 final SignalServiceAddress theirAddress, final IdentityKey theirIdentityKey
2012 ) {
2013 return Utils.computeSafetyNumber(capabilities.isUuid(),
2014 account.getSelfAddress(),
2015 getIdentityKeyPair().getPublicKey(),
2016 theirAddress,
2017 theirIdentityKey);
2018 }
2019
2020 @Deprecated
2021 public SignalServiceAddress resolveSignalServiceAddress(String identifier) {
2022 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2023
2024 return resolveSignalServiceAddress(address);
2025 }
2026
2027 @Deprecated
2028 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
2029 if (address.matches(account.getSelfAddress())) {
2030 return account.getSelfAddress();
2031 }
2032
2033 return account.getRecipientStore().resolveServiceAddress(address);
2034 }
2035
2036 public SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
2037 return account.getRecipientStore().resolveServiceAddress(recipientId);
2038 }
2039
2040 private String canonicalizePhoneNumber(final String number) throws InvalidNumberException {
2041 return PhoneNumberFormatter.formatNumber(number, account.getUsername());
2042 }
2043
2044 private RecipientId resolveRecipient(final String identifier) {
2045 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2046
2047 return resolveRecipient(address);
2048 }
2049
2050 private RecipientId resolveRecipient(final RecipientIdentifier.Single recipient) {
2051 final SignalServiceAddress address;
2052 if (recipient instanceof RecipientIdentifier.Uuid) {
2053 address = new SignalServiceAddress(((RecipientIdentifier.Uuid) recipient).uuid, null);
2054 } else {
2055 address = new SignalServiceAddress(null, ((RecipientIdentifier.Number) recipient).number);
2056 }
2057
2058 return resolveRecipient(address);
2059 }
2060
2061 public RecipientId resolveRecipient(SignalServiceAddress address) {
2062 return account.getRecipientStore().resolveRecipient(address);
2063 }
2064
2065 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
2066 return account.getRecipientStore().resolveRecipientTrusted(address);
2067 }
2068
2069 private void enqueueJob(Job job) {
2070 var context = new Context(account,
2071 dependencies.getAccountManager(),
2072 dependencies.getMessageReceiver(),
2073 stickerPackStore);
2074 job.run(context);
2075 }
2076
2077 @Override
2078 public void close() throws IOException {
2079 close(true);
2080 }
2081
2082 void close(boolean closeAccount) throws IOException {
2083 executor.shutdown();
2084
2085 dependencies.getSignalWebSocket().disconnect();
2086
2087 if (closeAccount && account != null) {
2088 account.close();
2089 }
2090 account = null;
2091 }
2092
2093 public interface ReceiveMessageHandler {
2094
2095 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
2096 }
2097 }