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