2 Copyright (C) 2015-2021 AsamK and contributors
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.
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.
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/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.signal
.manager
.actions
.HandleAction
;
20 import org
.asamk
.signal
.manager
.api
.Device
;
21 import org
.asamk
.signal
.manager
.api
.Message
;
22 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
23 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
24 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
25 import org
.asamk
.signal
.manager
.api
.TypingAction
;
26 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
27 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
28 import org
.asamk
.signal
.manager
.groups
.GroupId
;
29 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
30 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
31 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
32 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
33 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
34 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
35 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
36 import org
.asamk
.signal
.manager
.helper
.AttachmentHelper
;
37 import org
.asamk
.signal
.manager
.helper
.ContactHelper
;
38 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
39 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
40 import org
.asamk
.signal
.manager
.helper
.IncomingMessageHandler
;
41 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
42 import org
.asamk
.signal
.manager
.helper
.PreKeyHelper
;
43 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
44 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
45 import org
.asamk
.signal
.manager
.helper
.StorageHelper
;
46 import org
.asamk
.signal
.manager
.helper
.SyncHelper
;
47 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
48 import org
.asamk
.signal
.manager
.jobs
.Context
;
49 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
50 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
51 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
52 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
53 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
56 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
57 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
58 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
59 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
60 import org
.asamk
.signal
.manager
.util
.Utils
;
61 import org
.slf4j
.Logger
;
62 import org
.slf4j
.LoggerFactory
;
63 import org
.whispersystems
.libsignal
.IdentityKey
;
64 import org
.whispersystems
.libsignal
.InvalidKeyException
;
65 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
66 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
67 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintParsingException
;
68 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintVersionMismatchException
;
69 import org
.whispersystems
.libsignal
.util
.Pair
;
70 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
71 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
72 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
73 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
74 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
75 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
76 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
77 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
78 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
79 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
80 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
81 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
82 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
83 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
84 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
85 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
86 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
87 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
88 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
89 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
90 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
93 import java
.io
.IOException
;
95 import java
.net
.URISyntaxException
;
96 import java
.net
.URLEncoder
;
97 import java
.nio
.charset
.StandardCharsets
;
98 import java
.security
.SignatureException
;
99 import java
.util
.Arrays
;
100 import java
.util
.Collection
;
101 import java
.util
.Date
;
102 import java
.util
.HashMap
;
103 import java
.util
.HashSet
;
104 import java
.util
.List
;
105 import java
.util
.Map
;
106 import java
.util
.Set
;
107 import java
.util
.UUID
;
108 import java
.util
.concurrent
.ExecutorService
;
109 import java
.util
.concurrent
.Executors
;
110 import java
.util
.concurrent
.TimeUnit
;
111 import java
.util
.concurrent
.TimeoutException
;
112 import java
.util
.concurrent
.locks
.ReentrantLock
;
113 import java
.util
.function
.Function
;
114 import java
.util
.stream
.Collectors
;
116 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
118 public class ManagerImpl
implements Manager
{
120 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
122 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
123 private final SignalDependencies dependencies
;
125 private SignalAccount account
;
127 private final ExecutorService executor
= Executors
.newCachedThreadPool();
129 private final ProfileHelper profileHelper
;
130 private final PinHelper pinHelper
;
131 private final StorageHelper storageHelper
;
132 private final SendHelper sendHelper
;
133 private final SyncHelper syncHelper
;
134 private final AttachmentHelper attachmentHelper
;
135 private final GroupHelper groupHelper
;
136 private final ContactHelper contactHelper
;
137 private final IncomingMessageHandler incomingMessageHandler
;
138 private final PreKeyHelper preKeyHelper
;
140 private final Context context
;
141 private boolean hasCaughtUpWithOldMessages
= false;
144 SignalAccount account
,
145 PathConfig pathConfig
,
146 ServiceEnvironmentConfig serviceEnvironmentConfig
,
149 this.account
= account
;
150 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
152 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
153 account
.getUsername(),
154 account
.getPassword(),
155 account
.getDeviceId());
156 final var sessionLock
= new SignalSessionLock() {
157 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
160 public Lock
acquire() {
162 return LEGACY_LOCK
::unlock
;
165 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
168 account
.getSignalProtocolStore(),
171 final var avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
172 final var attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
173 final var stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
175 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
176 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
177 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
178 account
.getProfileStore()::getProfileKey
,
179 this::getRecipientProfile
,
180 this::getSenderCertificate
);
181 this.profileHelper
= new ProfileHelper(account
,
184 account
.getProfileStore()::getProfileKey
,
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
,
195 unidentifiedAccessHelper
,
196 this::resolveSignalServiceAddress
,
197 account
.getRecipientStore(),
198 this::handleIdentityFailure
,
200 this::refreshRegisteredUser
);
201 this.groupHelper
= new GroupHelper(account
,
207 this::resolveSignalServiceAddress
,
208 account
.getRecipientStore());
209 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
);
210 this.contactHelper
= new ContactHelper(account
);
211 this.syncHelper
= new SyncHelper(account
,
216 this::resolveSignalServiceAddress
);
217 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
219 this.context
= new Context(account
,
228 var jobExecutor
= new JobExecutor(context
);
230 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
232 account
.getRecipientStore(),
233 this::resolveSignalServiceAddress
,
238 this::getRecipientProfile
,
243 public String
getUsername() {
244 return account
.getUsername();
248 public RecipientId
getSelfRecipientId() {
249 return account
.getSelfRecipientId();
253 public int getDeviceId() {
254 return account
.getDeviceId();
258 public void checkAccountState() throws IOException
{
259 if (account
.getLastReceiveTimestamp() == 0) {
260 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
262 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
263 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
266 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
270 preKeyHelper
.refreshPreKeysIfNecessary();
271 if (account
.getUuid() == null) {
272 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
274 updateAccountAttributes(null);
278 * This is used for checking a set of phone numbers for registration on Signal
280 * @param numbers The set of phone number in question
281 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
282 * @throws IOException if its unable to get the contacts to check if they're registered
285 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
286 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
288 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
289 } catch (InvalidNumberException e
) {
294 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
295 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
297 .filter(s
-> !s
.isEmpty())
298 .collect(Collectors
.toSet()));
300 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
301 final var number
= canonicalizedNumbers
.get(n
);
302 final var uuid
= registeredUsers
.get(number
);
303 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
308 public void updateAccountAttributes(String deviceName
) throws IOException
{
309 final String encryptedDeviceName
;
310 if (deviceName
== null) {
311 encryptedDeviceName
= account
.getEncryptedDeviceName();
313 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
314 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
315 account
.setEncryptedDeviceName(encryptedDeviceName
);
317 dependencies
.getAccountManager()
318 .setAccountAttributes(encryptedDeviceName
,
320 account
.getLocalRegistrationId(),
323 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
324 account
.getSelfUnidentifiedAccessKey(),
325 account
.isUnrestrictedUnidentifiedAccess(),
327 account
.isDiscoverableByPhoneNumber());
331 * @param givenName if null, the previous givenName will be kept
332 * @param familyName if null, the previous familyName will be kept
333 * @param about if null, the previous about text will be kept
334 * @param aboutEmoji if null, the previous about emoji will be kept
335 * @param avatar if avatar is null the image from the local avatar store is used (if present),
338 public void setProfile(
339 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
340 ) throws IOException
{
341 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
342 syncHelper
.sendSyncFetchProfileMessage();
346 public void unregister() throws IOException
{
347 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
348 // If this is the master device, other users can't send messages to this number anymore.
349 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
350 dependencies
.getAccountManager().setGcmId(Optional
.absent());
352 account
.setRegistered(false);
356 public void deleteAccount() throws IOException
{
358 pinHelper
.removeRegistrationLockPin();
359 } catch (UnauthenticatedResponseException e
) {
360 logger
.warn("Failed to remove registration lock pin");
362 account
.setRegistrationLockPin(null, null);
364 dependencies
.getAccountManager().deleteAccount();
366 account
.setRegistered(false);
370 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
371 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
375 public List
<Device
> getLinkedDevices() throws IOException
{
376 var devices
= dependencies
.getAccountManager().getDevices();
377 account
.setMultiDevice(devices
.size() > 1);
378 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
379 return devices
.stream().map(d
-> {
380 String deviceName
= d
.getName();
381 if (deviceName
!= null) {
383 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
384 } catch (IOException e
) {
385 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
388 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
389 }).collect(Collectors
.toList());
393 public void removeLinkedDevices(int deviceId
) throws IOException
{
394 dependencies
.getAccountManager().removeDevice(deviceId
);
395 var devices
= dependencies
.getAccountManager().getDevices();
396 account
.setMultiDevice(devices
.size() > 1);
400 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
401 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
403 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
406 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
407 var identityKeyPair
= account
.getIdentityKeyPair();
408 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
410 dependencies
.getAccountManager()
411 .addDevice(deviceIdentifier
,
414 Optional
.of(account
.getProfileKey().serialize()),
416 account
.setMultiDevice(true);
420 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
421 if (!account
.isMasterDevice()) {
422 throw new RuntimeException("Only master device can set a PIN");
424 if (pin
.isPresent()) {
425 final var masterKey
= account
.getPinMasterKey() != null
426 ? account
.getPinMasterKey()
427 : KeyUtils
.createMasterKey();
429 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
431 account
.setRegistrationLockPin(pin
.get(), masterKey
);
434 pinHelper
.removeRegistrationLockPin();
436 account
.setRegistrationLockPin(null, null);
440 void refreshPreKeys() throws IOException
{
441 preKeyHelper
.refreshPreKeys();
445 public Profile
getRecipientProfile(RecipientId recipientId
) {
446 return profileHelper
.getRecipientProfile(recipientId
);
450 public List
<GroupInfo
> getGroups() {
451 return account
.getGroupStore().getGroups();
455 public SendGroupMessageResults
quitGroup(
456 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
457 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
458 final var newAdmins
= resolveRecipients(groupAdmins
);
459 return groupHelper
.quitGroup(groupId
, newAdmins
);
463 public void deleteGroup(GroupId groupId
) throws IOException
{
464 groupHelper
.deleteGroup(groupId
);
468 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
469 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
470 ) throws IOException
, AttachmentInvalidException
{
471 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
475 public SendGroupMessageResults
updateGroup(
479 Set
<RecipientIdentifier
.Single
> members
,
480 Set
<RecipientIdentifier
.Single
> removeMembers
,
481 Set
<RecipientIdentifier
.Single
> admins
,
482 Set
<RecipientIdentifier
.Single
> removeAdmins
,
483 boolean resetGroupLink
,
484 GroupLinkState groupLinkState
,
485 GroupPermission addMemberPermission
,
486 GroupPermission editDetailsPermission
,
488 Integer expirationTimer
,
489 Boolean isAnnouncementGroup
490 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
491 return groupHelper
.updateGroup(groupId
,
494 members
== null ?
null : resolveRecipients(members
),
495 removeMembers
== null ?
null : resolveRecipients(removeMembers
),
496 admins
== null ?
null : resolveRecipients(admins
),
497 removeAdmins
== null ?
null : resolveRecipients(removeAdmins
),
501 editDetailsPermission
,
504 isAnnouncementGroup
);
508 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
509 GroupInviteLinkUrl inviteLinkUrl
510 ) throws IOException
, GroupLinkNotActiveException
{
511 return groupHelper
.joinGroup(inviteLinkUrl
);
514 private SendMessageResults
sendMessage(
515 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
516 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
517 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
518 long timestamp
= System
.currentTimeMillis();
519 messageBuilder
.withTimestamp(timestamp
);
520 for (final var recipient
: recipients
) {
521 if (recipient
instanceof RecipientIdentifier
.Single
) {
522 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
523 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
524 results
.put(recipient
, List
.of(result
));
525 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
526 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
527 results
.put(recipient
, List
.of(result
));
528 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
529 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
530 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
531 results
.put(recipient
, result
);
534 return new SendMessageResults(timestamp
, results
);
537 private void sendTypingMessage(
538 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
539 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
540 final var timestamp
= System
.currentTimeMillis();
541 for (var recipient
: recipients
) {
542 if (recipient
instanceof RecipientIdentifier
.Single
) {
543 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
544 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
545 sendHelper
.sendTypingMessage(message
, recipientId
);
546 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
547 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
548 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
549 sendHelper
.sendGroupTypingMessage(message
, groupId
);
555 public void sendTypingMessage(
556 TypingAction action
, Set
<RecipientIdentifier
> recipients
557 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
558 sendTypingMessage(action
.toSignalService(), recipients
);
562 public void sendReadReceipt(
563 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
564 ) throws IOException
, UntrustedIdentityException
{
565 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
567 System
.currentTimeMillis());
569 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
573 public void sendViewedReceipt(
574 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
575 ) throws IOException
, UntrustedIdentityException
{
576 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
578 System
.currentTimeMillis());
580 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
584 public SendMessageResults
sendMessage(
585 Message message
, Set
<RecipientIdentifier
> recipients
586 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
587 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
588 applyMessage(messageBuilder
, message
);
589 return sendMessage(messageBuilder
, recipients
);
592 private void applyMessage(
593 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
594 ) throws AttachmentInvalidException
, IOException
{
595 messageBuilder
.withBody(message
.getMessageText());
596 final var attachments
= message
.getAttachments();
597 if (attachments
!= null) {
598 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
603 public SendMessageResults
sendRemoteDeleteMessage(
604 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
605 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
606 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
607 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
608 return sendMessage(messageBuilder
, recipients
);
612 public SendMessageResults
sendMessageReaction(
615 RecipientIdentifier
.Single targetAuthor
,
616 long targetSentTimestamp
,
617 Set
<RecipientIdentifier
> recipients
618 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
619 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
620 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
622 resolveSignalServiceAddress(targetAuthorRecipientId
),
623 targetSentTimestamp
);
624 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
625 return sendMessage(messageBuilder
, recipients
);
629 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
630 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
633 return sendMessage(messageBuilder
,
634 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
635 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
636 throw new AssertionError(e
);
638 for (var recipient
: recipients
) {
639 final var recipientId
= resolveRecipient(recipient
);
640 account
.getSessionStore().deleteAllSessions(recipientId
);
646 public void setContactName(
647 RecipientIdentifier
.Single recipient
, String name
648 ) throws NotMasterDeviceException
, UnregisteredUserException
{
649 if (!account
.isMasterDevice()) {
650 throw new NotMasterDeviceException();
652 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
656 public void setContactBlocked(
657 RecipientIdentifier
.Single recipient
, boolean blocked
658 ) throws NotMasterDeviceException
, IOException
{
659 if (!account
.isMasterDevice()) {
660 throw new NotMasterDeviceException();
662 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
663 // TODO cycle our profile key
664 syncHelper
.sendBlockedList();
668 public void setGroupBlocked(
669 final GroupId groupId
, final boolean blocked
670 ) throws GroupNotFoundException
, IOException
{
671 groupHelper
.setGroupBlocked(groupId
, blocked
);
672 // TODO cycle our profile key
673 syncHelper
.sendBlockedList();
677 * Change the expiration timer for a contact
680 public void setExpirationTimer(
681 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
682 ) throws IOException
{
683 var recipientId
= resolveRecipient(recipient
);
684 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
685 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
687 sendMessage(messageBuilder
, Set
.of(recipient
));
688 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
689 throw new AssertionError(e
);
694 * Upload the sticker pack from path.
696 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
697 * @return if successful, returns the URL to install the sticker pack in the signal app
700 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
701 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
703 var messageSender
= dependencies
.getMessageSender();
705 var packKey
= KeyUtils
.createStickerUploadKey();
706 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
707 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
709 var sticker
= new Sticker(packId
, packKey
);
710 account
.getStickerStore().updateSticker(sticker
);
713 return new URI("https",
717 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
719 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
720 } catch (URISyntaxException e
) {
721 throw new AssertionError(e
);
726 public void requestAllSyncData() throws IOException
{
727 syncHelper
.requestAllSyncData();
728 retrieveRemoteStorage();
731 void retrieveRemoteStorage() throws IOException
{
732 if (account
.getStorageKey() != null) {
733 storageHelper
.readDataFromStorage();
737 private byte[] getSenderCertificate() {
740 if (account
.isPhoneNumberShared()) {
741 certificate
= dependencies
.getAccountManager().getSenderCertificate();
743 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
745 } catch (IOException e
) {
746 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
749 // TODO cache for a day
753 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
754 final var address
= resolveSignalServiceAddress(recipientId
);
755 if (!address
.getNumber().isPresent()) {
758 final var number
= address
.getNumber().get();
759 final var uuid
= getRegisteredUser(number
);
760 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
763 private UUID
getRegisteredUser(final String number
) throws IOException
{
764 final Map
<String
, UUID
> uuidMap
;
766 uuidMap
= getRegisteredUsers(Set
.of(number
));
767 } catch (NumberFormatException e
) {
768 throw new UnregisteredUserException(number
, e
);
770 final var uuid
= uuidMap
.get(number
);
772 throw new UnregisteredUserException(number
, null);
777 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
778 final Map
<String
, UUID
> registeredUsers
;
780 registeredUsers
= dependencies
.getAccountManager()
781 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
783 serviceEnvironmentConfig
.getCdsMrenclave());
784 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
785 throw new IOException(e
);
788 // Store numbers as recipients so we have the number/uuid association
789 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
791 return registeredUsers
;
794 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
795 Set
<HandleAction
> queuedActions
= new HashSet
<>();
796 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
797 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
798 if (actions
!= null) {
799 queuedActions
.addAll(actions
);
802 handleQueuedActions(queuedActions
);
805 private List
<HandleAction
> retryFailedReceivedMessage(
806 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
808 var envelope
= cachedMessage
.loadEnvelope();
809 if (envelope
== null) {
810 cachedMessage
.delete();
814 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
815 final var actions
= result
.first();
816 final var exception
= result
.second();
818 if (exception
instanceof UntrustedIdentityException
) {
819 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
820 // Envelope is more than a month old, cleaning up.
821 cachedMessage
.delete();
824 if (!envelope
.hasSourceUuid()) {
825 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
826 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
828 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
829 } catch (IOException ioException
) {
830 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
836 // If successful and for all other errors that are not recoverable, delete the cached message
837 cachedMessage
.delete();
842 public void receiveMessages(
845 boolean returnOnTimeout
,
846 boolean ignoreAttachments
,
847 ReceiveMessageHandler handler
848 ) throws IOException
{
849 retryFailedReceivedMessages(handler
, ignoreAttachments
);
851 Set
<HandleAction
> queuedActions
= new HashSet
<>();
853 final var signalWebSocket
= dependencies
.getSignalWebSocket();
854 signalWebSocket
.connect();
856 hasCaughtUpWithOldMessages
= false;
858 while (!Thread
.interrupted()) {
859 SignalServiceEnvelope envelope
;
860 final CachedMessage
[] cachedMessage
= {null};
861 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
862 logger
.debug("Checking for new message from server");
864 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
865 final var recipientId
= envelope1
.hasSourceUuid()
866 ?
resolveRecipient(envelope1
.getSourceAddress())
868 // store message on disk, before acknowledging receipt to the server
869 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
871 if (result
.isPresent()) {
872 envelope
= result
.get();
873 logger
.debug("New message received from server");
875 logger
.debug("Received indicator that server queue is empty");
876 handleQueuedActions(queuedActions
);
877 queuedActions
.clear();
879 hasCaughtUpWithOldMessages
= true;
880 synchronized (this) {
884 // Continue to wait another timeout for new messages
887 } catch (AssertionError e
) {
888 if (e
.getCause() instanceof InterruptedException
) {
889 Thread
.currentThread().interrupt();
894 } catch (WebSocketUnavailableException e
) {
895 logger
.debug("Pipe unexpectedly unavailable, connecting");
896 signalWebSocket
.connect();
898 } catch (TimeoutException e
) {
899 if (returnOnTimeout
) return;
903 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
904 queuedActions
.addAll(result
.first());
905 final var exception
= result
.second();
907 if (hasCaughtUpWithOldMessages
) {
908 handleQueuedActions(queuedActions
);
910 if (cachedMessage
[0] != null) {
911 if (exception
instanceof UntrustedIdentityException
) {
912 final var address
= ((UntrustedIdentityException
) exception
).getSender();
913 final var recipientId
= resolveRecipient(address
);
914 if (!envelope
.hasSourceUuid()) {
916 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
917 } catch (IOException ioException
) {
918 logger
.warn("Failed to move cached message to recipient folder: {}",
919 ioException
.getMessage());
923 cachedMessage
[0].delete();
927 handleQueuedActions(queuedActions
);
931 public boolean hasCaughtUpWithOldMessages() {
932 return hasCaughtUpWithOldMessages
;
935 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
936 var interrupted
= false;
937 for (var action
: queuedActions
) {
939 action
.execute(context
);
940 } catch (Throwable e
) {
941 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
942 && e
.getCause() instanceof InterruptedException
) {
946 logger
.warn("Message action failed.", e
);
950 Thread
.currentThread().interrupt();
955 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
956 final RecipientId recipientId
;
958 recipientId
= resolveRecipient(recipient
);
959 } catch (UnregisteredUserException e
) {
962 return contactHelper
.isContactBlocked(recipientId
);
966 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
967 return attachmentHelper
.getAttachmentFile(attachmentId
);
971 public void sendContacts() throws IOException
{
972 syncHelper
.sendContacts();
976 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
977 return account
.getContactStore().getContacts();
981 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
982 final RecipientId recipientId
;
984 recipientId
= resolveRecipient(recipientIdentifier
);
985 } catch (UnregisteredUserException e
) {
989 final var contact
= account
.getContactStore().getContact(recipientId
);
990 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
991 return contact
.getName();
994 final var profile
= getRecipientProfile(recipientId
);
995 if (profile
!= null) {
996 return profile
.getDisplayName();
1003 public GroupInfo
getGroup(GroupId groupId
) {
1004 return groupHelper
.getGroup(groupId
);
1008 public List
<IdentityInfo
> getIdentities() {
1009 return account
.getIdentityKeyStore().getIdentities();
1013 public List
<IdentityInfo
> getIdentities(RecipientIdentifier
.Single recipient
) {
1014 IdentityInfo identity
;
1016 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1017 } catch (UnregisteredUserException e
) {
1020 return identity
== null ? List
.of() : List
.of(identity
);
1024 * Trust this the identity with this fingerprint
1026 * @param recipient username of the identity
1027 * @param fingerprint Fingerprint
1030 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1031 RecipientId recipientId
;
1033 recipientId
= resolveRecipient(recipient
);
1034 } catch (UnregisteredUserException e
) {
1037 return trustIdentity(recipientId
,
1038 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1039 TrustLevel
.TRUSTED_VERIFIED
);
1043 * Trust this the identity with this safety number
1045 * @param recipient username of the identity
1046 * @param safetyNumber Safety number
1049 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1050 RecipientId recipientId
;
1052 recipientId
= resolveRecipient(recipient
);
1053 } catch (UnregisteredUserException e
) {
1056 var address
= resolveSignalServiceAddress(recipientId
);
1057 return trustIdentity(recipientId
,
1058 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1059 TrustLevel
.TRUSTED_VERIFIED
);
1063 * Trust this the identity with this scannable safety number
1065 * @param recipient username of the identity
1066 * @param safetyNumber Scannable safety number
1069 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1070 RecipientId recipientId
;
1072 recipientId
= resolveRecipient(recipient
);
1073 } catch (UnregisteredUserException e
) {
1076 var address
= resolveSignalServiceAddress(recipientId
);
1077 return trustIdentity(recipientId
, identityKey
-> {
1078 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1080 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1081 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1084 }, TrustLevel
.TRUSTED_VERIFIED
);
1088 * Trust all keys of this identity without verification
1090 * @param recipient username of the identity
1093 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1094 RecipientId recipientId
;
1096 recipientId
= resolveRecipient(recipient
);
1097 } catch (UnregisteredUserException e
) {
1100 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1103 private boolean trustIdentity(
1104 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1106 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1107 if (identity
== null) {
1111 if (!verifier
.apply(identity
.getIdentityKey())) {
1115 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1117 var address
= resolveSignalServiceAddress(recipientId
);
1118 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1119 } catch (IOException e
) {
1120 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1126 private void handleIdentityFailure(
1127 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1129 final var identityKey
= identityFailure
.getIdentityKey();
1130 if (identityKey
!= null) {
1131 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1133 account
.getSessionStore().archiveSessions(recipientId
);
1136 // Retrieve profile to get the current identity key from the server
1137 profileHelper
.refreshRecipientProfile(recipientId
);
1142 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1143 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1144 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1148 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1149 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1150 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1153 private Fingerprint
computeSafetyNumberFingerprint(
1154 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1156 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1157 account
.getSelfAddress(),
1158 account
.getIdentityKeyPair().getPublicKey(),
1164 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1165 return resolveSignalServiceAddress(resolveRecipient(address
));
1169 public SignalServiceAddress
resolveSignalServiceAddress(UUID uuid
) {
1170 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1174 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1175 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1176 if (address
.getUuid().isPresent()) {
1177 return address
.toSignalServiceAddress();
1180 // Address in recipient store doesn't have a uuid, this shouldn't happen
1181 // Try to retrieve the uuid from the server
1182 final var number
= address
.getNumber().get();
1184 return resolveSignalServiceAddress(getRegisteredUser(number
));
1185 } catch (IOException e
) {
1186 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1187 // Return SignalServiceAddress with unknown UUID
1188 return address
.toSignalServiceAddress();
1192 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1193 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1194 for (var number
: recipients
) {
1195 final var recipientId
= resolveRecipient(number
);
1196 recipientIds
.add(recipientId
);
1198 return recipientIds
;
1201 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1202 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1203 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1205 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1206 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1208 return getRegisteredUser(number
);
1209 } catch (IOException e
) {
1216 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1217 return account
.getRecipientStore().resolveRecipient(address
);
1220 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1221 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1225 public void close() throws IOException
{
1229 private void close(boolean closeAccount
) throws IOException
{
1230 executor
.shutdown();
1232 dependencies
.getSignalWebSocket().disconnect();
1234 if (closeAccount
&& account
!= null) {