]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/ManagerImpl.java
Clear queued message actions after handling
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / ManagerImpl.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.actions.HandleAction;
20 import org.asamk.signal.manager.api.Device;
21 import org.asamk.signal.manager.api.Group;
22 import org.asamk.signal.manager.api.Identity;
23 import org.asamk.signal.manager.api.Message;
24 import org.asamk.signal.manager.api.RecipientIdentifier;
25 import org.asamk.signal.manager.api.SendGroupMessageResults;
26 import org.asamk.signal.manager.api.SendMessageResults;
27 import org.asamk.signal.manager.api.TypingAction;
28 import org.asamk.signal.manager.api.UpdateGroup;
29 import org.asamk.signal.manager.config.ServiceConfig;
30 import org.asamk.signal.manager.config.ServiceEnvironmentConfig;
31 import org.asamk.signal.manager.groups.GroupId;
32 import org.asamk.signal.manager.groups.GroupInviteLinkUrl;
33 import org.asamk.signal.manager.groups.GroupNotFoundException;
34 import org.asamk.signal.manager.groups.GroupSendingNotAllowedException;
35 import org.asamk.signal.manager.groups.LastGroupAdminException;
36 import org.asamk.signal.manager.groups.NotAGroupMemberException;
37 import org.asamk.signal.manager.helper.AttachmentHelper;
38 import org.asamk.signal.manager.helper.ContactHelper;
39 import org.asamk.signal.manager.helper.GroupHelper;
40 import org.asamk.signal.manager.helper.GroupV2Helper;
41 import org.asamk.signal.manager.helper.IdentityHelper;
42 import org.asamk.signal.manager.helper.IncomingMessageHandler;
43 import org.asamk.signal.manager.helper.PinHelper;
44 import org.asamk.signal.manager.helper.PreKeyHelper;
45 import org.asamk.signal.manager.helper.ProfileHelper;
46 import org.asamk.signal.manager.helper.SendHelper;
47 import org.asamk.signal.manager.helper.StorageHelper;
48 import org.asamk.signal.manager.helper.SyncHelper;
49 import org.asamk.signal.manager.helper.UnidentifiedAccessHelper;
50 import org.asamk.signal.manager.jobs.Context;
51 import org.asamk.signal.manager.storage.SignalAccount;
52 import org.asamk.signal.manager.storage.groups.GroupInfo;
53 import org.asamk.signal.manager.storage.identities.IdentityInfo;
54 import org.asamk.signal.manager.storage.messageCache.CachedMessage;
55 import org.asamk.signal.manager.storage.recipients.Contact;
56 import org.asamk.signal.manager.storage.recipients.Profile;
57 import org.asamk.signal.manager.storage.recipients.RecipientAddress;
58 import org.asamk.signal.manager.storage.recipients.RecipientId;
59 import org.asamk.signal.manager.storage.stickers.Sticker;
60 import org.asamk.signal.manager.storage.stickers.StickerPackId;
61 import org.asamk.signal.manager.util.KeyUtils;
62 import org.asamk.signal.manager.util.StickerUtils;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65 import org.whispersystems.libsignal.InvalidKeyException;
66 import org.whispersystems.libsignal.ecc.ECPublicKey;
67 import org.whispersystems.libsignal.util.Pair;
68 import org.whispersystems.libsignal.util.guava.Optional;
69 import org.whispersystems.signalservice.api.SignalSessionLock;
70 import org.whispersystems.signalservice.api.groupsv2.GroupLinkNotActiveException;
71 import org.whispersystems.signalservice.api.messages.SendMessageResult;
72 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentRemoteId;
73 import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
74 import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
75 import org.whispersystems.signalservice.api.messages.SignalServiceReceiptMessage;
76 import org.whispersystems.signalservice.api.messages.SignalServiceTypingMessage;
77 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
78 import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
79 import org.whispersystems.signalservice.api.util.DeviceNameUtil;
80 import org.whispersystems.signalservice.api.util.InvalidNumberException;
81 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
82 import org.whispersystems.signalservice.api.websocket.WebSocketUnavailableException;
83 import org.whispersystems.signalservice.internal.contacts.crypto.Quote;
84 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedQuoteException;
85 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedResponseException;
86 import org.whispersystems.signalservice.internal.util.DynamicCredentialsProvider;
87 import org.whispersystems.signalservice.internal.util.Hex;
88 import org.whispersystems.signalservice.internal.util.Util;
89
90 import java.io.File;
91 import java.io.IOException;
92 import java.net.URI;
93 import java.net.URISyntaxException;
94 import java.net.URLEncoder;
95 import java.nio.charset.StandardCharsets;
96 import java.security.SignatureException;
97 import java.util.Collection;
98 import java.util.HashMap;
99 import java.util.HashSet;
100 import java.util.List;
101 import java.util.Map;
102 import java.util.Set;
103 import java.util.UUID;
104 import java.util.concurrent.ExecutorService;
105 import java.util.concurrent.Executors;
106 import java.util.concurrent.TimeUnit;
107 import java.util.concurrent.TimeoutException;
108 import java.util.concurrent.locks.ReentrantLock;
109 import java.util.stream.Collectors;
110
111 import static org.asamk.signal.manager.config.ServiceConfig.capabilities;
112
113 public class ManagerImpl implements Manager {
114
115 private final static Logger logger = LoggerFactory.getLogger(ManagerImpl.class);
116
117 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
118 private final SignalDependencies dependencies;
119
120 private SignalAccount account;
121
122 private final ExecutorService executor = Executors.newCachedThreadPool();
123
124 private final ProfileHelper profileHelper;
125 private final PinHelper pinHelper;
126 private final StorageHelper storageHelper;
127 private final SendHelper sendHelper;
128 private final SyncHelper syncHelper;
129 private final AttachmentHelper attachmentHelper;
130 private final GroupHelper groupHelper;
131 private final ContactHelper contactHelper;
132 private final IncomingMessageHandler incomingMessageHandler;
133 private final PreKeyHelper preKeyHelper;
134 private final IdentityHelper identityHelper;
135
136 private final Context context;
137 private boolean hasCaughtUpWithOldMessages = false;
138
139 ManagerImpl(
140 SignalAccount account,
141 PathConfig pathConfig,
142 ServiceEnvironmentConfig serviceEnvironmentConfig,
143 String userAgent
144 ) {
145 this.account = account;
146 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
147
148 final var credentialsProvider = new DynamicCredentialsProvider(account.getUuid(),
149 account.getUsername(),
150 account.getPassword(),
151 account.getDeviceId());
152 final var sessionLock = new SignalSessionLock() {
153 private final ReentrantLock LEGACY_LOCK = new ReentrantLock();
154
155 @Override
156 public Lock acquire() {
157 LEGACY_LOCK.lock();
158 return LEGACY_LOCK::unlock;
159 }
160 };
161 this.dependencies = new SignalDependencies(serviceEnvironmentConfig,
162 userAgent,
163 credentialsProvider,
164 account.getSignalProtocolStore(),
165 executor,
166 sessionLock);
167 final var avatarStore = new AvatarStore(pathConfig.getAvatarsPath());
168 final var attachmentStore = new AttachmentStore(pathConfig.getAttachmentsPath());
169 final var stickerPackStore = new StickerPackStore(pathConfig.getStickerPacksPath());
170
171 this.attachmentHelper = new AttachmentHelper(dependencies, attachmentStore);
172 this.pinHelper = new PinHelper(dependencies.getKeyBackupService());
173 final var unidentifiedAccessHelper = new UnidentifiedAccessHelper(account,
174 dependencies,
175 account::getProfileKey,
176 this::getRecipientProfile);
177 this.profileHelper = new ProfileHelper(account,
178 dependencies,
179 avatarStore,
180 unidentifiedAccessHelper::getAccessFor,
181 this::resolveSignalServiceAddress);
182 final GroupV2Helper groupV2Helper = new GroupV2Helper(profileHelper::getRecipientProfileKeyCredential,
183 this::getRecipientProfile,
184 account::getSelfRecipientId,
185 dependencies.getGroupsV2Operations(),
186 dependencies.getGroupsV2Api(),
187 this::resolveSignalServiceAddress);
188 this.sendHelper = new SendHelper(account,
189 dependencies,
190 unidentifiedAccessHelper,
191 this::resolveSignalServiceAddress,
192 account.getRecipientStore(),
193 this::handleIdentityFailure,
194 this::getGroupInfo,
195 this::refreshRegisteredUser);
196 this.groupHelper = new GroupHelper(account,
197 dependencies,
198 attachmentHelper,
199 sendHelper,
200 groupV2Helper,
201 avatarStore,
202 this::resolveSignalServiceAddress,
203 account.getRecipientStore());
204 this.storageHelper = new StorageHelper(account, dependencies, groupHelper, profileHelper);
205 this.contactHelper = new ContactHelper(account);
206 this.syncHelper = new SyncHelper(account,
207 attachmentHelper,
208 sendHelper,
209 groupHelper,
210 avatarStore,
211 this::resolveSignalServiceAddress);
212 preKeyHelper = new PreKeyHelper(account, dependencies);
213
214 this.context = new Context(account,
215 dependencies,
216 stickerPackStore,
217 sendHelper,
218 groupHelper,
219 syncHelper,
220 profileHelper,
221 storageHelper,
222 preKeyHelper);
223 var jobExecutor = new JobExecutor(context);
224
225 this.incomingMessageHandler = new IncomingMessageHandler(account,
226 dependencies,
227 account.getRecipientStore(),
228 this::resolveSignalServiceAddress,
229 groupHelper,
230 contactHelper,
231 attachmentHelper,
232 syncHelper,
233 this::getRecipientProfile,
234 jobExecutor);
235 this.identityHelper = new IdentityHelper(account,
236 dependencies,
237 this::resolveSignalServiceAddress,
238 syncHelper,
239 profileHelper);
240 }
241
242 @Override
243 public String getSelfNumber() {
244 return account.getUsername();
245 }
246
247 @Override
248 public void checkAccountState() throws IOException {
249 if (account.getLastReceiveTimestamp() == 0) {
250 logger.info("The Signal protocol expects that incoming messages are regularly received.");
251 } else {
252 var diffInMilliseconds = System.currentTimeMillis() - account.getLastReceiveTimestamp();
253 long days = TimeUnit.DAYS.convert(diffInMilliseconds, TimeUnit.MILLISECONDS);
254 if (days > 7) {
255 logger.warn(
256 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
257 days);
258 }
259 }
260 preKeyHelper.refreshPreKeysIfNecessary();
261 if (account.getUuid() == null) {
262 account.setUuid(dependencies.getAccountManager().getOwnUuid());
263 }
264 updateAccountAttributes(null);
265 }
266
267 /**
268 * This is used for checking a set of phone numbers for registration on Signal
269 *
270 * @param numbers The set of phone number in question
271 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
272 * @throws IOException if its unable to get the contacts to check if they're registered
273 */
274 @Override
275 public Map<String, Pair<String, UUID>> areUsersRegistered(Set<String> numbers) throws IOException {
276 Map<String, String> canonicalizedNumbers = numbers.stream().collect(Collectors.toMap(n -> n, n -> {
277 try {
278 return PhoneNumberFormatter.formatNumber(n, account.getUsername());
279 } catch (InvalidNumberException e) {
280 return "";
281 }
282 }));
283
284 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
285 var registeredUsers = getRegisteredUsers(canonicalizedNumbers.values()
286 .stream()
287 .filter(s -> !s.isEmpty())
288 .collect(Collectors.toSet()));
289
290 return numbers.stream().collect(Collectors.toMap(n -> n, n -> {
291 final var number = canonicalizedNumbers.get(n);
292 final var uuid = registeredUsers.get(number);
293 return new Pair<>(number.isEmpty() ? null : number, uuid);
294 }));
295 }
296
297 @Override
298 public void updateAccountAttributes(String deviceName) throws IOException {
299 final String encryptedDeviceName;
300 if (deviceName == null) {
301 encryptedDeviceName = account.getEncryptedDeviceName();
302 } else {
303 final var privateKey = account.getIdentityKeyPair().getPrivateKey();
304 encryptedDeviceName = DeviceNameUtil.encryptDeviceName(deviceName, privateKey);
305 account.setEncryptedDeviceName(encryptedDeviceName);
306 }
307 dependencies.getAccountManager()
308 .setAccountAttributes(encryptedDeviceName,
309 null,
310 account.getLocalRegistrationId(),
311 true,
312 null,
313 account.getPinMasterKey() == null ? null : account.getPinMasterKey().deriveRegistrationLock(),
314 account.getSelfUnidentifiedAccessKey(),
315 account.isUnrestrictedUnidentifiedAccess(),
316 capabilities,
317 account.isDiscoverableByPhoneNumber());
318 }
319
320 @Override
321 public void updateConfiguration(
322 final Boolean readReceipts,
323 final Boolean unidentifiedDeliveryIndicators,
324 final Boolean typingIndicators,
325 final Boolean linkPreviews
326 ) throws IOException, NotMasterDeviceException {
327 if (!account.isMasterDevice()) {
328 throw new NotMasterDeviceException();
329 }
330
331 final var configurationStore = account.getConfigurationStore();
332 if (readReceipts != null) {
333 configurationStore.setReadReceipts(readReceipts);
334 }
335 if (unidentifiedDeliveryIndicators != null) {
336 configurationStore.setUnidentifiedDeliveryIndicators(unidentifiedDeliveryIndicators);
337 }
338 if (typingIndicators != null) {
339 configurationStore.setTypingIndicators(typingIndicators);
340 }
341 if (linkPreviews != null) {
342 configurationStore.setLinkPreviews(linkPreviews);
343 }
344 syncHelper.sendConfigurationMessage();
345 }
346
347 /**
348 * @param givenName if null, the previous givenName will be kept
349 * @param familyName if null, the previous familyName will be kept
350 * @param about if null, the previous about text will be kept
351 * @param aboutEmoji if null, the previous about emoji will be kept
352 * @param avatar if avatar is null the image from the local avatar store is used (if present),
353 */
354 @Override
355 public void setProfile(
356 String givenName, final String familyName, String about, String aboutEmoji, Optional<File> avatar
357 ) throws IOException {
358 profileHelper.setProfile(givenName, familyName, about, aboutEmoji, avatar);
359 syncHelper.sendSyncFetchProfileMessage();
360 }
361
362 @Override
363 public void unregister() throws IOException {
364 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
365 // If this is the master device, other users can't send messages to this number anymore.
366 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
367 dependencies.getAccountManager().setGcmId(Optional.absent());
368
369 account.setRegistered(false);
370 }
371
372 @Override
373 public void deleteAccount() throws IOException {
374 try {
375 pinHelper.removeRegistrationLockPin();
376 } catch (UnauthenticatedResponseException e) {
377 logger.warn("Failed to remove registration lock pin");
378 }
379 account.setRegistrationLockPin(null, null);
380
381 dependencies.getAccountManager().deleteAccount();
382
383 account.setRegistered(false);
384 }
385
386 @Override
387 public void submitRateLimitRecaptchaChallenge(String challenge, String captcha) throws IOException {
388 dependencies.getAccountManager().submitRateLimitRecaptchaChallenge(challenge, captcha);
389 }
390
391 @Override
392 public List<Device> getLinkedDevices() throws IOException {
393 var devices = dependencies.getAccountManager().getDevices();
394 account.setMultiDevice(devices.size() > 1);
395 var identityKey = account.getIdentityKeyPair().getPrivateKey();
396 return devices.stream().map(d -> {
397 String deviceName = d.getName();
398 if (deviceName != null) {
399 try {
400 deviceName = DeviceNameUtil.decryptDeviceName(deviceName, identityKey);
401 } catch (IOException e) {
402 logger.debug("Failed to decrypt device name, maybe plain text?", e);
403 }
404 }
405 return new Device(d.getId(),
406 deviceName,
407 d.getCreated(),
408 d.getLastSeen(),
409 d.getId() == account.getDeviceId());
410 }).collect(Collectors.toList());
411 }
412
413 @Override
414 public void removeLinkedDevices(long deviceId) throws IOException {
415 dependencies.getAccountManager().removeDevice(deviceId);
416 var devices = dependencies.getAccountManager().getDevices();
417 account.setMultiDevice(devices.size() > 1);
418 }
419
420 @Override
421 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
422 var info = DeviceLinkInfo.parseDeviceLinkUri(linkUri);
423
424 addDevice(info.deviceIdentifier, info.deviceKey);
425 }
426
427 private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
428 var identityKeyPair = account.getIdentityKeyPair();
429 var verificationCode = dependencies.getAccountManager().getNewDeviceVerificationCode();
430
431 dependencies.getAccountManager()
432 .addDevice(deviceIdentifier,
433 deviceKey,
434 identityKeyPair,
435 Optional.of(account.getProfileKey().serialize()),
436 verificationCode);
437 account.setMultiDevice(true);
438 }
439
440 @Override
441 public void setRegistrationLockPin(Optional<String> pin) throws IOException, UnauthenticatedResponseException {
442 if (!account.isMasterDevice()) {
443 throw new RuntimeException("Only master device can set a PIN");
444 }
445 if (pin.isPresent()) {
446 final var masterKey = account.getPinMasterKey() != null
447 ? account.getPinMasterKey()
448 : KeyUtils.createMasterKey();
449
450 pinHelper.setRegistrationLockPin(pin.get(), masterKey);
451
452 account.setRegistrationLockPin(pin.get(), masterKey);
453 } else {
454 // Remove KBS Pin
455 pinHelper.removeRegistrationLockPin();
456
457 account.setRegistrationLockPin(null, null);
458 }
459 }
460
461 void refreshPreKeys() throws IOException {
462 preKeyHelper.refreshPreKeys();
463 }
464
465 @Override
466 public Profile getRecipientProfile(RecipientIdentifier.Single recipient) throws UnregisteredUserException {
467 return profileHelper.getRecipientProfile(resolveRecipient(recipient));
468 }
469
470 private Profile getRecipientProfile(RecipientId recipientId) {
471 return profileHelper.getRecipientProfile(recipientId);
472 }
473
474 @Override
475 public List<Group> getGroups() {
476 return account.getGroupStore().getGroups().stream().map(this::toGroup).collect(Collectors.toList());
477 }
478
479 private Group toGroup(final GroupInfo groupInfo) {
480 if (groupInfo == null) {
481 return null;
482 }
483
484 return new Group(groupInfo.getGroupId(),
485 groupInfo.getTitle(),
486 groupInfo.getDescription(),
487 groupInfo.getGroupInviteLink(),
488 groupInfo.getMembers()
489 .stream()
490 .map(account.getRecipientStore()::resolveRecipientAddress)
491 .collect(Collectors.toSet()),
492 groupInfo.getPendingMembers()
493 .stream()
494 .map(account.getRecipientStore()::resolveRecipientAddress)
495 .collect(Collectors.toSet()),
496 groupInfo.getRequestingMembers()
497 .stream()
498 .map(account.getRecipientStore()::resolveRecipientAddress)
499 .collect(Collectors.toSet()),
500 groupInfo.getAdminMembers()
501 .stream()
502 .map(account.getRecipientStore()::resolveRecipientAddress)
503 .collect(Collectors.toSet()),
504 groupInfo.isBlocked(),
505 groupInfo.getMessageExpirationTimer(),
506 groupInfo.getPermissionAddMember(),
507 groupInfo.getPermissionEditDetails(),
508 groupInfo.getPermissionSendMessage(),
509 groupInfo.isMember(account.getSelfRecipientId()),
510 groupInfo.isAdmin(account.getSelfRecipientId()));
511 }
512
513 @Override
514 public SendGroupMessageResults quitGroup(
515 GroupId groupId, Set<RecipientIdentifier.Single> groupAdmins
516 ) throws GroupNotFoundException, IOException, NotAGroupMemberException, LastGroupAdminException {
517 final var newAdmins = resolveRecipients(groupAdmins);
518 return groupHelper.quitGroup(groupId, newAdmins);
519 }
520
521 @Override
522 public void deleteGroup(GroupId groupId) throws IOException {
523 groupHelper.deleteGroup(groupId);
524 }
525
526 @Override
527 public Pair<GroupId, SendGroupMessageResults> createGroup(
528 String name, Set<RecipientIdentifier.Single> members, File avatarFile
529 ) throws IOException, AttachmentInvalidException {
530 return groupHelper.createGroup(name, members == null ? null : resolveRecipients(members), avatarFile);
531 }
532
533 @Override
534 public SendGroupMessageResults updateGroup(
535 final GroupId groupId, final UpdateGroup updateGroup
536 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException, GroupSendingNotAllowedException {
537 return groupHelper.updateGroup(groupId,
538 updateGroup.getName(),
539 updateGroup.getDescription(),
540 updateGroup.getMembers() == null ? null : resolveRecipients(updateGroup.getMembers()),
541 updateGroup.getRemoveMembers() == null ? null : resolveRecipients(updateGroup.getRemoveMembers()),
542 updateGroup.getAdmins() == null ? null : resolveRecipients(updateGroup.getAdmins()),
543 updateGroup.getRemoveAdmins() == null ? null : resolveRecipients(updateGroup.getRemoveAdmins()),
544 updateGroup.isResetGroupLink(),
545 updateGroup.getGroupLinkState(),
546 updateGroup.getAddMemberPermission(),
547 updateGroup.getEditDetailsPermission(),
548 updateGroup.getAvatarFile(),
549 updateGroup.getExpirationTimer(),
550 updateGroup.getIsAnnouncementGroup());
551 }
552
553 @Override
554 public Pair<GroupId, SendGroupMessageResults> joinGroup(
555 GroupInviteLinkUrl inviteLinkUrl
556 ) throws IOException, GroupLinkNotActiveException {
557 return groupHelper.joinGroup(inviteLinkUrl);
558 }
559
560 private SendMessageResults sendMessage(
561 SignalServiceDataMessage.Builder messageBuilder, Set<RecipientIdentifier> recipients
562 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
563 var results = new HashMap<RecipientIdentifier, List<SendMessageResult>>();
564 long timestamp = System.currentTimeMillis();
565 messageBuilder.withTimestamp(timestamp);
566 for (final var recipient : recipients) {
567 if (recipient instanceof RecipientIdentifier.Single) {
568 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
569 final var result = sendHelper.sendMessage(messageBuilder, recipientId);
570 results.put(recipient, List.of(result));
571 } else if (recipient instanceof RecipientIdentifier.NoteToSelf) {
572 final var result = sendHelper.sendSelfMessage(messageBuilder);
573 results.put(recipient, List.of(result));
574 } else if (recipient instanceof RecipientIdentifier.Group) {
575 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
576 final var result = sendHelper.sendAsGroupMessage(messageBuilder, groupId);
577 results.put(recipient, result);
578 }
579 }
580 return new SendMessageResults(timestamp, results);
581 }
582
583 private void sendTypingMessage(
584 SignalServiceTypingMessage.Action action, Set<RecipientIdentifier> recipients
585 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
586 final var timestamp = System.currentTimeMillis();
587 for (var recipient : recipients) {
588 if (recipient instanceof RecipientIdentifier.Single) {
589 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.absent());
590 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
591 sendHelper.sendTypingMessage(message, recipientId);
592 } else if (recipient instanceof RecipientIdentifier.Group) {
593 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
594 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.of(groupId.serialize()));
595 sendHelper.sendGroupTypingMessage(message, groupId);
596 }
597 }
598 }
599
600 @Override
601 public void sendTypingMessage(
602 TypingAction action, Set<RecipientIdentifier> recipients
603 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
604 sendTypingMessage(action.toSignalService(), recipients);
605 }
606
607 @Override
608 public void sendReadReceipt(
609 RecipientIdentifier.Single sender, List<Long> messageIds
610 ) throws IOException, UntrustedIdentityException {
611 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.READ,
612 messageIds,
613 System.currentTimeMillis());
614
615 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
616 }
617
618 @Override
619 public void sendViewedReceipt(
620 RecipientIdentifier.Single sender, List<Long> messageIds
621 ) throws IOException, UntrustedIdentityException {
622 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.VIEWED,
623 messageIds,
624 System.currentTimeMillis());
625
626 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
627 }
628
629 @Override
630 public SendMessageResults sendMessage(
631 Message message, Set<RecipientIdentifier> recipients
632 ) throws IOException, AttachmentInvalidException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
633 final var messageBuilder = SignalServiceDataMessage.newBuilder();
634 applyMessage(messageBuilder, message);
635 return sendMessage(messageBuilder, recipients);
636 }
637
638 private void applyMessage(
639 final SignalServiceDataMessage.Builder messageBuilder, final Message message
640 ) throws AttachmentInvalidException, IOException {
641 messageBuilder.withBody(message.getMessageText());
642 final var attachments = message.getAttachments();
643 if (attachments != null) {
644 messageBuilder.withAttachments(attachmentHelper.uploadAttachments(attachments));
645 }
646 }
647
648 @Override
649 public SendMessageResults sendRemoteDeleteMessage(
650 long targetSentTimestamp, Set<RecipientIdentifier> recipients
651 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
652 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
653 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
654 return sendMessage(messageBuilder, recipients);
655 }
656
657 @Override
658 public SendMessageResults sendMessageReaction(
659 String emoji,
660 boolean remove,
661 RecipientIdentifier.Single targetAuthor,
662 long targetSentTimestamp,
663 Set<RecipientIdentifier> recipients
664 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
665 var targetAuthorRecipientId = resolveRecipient(targetAuthor);
666 var reaction = new SignalServiceDataMessage.Reaction(emoji,
667 remove,
668 resolveSignalServiceAddress(targetAuthorRecipientId),
669 targetSentTimestamp);
670 final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
671 return sendMessage(messageBuilder, recipients);
672 }
673
674 @Override
675 public SendMessageResults sendEndSessionMessage(Set<RecipientIdentifier.Single> recipients) throws IOException {
676 var messageBuilder = SignalServiceDataMessage.newBuilder().asEndSessionMessage();
677
678 try {
679 return sendMessage(messageBuilder,
680 recipients.stream().map(RecipientIdentifier.class::cast).collect(Collectors.toSet()));
681 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
682 throw new AssertionError(e);
683 } finally {
684 for (var recipient : recipients) {
685 final var recipientId = resolveRecipient(recipient);
686 account.getSessionStore().deleteAllSessions(recipientId);
687 }
688 }
689 }
690
691 @Override
692 public void setContactName(
693 RecipientIdentifier.Single recipient, String name
694 ) throws NotMasterDeviceException, UnregisteredUserException {
695 if (!account.isMasterDevice()) {
696 throw new NotMasterDeviceException();
697 }
698 contactHelper.setContactName(resolveRecipient(recipient), name);
699 }
700
701 @Override
702 public void setContactBlocked(
703 RecipientIdentifier.Single recipient, boolean blocked
704 ) throws NotMasterDeviceException, IOException {
705 if (!account.isMasterDevice()) {
706 throw new NotMasterDeviceException();
707 }
708 contactHelper.setContactBlocked(resolveRecipient(recipient), blocked);
709 // TODO cycle our profile key
710 syncHelper.sendBlockedList();
711 }
712
713 @Override
714 public void setGroupBlocked(
715 final GroupId groupId, final boolean blocked
716 ) throws GroupNotFoundException, IOException, NotMasterDeviceException {
717 if (!account.isMasterDevice()) {
718 throw new NotMasterDeviceException();
719 }
720 groupHelper.setGroupBlocked(groupId, blocked);
721 // TODO cycle our profile key
722 syncHelper.sendBlockedList();
723 }
724
725 /**
726 * Change the expiration timer for a contact
727 */
728 @Override
729 public void setExpirationTimer(
730 RecipientIdentifier.Single recipient, int messageExpirationTimer
731 ) throws IOException {
732 var recipientId = resolveRecipient(recipient);
733 contactHelper.setExpirationTimer(recipientId, messageExpirationTimer);
734 final var messageBuilder = SignalServiceDataMessage.newBuilder().asExpirationUpdate();
735 try {
736 sendMessage(messageBuilder, Set.of(recipient));
737 } catch (NotAGroupMemberException | GroupNotFoundException | GroupSendingNotAllowedException e) {
738 throw new AssertionError(e);
739 }
740 }
741
742 /**
743 * Upload the sticker pack from path.
744 *
745 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
746 * @return if successful, returns the URL to install the sticker pack in the signal app
747 */
748 @Override
749 public URI uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
750 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
751
752 var messageSender = dependencies.getMessageSender();
753
754 var packKey = KeyUtils.createStickerUploadKey();
755 var packIdString = messageSender.uploadStickerManifest(manifest, packKey);
756 var packId = StickerPackId.deserialize(Hex.fromStringCondensed(packIdString));
757
758 var sticker = new Sticker(packId, packKey);
759 account.getStickerStore().updateSticker(sticker);
760
761 try {
762 return new URI("https",
763 "signal.art",
764 "/addstickers/",
765 "pack_id="
766 + URLEncoder.encode(Hex.toStringCondensed(packId.serialize()), StandardCharsets.UTF_8)
767 + "&pack_key="
768 + URLEncoder.encode(Hex.toStringCondensed(packKey), StandardCharsets.UTF_8));
769 } catch (URISyntaxException e) {
770 throw new AssertionError(e);
771 }
772 }
773
774 @Override
775 public void requestAllSyncData() throws IOException {
776 syncHelper.requestAllSyncData();
777 retrieveRemoteStorage();
778 }
779
780 void retrieveRemoteStorage() throws IOException {
781 if (account.getStorageKey() != null) {
782 storageHelper.readDataFromStorage();
783 }
784 }
785
786 private RecipientId refreshRegisteredUser(RecipientId recipientId) throws IOException {
787 final var address = resolveSignalServiceAddress(recipientId);
788 if (!address.getNumber().isPresent()) {
789 return recipientId;
790 }
791 final var number = address.getNumber().get();
792 final var uuid = getRegisteredUser(number);
793 return resolveRecipientTrusted(new SignalServiceAddress(uuid, number));
794 }
795
796 private UUID getRegisteredUser(final String number) throws IOException {
797 final Map<String, UUID> uuidMap;
798 try {
799 uuidMap = getRegisteredUsers(Set.of(number));
800 } catch (NumberFormatException e) {
801 throw new UnregisteredUserException(number, e);
802 }
803 final var uuid = uuidMap.get(number);
804 if (uuid == null) {
805 throw new UnregisteredUserException(number, null);
806 }
807 return uuid;
808 }
809
810 private Map<String, UUID> getRegisteredUsers(final Set<String> numbers) throws IOException {
811 final Map<String, UUID> registeredUsers;
812 try {
813 registeredUsers = dependencies.getAccountManager()
814 .getRegisteredUsers(ServiceConfig.getIasKeyStore(),
815 numbers,
816 serviceEnvironmentConfig.getCdsMrenclave());
817 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
818 throw new IOException(e);
819 }
820
821 // Store numbers as recipients so we have the number/uuid association
822 registeredUsers.forEach((number, uuid) -> resolveRecipientTrusted(new SignalServiceAddress(uuid, number)));
823
824 return registeredUsers;
825 }
826
827 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
828 Set<HandleAction> queuedActions = new HashSet<>();
829 for (var cachedMessage : account.getMessageCache().getCachedMessages()) {
830 var actions = retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
831 if (actions != null) {
832 queuedActions.addAll(actions);
833 }
834 }
835 handleQueuedActions(queuedActions);
836 }
837
838 private List<HandleAction> retryFailedReceivedMessage(
839 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
840 ) {
841 var envelope = cachedMessage.loadEnvelope();
842 if (envelope == null) {
843 cachedMessage.delete();
844 return null;
845 }
846
847 final var result = incomingMessageHandler.handleRetryEnvelope(envelope, ignoreAttachments, handler);
848 final var actions = result.first();
849 final var exception = result.second();
850
851 if (exception instanceof UntrustedIdentityException) {
852 if (System.currentTimeMillis() - envelope.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
853 // Envelope is more than a month old, cleaning up.
854 cachedMessage.delete();
855 return null;
856 }
857 if (!envelope.hasSourceUuid()) {
858 final var identifier = ((UntrustedIdentityException) exception).getSender();
859 final var recipientId = account.getRecipientStore().resolveRecipient(identifier);
860 try {
861 account.getMessageCache().replaceSender(cachedMessage, recipientId);
862 } catch (IOException ioException) {
863 logger.warn("Failed to move cached message to recipient folder: {}", ioException.getMessage());
864 }
865 }
866 return null;
867 }
868
869 // If successful and for all other errors that are not recoverable, delete the cached message
870 cachedMessage.delete();
871 return actions;
872 }
873
874 @Override
875 public void receiveMessages(
876 long timeout,
877 TimeUnit unit,
878 boolean returnOnTimeout,
879 boolean ignoreAttachments,
880 ReceiveMessageHandler handler
881 ) throws IOException {
882 retryFailedReceivedMessages(handler, ignoreAttachments);
883
884 Set<HandleAction> queuedActions = new HashSet<>();
885
886 final var signalWebSocket = dependencies.getSignalWebSocket();
887 signalWebSocket.connect();
888
889 hasCaughtUpWithOldMessages = false;
890
891 while (!Thread.interrupted()) {
892 SignalServiceEnvelope envelope;
893 final CachedMessage[] cachedMessage = {null};
894 account.setLastReceiveTimestamp(System.currentTimeMillis());
895 logger.debug("Checking for new message from server");
896 try {
897 var result = signalWebSocket.readOrEmpty(unit.toMillis(timeout), envelope1 -> {
898 final var recipientId = envelope1.hasSourceUuid()
899 ? resolveRecipient(envelope1.getSourceAddress())
900 : null;
901 // store message on disk, before acknowledging receipt to the server
902 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
903 });
904 if (result.isPresent()) {
905 envelope = result.get();
906 logger.debug("New message received from server");
907 } else {
908 logger.debug("Received indicator that server queue is empty");
909 handleQueuedActions(queuedActions);
910 queuedActions.clear();
911
912 hasCaughtUpWithOldMessages = true;
913 synchronized (this) {
914 this.notifyAll();
915 }
916
917 // Continue to wait another timeout for new messages
918 continue;
919 }
920 } catch (AssertionError e) {
921 if (e.getCause() instanceof InterruptedException) {
922 Thread.currentThread().interrupt();
923 break;
924 } else {
925 throw e;
926 }
927 } catch (WebSocketUnavailableException e) {
928 logger.debug("Pipe unexpectedly unavailable, connecting");
929 signalWebSocket.connect();
930 continue;
931 } catch (TimeoutException e) {
932 if (returnOnTimeout) return;
933 continue;
934 }
935
936 final var result = incomingMessageHandler.handleEnvelope(envelope, ignoreAttachments, handler);
937 queuedActions.addAll(result.first());
938 final var exception = result.second();
939
940 if (hasCaughtUpWithOldMessages) {
941 handleQueuedActions(queuedActions);
942 queuedActions.clear();
943 }
944 if (cachedMessage[0] != null) {
945 if (exception instanceof UntrustedIdentityException) {
946 logger.debug("Keeping message with untrusted identity in message cache");
947 final var address = ((UntrustedIdentityException) exception).getSender();
948 final var recipientId = resolveRecipient(address);
949 if (!envelope.hasSourceUuid()) {
950 try {
951 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
952 } catch (IOException ioException) {
953 logger.warn("Failed to move cached message to recipient folder: {}",
954 ioException.getMessage());
955 }
956 }
957 } else {
958 cachedMessage[0].delete();
959 }
960 }
961 }
962 handleQueuedActions(queuedActions);
963 queuedActions.clear();
964 }
965
966 @Override
967 public boolean hasCaughtUpWithOldMessages() {
968 return hasCaughtUpWithOldMessages;
969 }
970
971 private void handleQueuedActions(final Collection<HandleAction> queuedActions) {
972 logger.debug("Handling message actions");
973 var interrupted = false;
974 for (var action : queuedActions) {
975 try {
976 action.execute(context);
977 } catch (Throwable e) {
978 if ((e instanceof AssertionError || e instanceof RuntimeException)
979 && e.getCause() instanceof InterruptedException) {
980 interrupted = true;
981 continue;
982 }
983 logger.warn("Message action failed.", e);
984 }
985 }
986 if (interrupted) {
987 Thread.currentThread().interrupt();
988 }
989 }
990
991 @Override
992 public boolean isContactBlocked(final RecipientIdentifier.Single recipient) {
993 final RecipientId recipientId;
994 try {
995 recipientId = resolveRecipient(recipient);
996 } catch (UnregisteredUserException e) {
997 return false;
998 }
999 return contactHelper.isContactBlocked(recipientId);
1000 }
1001
1002 @Override
1003 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
1004 return attachmentHelper.getAttachmentFile(attachmentId);
1005 }
1006
1007 @Override
1008 public void sendContacts() throws IOException {
1009 syncHelper.sendContacts();
1010 }
1011
1012 @Override
1013 public List<Pair<RecipientAddress, Contact>> getContacts() {
1014 return account.getContactStore()
1015 .getContacts()
1016 .stream()
1017 .map(p -> new Pair<>(account.getRecipientStore().resolveRecipientAddress(p.first()), p.second()))
1018 .collect(Collectors.toList());
1019 }
1020
1021 @Override
1022 public String getContactOrProfileName(RecipientIdentifier.Single recipient) {
1023 final RecipientId recipientId;
1024 try {
1025 recipientId = resolveRecipient(recipient);
1026 } catch (UnregisteredUserException e) {
1027 return null;
1028 }
1029
1030 final var contact = account.getContactStore().getContact(recipientId);
1031 if (contact != null && !Util.isEmpty(contact.getName())) {
1032 return contact.getName();
1033 }
1034
1035 final var profile = getRecipientProfile(recipientId);
1036 if (profile != null) {
1037 return profile.getDisplayName();
1038 }
1039
1040 return null;
1041 }
1042
1043 @Override
1044 public Group getGroup(GroupId groupId) {
1045 return toGroup(groupHelper.getGroup(groupId));
1046 }
1047
1048 private GroupInfo getGroupInfo(GroupId groupId) {
1049 return groupHelper.getGroup(groupId);
1050 }
1051
1052 @Override
1053 public List<Identity> getIdentities() {
1054 return account.getIdentityKeyStore()
1055 .getIdentities()
1056 .stream()
1057 .map(this::toIdentity)
1058 .collect(Collectors.toList());
1059 }
1060
1061 private Identity toIdentity(final IdentityInfo identityInfo) {
1062 if (identityInfo == null) {
1063 return null;
1064 }
1065
1066 final var address = account.getRecipientStore().resolveRecipientAddress(identityInfo.getRecipientId());
1067 return new Identity(address,
1068 identityInfo.getIdentityKey(),
1069 identityHelper.computeSafetyNumber(identityInfo.getRecipientId(), identityInfo.getIdentityKey()),
1070 identityHelper.computeSafetyNumberForScanning(identityInfo.getRecipientId(),
1071 identityInfo.getIdentityKey()).getSerialized(),
1072 identityInfo.getTrustLevel(),
1073 identityInfo.getDateAdded());
1074 }
1075
1076 @Override
1077 public List<Identity> getIdentities(RecipientIdentifier.Single recipient) {
1078 IdentityInfo identity;
1079 try {
1080 identity = account.getIdentityKeyStore().getIdentity(resolveRecipient(recipient));
1081 } catch (UnregisteredUserException e) {
1082 identity = null;
1083 }
1084 return identity == null ? List.of() : List.of(toIdentity(identity));
1085 }
1086
1087 /**
1088 * Trust this the identity with this fingerprint
1089 *
1090 * @param recipient username of the identity
1091 * @param fingerprint Fingerprint
1092 */
1093 @Override
1094 public boolean trustIdentityVerified(RecipientIdentifier.Single recipient, byte[] fingerprint) {
1095 RecipientId recipientId;
1096 try {
1097 recipientId = resolveRecipient(recipient);
1098 } catch (UnregisteredUserException e) {
1099 return false;
1100 }
1101 return identityHelper.trustIdentityVerified(recipientId, fingerprint);
1102 }
1103
1104 /**
1105 * Trust this the identity with this safety number
1106 *
1107 * @param recipient username of the identity
1108 * @param safetyNumber Safety number
1109 */
1110 @Override
1111 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, String safetyNumber) {
1112 RecipientId recipientId;
1113 try {
1114 recipientId = resolveRecipient(recipient);
1115 } catch (UnregisteredUserException e) {
1116 return false;
1117 }
1118 return identityHelper.trustIdentityVerifiedSafetyNumber(recipientId, safetyNumber);
1119 }
1120
1121 /**
1122 * Trust this the identity with this scannable safety number
1123 *
1124 * @param recipient username of the identity
1125 * @param safetyNumber Scannable safety number
1126 */
1127 @Override
1128 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, byte[] safetyNumber) {
1129 RecipientId recipientId;
1130 try {
1131 recipientId = resolveRecipient(recipient);
1132 } catch (UnregisteredUserException e) {
1133 return false;
1134 }
1135 return identityHelper.trustIdentityVerifiedSafetyNumber(recipientId, safetyNumber);
1136 }
1137
1138 /**
1139 * Trust all keys of this identity without verification
1140 *
1141 * @param recipient username of the identity
1142 */
1143 @Override
1144 public boolean trustIdentityAllKeys(RecipientIdentifier.Single recipient) {
1145 RecipientId recipientId;
1146 try {
1147 recipientId = resolveRecipient(recipient);
1148 } catch (UnregisteredUserException e) {
1149 return false;
1150 }
1151 return identityHelper.trustIdentityAllKeys(recipientId);
1152 }
1153
1154 private void handleIdentityFailure(
1155 final RecipientId recipientId, final SendMessageResult.IdentityFailure identityFailure
1156 ) {
1157 this.identityHelper.handleIdentityFailure(recipientId, identityFailure);
1158 }
1159
1160 @Override
1161 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
1162 return resolveSignalServiceAddress(resolveRecipient(address));
1163 }
1164
1165 private SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
1166 final var address = account.getRecipientStore().resolveRecipientAddress(recipientId);
1167 if (address.getUuid().isPresent()) {
1168 return address.toSignalServiceAddress();
1169 }
1170
1171 // Address in recipient store doesn't have a uuid, this shouldn't happen
1172 // Try to retrieve the uuid from the server
1173 final var number = address.getNumber().get();
1174 final UUID uuid;
1175 try {
1176 uuid = getRegisteredUser(number);
1177 } catch (IOException e) {
1178 logger.warn("Failed to get uuid for e164 number: {}", number, e);
1179 // Return SignalServiceAddress with unknown UUID
1180 return address.toSignalServiceAddress();
1181 }
1182 return resolveSignalServiceAddress(account.getRecipientStore().resolveRecipient(uuid));
1183 }
1184
1185 private Set<RecipientId> resolveRecipients(Collection<RecipientIdentifier.Single> recipients) throws UnregisteredUserException {
1186 final var recipientIds = new HashSet<RecipientId>(recipients.size());
1187 for (var number : recipients) {
1188 final var recipientId = resolveRecipient(number);
1189 recipientIds.add(recipientId);
1190 }
1191 return recipientIds;
1192 }
1193
1194 private RecipientId resolveRecipient(final RecipientIdentifier.Single recipient) throws UnregisteredUserException {
1195 if (recipient instanceof RecipientIdentifier.Uuid) {
1196 return account.getRecipientStore().resolveRecipient(((RecipientIdentifier.Uuid) recipient).uuid);
1197 } else {
1198 final var number = ((RecipientIdentifier.Number) recipient).number;
1199 return account.getRecipientStore().resolveRecipient(number, () -> {
1200 try {
1201 return getRegisteredUser(number);
1202 } catch (IOException e) {
1203 return null;
1204 }
1205 });
1206 }
1207 }
1208
1209 private RecipientId resolveRecipient(SignalServiceAddress address) {
1210 return account.getRecipientStore().resolveRecipient(address);
1211 }
1212
1213 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
1214 return account.getRecipientStore().resolveRecipientTrusted(address);
1215 }
1216
1217 @Override
1218 public void close() throws IOException {
1219 close(true);
1220 }
1221
1222 private void close(boolean closeAccount) throws IOException {
1223 executor.shutdown();
1224
1225 dependencies.getSignalWebSocket().disconnect();
1226
1227 if (closeAccount && account != null) {
1228 account.close();
1229 }
1230 account = null;
1231 }
1232 }