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
.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
;
91 import java
.io
.IOException
;
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
;
111 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
113 public class ManagerImpl
implements Manager
{
115 private final static Logger logger
= LoggerFactory
.getLogger(ManagerImpl
.class);
117 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
118 private final SignalDependencies dependencies
;
120 private SignalAccount account
;
122 private final ExecutorService executor
= Executors
.newCachedThreadPool();
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
;
136 private final Context context
;
137 private boolean hasCaughtUpWithOldMessages
= false;
140 SignalAccount account
,
141 PathConfig pathConfig
,
142 ServiceEnvironmentConfig serviceEnvironmentConfig
,
145 this.account
= account
;
146 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
148 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
149 account
.getUsername(),
150 account
.getPassword(),
151 account
.getDeviceId());
152 final var sessionLock
= new SignalSessionLock() {
153 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
156 public Lock
acquire() {
158 return LEGACY_LOCK
::unlock
;
161 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
164 account
.getSignalProtocolStore(),
167 final var avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
168 final var attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
169 final var stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
171 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
172 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
173 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
,
175 account
::getProfileKey
,
176 this::getRecipientProfile
);
177 this.profileHelper
= new ProfileHelper(account
,
180 unidentifiedAccessHelper
::getAccessFor
,
181 this::resolveSignalServiceAddress
);
182 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
183 this::getRecipientProfile
,
184 account
::getSelfRecipientId
,
185 dependencies
.getGroupsV2Operations(),
186 dependencies
.getGroupsV2Api(),
187 this::resolveSignalServiceAddress
);
188 this.sendHelper
= new SendHelper(account
,
190 unidentifiedAccessHelper
,
191 this::resolveSignalServiceAddress
,
192 account
.getRecipientStore(),
193 this::handleIdentityFailure
,
195 this::refreshRegisteredUser
);
196 this.groupHelper
= new GroupHelper(account
,
202 this::resolveSignalServiceAddress
,
203 account
.getRecipientStore());
204 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
, profileHelper
);
205 this.contactHelper
= new ContactHelper(account
);
206 this.syncHelper
= new SyncHelper(account
,
211 this::resolveSignalServiceAddress
);
212 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
214 this.context
= new Context(account
,
223 var jobExecutor
= new JobExecutor(context
);
225 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
227 account
.getRecipientStore(),
228 this::resolveSignalServiceAddress
,
233 this::getRecipientProfile
,
235 this.identityHelper
= new IdentityHelper(account
,
237 this::resolveSignalServiceAddress
,
243 public String
getSelfNumber() {
244 return account
.getUsername();
248 public void checkAccountState() throws IOException
{
249 if (account
.getLastReceiveTimestamp() == 0) {
250 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
252 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
253 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
256 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
260 preKeyHelper
.refreshPreKeysIfNecessary();
261 if (account
.getUuid() == null) {
262 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
264 updateAccountAttributes(null);
268 * This is used for checking a set of phone numbers for registration on Signal
270 * @param numbers The set of phone number in question
271 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
272 * @throws IOException if its unable to get the contacts to check if they're registered
275 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
276 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
278 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
279 } catch (InvalidNumberException e
) {
284 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
285 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
287 .filter(s
-> !s
.isEmpty())
288 .collect(Collectors
.toSet()));
290 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
291 final var number
= canonicalizedNumbers
.get(n
);
292 final var uuid
= registeredUsers
.get(number
);
293 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
298 public void updateAccountAttributes(String deviceName
) throws IOException
{
299 final String encryptedDeviceName
;
300 if (deviceName
== null) {
301 encryptedDeviceName
= account
.getEncryptedDeviceName();
303 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
304 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
305 account
.setEncryptedDeviceName(encryptedDeviceName
);
307 dependencies
.getAccountManager()
308 .setAccountAttributes(encryptedDeviceName
,
310 account
.getLocalRegistrationId(),
313 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
314 account
.getSelfUnidentifiedAccessKey(),
315 account
.isUnrestrictedUnidentifiedAccess(),
317 account
.isDiscoverableByPhoneNumber());
321 public void updateConfiguration(
322 final Boolean readReceipts
,
323 final Boolean unidentifiedDeliveryIndicators
,
324 final Boolean typingIndicators
,
325 final Boolean linkPreviews
326 ) throws IOException
, NotMasterDeviceException
{
327 if (!account
.isMasterDevice()) {
328 throw new NotMasterDeviceException();
331 final var configurationStore
= account
.getConfigurationStore();
332 if (readReceipts
!= null) {
333 configurationStore
.setReadReceipts(readReceipts
);
335 if (unidentifiedDeliveryIndicators
!= null) {
336 configurationStore
.setUnidentifiedDeliveryIndicators(unidentifiedDeliveryIndicators
);
338 if (typingIndicators
!= null) {
339 configurationStore
.setTypingIndicators(typingIndicators
);
341 if (linkPreviews
!= null) {
342 configurationStore
.setLinkPreviews(linkPreviews
);
344 syncHelper
.sendConfigurationMessage();
348 public List
<Boolean
> getConfiguration() throws IOException
, NotMasterDeviceException
{
349 if (!account
.isMasterDevice()) {
350 throw new NotMasterDeviceException();
352 final var configurationStore
= account
.getConfigurationStore();
353 final Boolean readReceipts
= configurationStore
.getReadReceipts();
354 final Boolean unidentifiedDeliveryIndicators
= configurationStore
.getUnidentifiedDeliveryIndicators();
355 final Boolean typingIndicators
= configurationStore
.getTypingIndicators();
356 final Boolean linkPreviews
= configurationStore
.getLinkPreviews();
357 return List
.of(readReceipts
, unidentifiedDeliveryIndicators
, typingIndicators
, linkPreviews
);
361 * @param givenName if null, the previous givenName will be kept
362 * @param familyName if null, the previous familyName will be kept
363 * @param about if null, the previous about text will be kept
364 * @param aboutEmoji if null, the previous about emoji will be kept
365 * @param avatar if avatar is null the image from the local avatar store is used (if present),
368 public void setProfile(
369 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
370 ) throws IOException
{
371 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
372 syncHelper
.sendSyncFetchProfileMessage();
376 public void unregister() throws IOException
{
377 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
378 // If this is the master device, other users can't send messages to this number anymore.
379 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
380 dependencies
.getAccountManager().setGcmId(Optional
.absent());
382 account
.setRegistered(false);
386 public void deleteAccount() throws IOException
{
388 pinHelper
.removeRegistrationLockPin();
389 } catch (UnauthenticatedResponseException e
) {
390 logger
.warn("Failed to remove registration lock pin");
392 account
.setRegistrationLockPin(null, null);
394 dependencies
.getAccountManager().deleteAccount();
396 account
.setRegistered(false);
400 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
401 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
405 public List
<Device
> getLinkedDevices() throws IOException
{
406 var devices
= dependencies
.getAccountManager().getDevices();
407 account
.setMultiDevice(devices
.size() > 1);
408 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
409 return devices
.stream().map(d
-> {
410 String deviceName
= d
.getName();
411 if (deviceName
!= null) {
413 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
414 } catch (IOException e
) {
415 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
418 return new Device(d
.getId(),
422 d
.getId() == account
.getDeviceId());
423 }).collect(Collectors
.toList());
427 public void removeLinkedDevices(long deviceId
) throws IOException
{
428 dependencies
.getAccountManager().removeDevice(deviceId
);
429 var devices
= dependencies
.getAccountManager().getDevices();
430 account
.setMultiDevice(devices
.size() > 1);
434 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
435 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
437 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
440 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
441 var identityKeyPair
= account
.getIdentityKeyPair();
442 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
444 dependencies
.getAccountManager()
445 .addDevice(deviceIdentifier
,
448 Optional
.of(account
.getProfileKey().serialize()),
450 account
.setMultiDevice(true);
454 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
455 if (!account
.isMasterDevice()) {
456 throw new RuntimeException("Only master device can set a PIN");
458 if (pin
.isPresent()) {
459 final var masterKey
= account
.getPinMasterKey() != null
460 ? account
.getPinMasterKey()
461 : KeyUtils
.createMasterKey();
463 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
465 account
.setRegistrationLockPin(pin
.get(), masterKey
);
468 pinHelper
.removeRegistrationLockPin();
470 account
.setRegistrationLockPin(null, null);
474 void refreshPreKeys() throws IOException
{
475 preKeyHelper
.refreshPreKeys();
479 public Profile
getRecipientProfile(RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
480 return profileHelper
.getRecipientProfile(resolveRecipient(recipient
));
483 private Profile
getRecipientProfile(RecipientId recipientId
) {
484 return profileHelper
.getRecipientProfile(recipientId
);
488 public List
<Group
> getGroups() {
489 return account
.getGroupStore().getGroups().stream().map(this::toGroup
).collect(Collectors
.toList());
492 private Group
toGroup(final GroupInfo groupInfo
) {
493 if (groupInfo
== null) {
497 return new Group(groupInfo
.getGroupId(),
498 groupInfo
.getTitle(),
499 groupInfo
.getDescription(),
500 groupInfo
.getGroupInviteLink(),
501 groupInfo
.getMembers()
503 .map(account
.getRecipientStore()::resolveRecipientAddress
)
504 .collect(Collectors
.toSet()),
505 groupInfo
.getPendingMembers()
507 .map(account
.getRecipientStore()::resolveRecipientAddress
)
508 .collect(Collectors
.toSet()),
509 groupInfo
.getRequestingMembers()
511 .map(account
.getRecipientStore()::resolveRecipientAddress
)
512 .collect(Collectors
.toSet()),
513 groupInfo
.getAdminMembers()
515 .map(account
.getRecipientStore()::resolveRecipientAddress
)
516 .collect(Collectors
.toSet()),
517 groupInfo
.isBlocked(),
518 groupInfo
.getMessageExpirationTimer(),
519 groupInfo
.getPermissionAddMember(),
520 groupInfo
.getPermissionEditDetails(),
521 groupInfo
.getPermissionSendMessage(),
522 groupInfo
.isMember(account
.getSelfRecipientId()),
523 groupInfo
.isAdmin(account
.getSelfRecipientId()));
527 public SendGroupMessageResults
quitGroup(
528 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
529 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
530 final var newAdmins
= resolveRecipients(groupAdmins
);
531 return groupHelper
.quitGroup(groupId
, newAdmins
);
535 public void deleteGroup(GroupId groupId
) throws IOException
{
536 groupHelper
.deleteGroup(groupId
);
540 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
541 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
542 ) throws IOException
, AttachmentInvalidException
{
543 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
547 public SendGroupMessageResults
updateGroup(
548 final GroupId groupId
, final UpdateGroup updateGroup
549 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
550 return groupHelper
.updateGroup(groupId
,
551 updateGroup
.getName(),
552 updateGroup
.getDescription(),
553 updateGroup
.getMembers() == null ?
null : resolveRecipients(updateGroup
.getMembers()),
554 updateGroup
.getRemoveMembers() == null ?
null : resolveRecipients(updateGroup
.getRemoveMembers()),
555 updateGroup
.getAdmins() == null ?
null : resolveRecipients(updateGroup
.getAdmins()),
556 updateGroup
.getRemoveAdmins() == null ?
null : resolveRecipients(updateGroup
.getRemoveAdmins()),
557 updateGroup
.isResetGroupLink(),
558 updateGroup
.getGroupLinkState(),
559 updateGroup
.getAddMemberPermission(),
560 updateGroup
.getEditDetailsPermission(),
561 updateGroup
.getAvatarFile(),
562 updateGroup
.getExpirationTimer(),
563 updateGroup
.getIsAnnouncementGroup());
567 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
568 GroupInviteLinkUrl inviteLinkUrl
569 ) throws IOException
, GroupLinkNotActiveException
{
570 return groupHelper
.joinGroup(inviteLinkUrl
);
573 private SendMessageResults
sendMessage(
574 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
575 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
576 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
577 long timestamp
= System
.currentTimeMillis();
578 messageBuilder
.withTimestamp(timestamp
);
579 for (final var recipient
: recipients
) {
580 if (recipient
instanceof RecipientIdentifier
.Single
) {
581 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
582 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
583 results
.put(recipient
, List
.of(result
));
584 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
585 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
586 results
.put(recipient
, List
.of(result
));
587 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
588 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
589 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
590 results
.put(recipient
, result
);
593 return new SendMessageResults(timestamp
, results
);
596 private void sendTypingMessage(
597 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
598 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
599 final var timestamp
= System
.currentTimeMillis();
600 for (var recipient
: recipients
) {
601 if (recipient
instanceof RecipientIdentifier
.Single
) {
602 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
603 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
604 sendHelper
.sendTypingMessage(message
, recipientId
);
605 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
606 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
607 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
608 sendHelper
.sendGroupTypingMessage(message
, groupId
);
614 public void sendTypingMessage(
615 TypingAction action
, Set
<RecipientIdentifier
> recipients
616 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
617 sendTypingMessage(action
.toSignalService(), recipients
);
621 public void sendReadReceipt(
622 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
623 ) throws IOException
, UntrustedIdentityException
{
624 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
626 System
.currentTimeMillis());
628 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
632 public void sendViewedReceipt(
633 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
634 ) throws IOException
, UntrustedIdentityException
{
635 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
637 System
.currentTimeMillis());
639 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
643 public SendMessageResults
sendMessage(
644 Message message
, Set
<RecipientIdentifier
> recipients
645 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
646 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
647 applyMessage(messageBuilder
, message
);
648 return sendMessage(messageBuilder
, recipients
);
651 private void applyMessage(
652 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
653 ) throws AttachmentInvalidException
, IOException
{
654 messageBuilder
.withBody(message
.getMessageText());
655 final var attachments
= message
.getAttachments();
656 if (attachments
!= null) {
657 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
662 public SendMessageResults
sendRemoteDeleteMessage(
663 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
664 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
665 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
666 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
667 return sendMessage(messageBuilder
, recipients
);
671 public SendMessageResults
sendMessageReaction(
674 RecipientIdentifier
.Single targetAuthor
,
675 long targetSentTimestamp
,
676 Set
<RecipientIdentifier
> recipients
677 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
678 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
679 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
681 resolveSignalServiceAddress(targetAuthorRecipientId
),
682 targetSentTimestamp
);
683 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
684 return sendMessage(messageBuilder
, recipients
);
688 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
689 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
692 return sendMessage(messageBuilder
,
693 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
694 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
695 throw new AssertionError(e
);
697 for (var recipient
: recipients
) {
698 final var recipientId
= resolveRecipient(recipient
);
699 account
.getSessionStore().deleteAllSessions(recipientId
);
705 public void setContactName(
706 RecipientIdentifier
.Single recipient
, String name
707 ) throws NotMasterDeviceException
, UnregisteredUserException
{
708 if (!account
.isMasterDevice()) {
709 throw new NotMasterDeviceException();
711 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
715 public void setContactBlocked(
716 RecipientIdentifier
.Single recipient
, boolean blocked
717 ) throws NotMasterDeviceException
, IOException
{
718 if (!account
.isMasterDevice()) {
719 throw new NotMasterDeviceException();
721 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
722 // TODO cycle our profile key
723 syncHelper
.sendBlockedList();
727 public void setGroupBlocked(
728 final GroupId groupId
, final boolean blocked
729 ) throws GroupNotFoundException
, IOException
, NotMasterDeviceException
{
730 if (!account
.isMasterDevice()) {
731 throw new NotMasterDeviceException();
733 groupHelper
.setGroupBlocked(groupId
, blocked
);
734 // TODO cycle our profile key
735 syncHelper
.sendBlockedList();
739 * Change the expiration timer for a contact
742 public void setExpirationTimer(
743 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
744 ) throws IOException
{
745 var recipientId
= resolveRecipient(recipient
);
746 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
747 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
749 sendMessage(messageBuilder
, Set
.of(recipient
));
750 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
751 throw new AssertionError(e
);
756 * Upload the sticker pack from path.
758 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
759 * @return if successful, returns the URL to install the sticker pack in the signal app
762 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
763 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
765 var messageSender
= dependencies
.getMessageSender();
767 var packKey
= KeyUtils
.createStickerUploadKey();
768 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
769 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
771 var sticker
= new Sticker(packId
, packKey
);
772 account
.getStickerStore().updateSticker(sticker
);
775 return new URI("https",
779 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
781 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
782 } catch (URISyntaxException e
) {
783 throw new AssertionError(e
);
788 public void requestAllSyncData() throws IOException
{
789 syncHelper
.requestAllSyncData();
790 retrieveRemoteStorage();
793 void retrieveRemoteStorage() throws IOException
{
794 if (account
.getStorageKey() != null) {
795 storageHelper
.readDataFromStorage();
799 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
800 final var address
= resolveSignalServiceAddress(recipientId
);
801 if (!address
.getNumber().isPresent()) {
804 final var number
= address
.getNumber().get();
805 final var uuid
= getRegisteredUser(number
);
806 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
809 private UUID
getRegisteredUser(final String number
) throws IOException
{
810 final Map
<String
, UUID
> uuidMap
;
812 uuidMap
= getRegisteredUsers(Set
.of(number
));
813 } catch (NumberFormatException e
) {
814 throw new UnregisteredUserException(number
, e
);
816 final var uuid
= uuidMap
.get(number
);
818 throw new UnregisteredUserException(number
, null);
823 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
824 final Map
<String
, UUID
> registeredUsers
;
826 registeredUsers
= dependencies
.getAccountManager()
827 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
829 serviceEnvironmentConfig
.getCdsMrenclave());
830 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
831 throw new IOException(e
);
834 // Store numbers as recipients so we have the number/uuid association
835 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
837 return registeredUsers
;
840 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
841 Set
<HandleAction
> queuedActions
= new HashSet
<>();
842 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
843 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
844 if (actions
!= null) {
845 queuedActions
.addAll(actions
);
848 handleQueuedActions(queuedActions
);
851 private List
<HandleAction
> retryFailedReceivedMessage(
852 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
854 var envelope
= cachedMessage
.loadEnvelope();
855 if (envelope
== null) {
856 cachedMessage
.delete();
860 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
861 final var actions
= result
.first();
862 final var exception
= result
.second();
864 if (exception
instanceof UntrustedIdentityException
) {
865 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
866 // Envelope is more than a month old, cleaning up.
867 cachedMessage
.delete();
870 if (!envelope
.hasSourceUuid()) {
871 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
872 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
874 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
875 } catch (IOException ioException
) {
876 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
882 // If successful and for all other errors that are not recoverable, delete the cached message
883 cachedMessage
.delete();
888 public void receiveMessages(
891 boolean returnOnTimeout
,
892 boolean ignoreAttachments
,
893 ReceiveMessageHandler handler
894 ) throws IOException
{
895 retryFailedReceivedMessages(handler
, ignoreAttachments
);
897 Set
<HandleAction
> queuedActions
= new HashSet
<>();
899 final var signalWebSocket
= dependencies
.getSignalWebSocket();
900 signalWebSocket
.connect();
902 hasCaughtUpWithOldMessages
= false;
904 while (!Thread
.interrupted()) {
905 SignalServiceEnvelope envelope
;
906 final CachedMessage
[] cachedMessage
= {null};
907 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
908 logger
.debug("Checking for new message from server");
910 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
911 final var recipientId
= envelope1
.hasSourceUuid()
912 ?
resolveRecipient(envelope1
.getSourceAddress())
914 // store message on disk, before acknowledging receipt to the server
915 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
917 if (result
.isPresent()) {
918 envelope
= result
.get();
919 logger
.debug("New message received from server");
921 logger
.debug("Received indicator that server queue is empty");
922 handleQueuedActions(queuedActions
);
923 queuedActions
.clear();
925 hasCaughtUpWithOldMessages
= true;
926 synchronized (this) {
930 // Continue to wait another timeout for new messages
933 } catch (AssertionError e
) {
934 if (e
.getCause() instanceof InterruptedException
) {
935 Thread
.currentThread().interrupt();
940 } catch (WebSocketUnavailableException e
) {
941 logger
.debug("Pipe unexpectedly unavailable, connecting");
942 signalWebSocket
.connect();
944 } catch (TimeoutException e
) {
945 if (returnOnTimeout
) return;
949 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
950 queuedActions
.addAll(result
.first());
951 final var exception
= result
.second();
953 if (hasCaughtUpWithOldMessages
) {
954 handleQueuedActions(queuedActions
);
956 if (cachedMessage
[0] != null) {
957 if (exception
instanceof UntrustedIdentityException
) {
958 final var address
= ((UntrustedIdentityException
) exception
).getSender();
959 final var recipientId
= resolveRecipient(address
);
960 if (!envelope
.hasSourceUuid()) {
962 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
963 } catch (IOException ioException
) {
964 logger
.warn("Failed to move cached message to recipient folder: {}",
965 ioException
.getMessage());
969 cachedMessage
[0].delete();
973 handleQueuedActions(queuedActions
);
977 public boolean hasCaughtUpWithOldMessages() {
978 return hasCaughtUpWithOldMessages
;
981 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
982 var interrupted
= false;
983 for (var action
: queuedActions
) {
985 action
.execute(context
);
986 } catch (Throwable e
) {
987 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
988 && e
.getCause() instanceof InterruptedException
) {
992 logger
.warn("Message action failed.", e
);
996 Thread
.currentThread().interrupt();
1001 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
1002 final RecipientId recipientId
;
1004 recipientId
= resolveRecipient(recipient
);
1005 } catch (UnregisteredUserException e
) {
1008 return contactHelper
.isContactBlocked(recipientId
);
1012 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
1013 return attachmentHelper
.getAttachmentFile(attachmentId
);
1017 public void sendContacts() throws IOException
{
1018 syncHelper
.sendContacts();
1022 public List
<Pair
<RecipientAddress
, Contact
>> getContacts() {
1023 return account
.getContactStore()
1026 .map(p
-> new Pair
<>(account
.getRecipientStore().resolveRecipientAddress(p
.first()), p
.second()))
1027 .collect(Collectors
.toList());
1031 public String
getContactOrProfileName(RecipientIdentifier
.Single recipient
) {
1032 final RecipientId recipientId
;
1034 recipientId
= resolveRecipient(recipient
);
1035 } catch (UnregisteredUserException e
) {
1039 final var contact
= account
.getContactStore().getContact(recipientId
);
1040 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1041 return contact
.getName();
1044 final var profile
= getRecipientProfile(recipientId
);
1045 if (profile
!= null) {
1046 return profile
.getDisplayName();
1053 public Group
getGroup(GroupId groupId
) {
1054 return toGroup(groupHelper
.getGroup(groupId
));
1057 private GroupInfo
getGroupInfo(GroupId groupId
) {
1058 return groupHelper
.getGroup(groupId
);
1062 public List
<Identity
> getIdentities() {
1063 return account
.getIdentityKeyStore()
1066 .map(this::toIdentity
)
1067 .collect(Collectors
.toList());
1070 private Identity
toIdentity(final IdentityInfo identityInfo
) {
1071 if (identityInfo
== null) {
1075 final var address
= account
.getRecipientStore().resolveRecipientAddress(identityInfo
.getRecipientId());
1076 return new Identity(address
,
1077 identityInfo
.getIdentityKey(),
1078 identityHelper
.computeSafetyNumber(identityInfo
.getRecipientId(), identityInfo
.getIdentityKey()),
1079 identityHelper
.computeSafetyNumberForScanning(identityInfo
.getRecipientId(),
1080 identityInfo
.getIdentityKey()).getSerialized(),
1081 identityInfo
.getTrustLevel(),
1082 identityInfo
.getDateAdded());
1086 public List
<Identity
> getIdentities(RecipientIdentifier
.Single recipient
) {
1087 IdentityInfo identity
;
1089 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1090 } catch (UnregisteredUserException e
) {
1093 return identity
== null ? List
.of() : List
.of(toIdentity(identity
));
1097 * Trust this the identity with this fingerprint
1099 * @param recipient username of the identity
1100 * @param fingerprint Fingerprint
1103 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1104 RecipientId recipientId
;
1106 recipientId
= resolveRecipient(recipient
);
1107 } catch (UnregisteredUserException e
) {
1110 return identityHelper
.trustIdentityVerified(recipientId
, fingerprint
);
1114 * Trust this the identity with this safety number
1116 * @param recipient username of the identity
1117 * @param safetyNumber Safety number
1120 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1121 RecipientId recipientId
;
1123 recipientId
= resolveRecipient(recipient
);
1124 } catch (UnregisteredUserException e
) {
1127 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1131 * Trust this the identity with this scannable safety number
1133 * @param recipient username of the identity
1134 * @param safetyNumber Scannable safety number
1137 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1138 RecipientId recipientId
;
1140 recipientId
= resolveRecipient(recipient
);
1141 } catch (UnregisteredUserException e
) {
1144 return identityHelper
.trustIdentityVerifiedSafetyNumber(recipientId
, safetyNumber
);
1148 * Trust all keys of this identity without verification
1150 * @param recipient username of the identity
1153 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1154 RecipientId recipientId
;
1156 recipientId
= resolveRecipient(recipient
);
1157 } catch (UnregisteredUserException e
) {
1160 return identityHelper
.trustIdentityAllKeys(recipientId
);
1163 private void handleIdentityFailure(
1164 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1166 this.identityHelper
.handleIdentityFailure(recipientId
, identityFailure
);
1170 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1171 return resolveSignalServiceAddress(resolveRecipient(address
));
1174 private 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();
1185 uuid
= getRegisteredUser(number
);
1186 } catch (IOException e
) {
1187 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1188 // Return SignalServiceAddress with unknown UUID
1189 return address
.toSignalServiceAddress();
1191 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1194 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1195 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1196 for (var number
: recipients
) {
1197 final var recipientId
= resolveRecipient(number
);
1198 recipientIds
.add(recipientId
);
1200 return recipientIds
;
1203 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1204 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1205 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1207 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1208 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1210 return getRegisteredUser(number
);
1211 } catch (IOException e
) {
1218 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1219 return account
.getRecipientStore().resolveRecipient(address
);
1222 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1223 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1227 public void close() throws IOException
{
1231 private void close(boolean closeAccount
) throws IOException
{
1232 executor
.shutdown();
1234 dependencies
.getSignalWebSocket().disconnect();
1236 if (closeAccount
&& account
!= null) {