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
.ServiceEnvironment
;
28 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
29 import org
.asamk
.signal
.manager
.groups
.GroupId
;
30 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
31 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
32 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
33 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
34 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
35 import org
.asamk
.signal
.manager
.groups
.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
.IncomingMessageHandler
;
42 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
43 import org
.asamk
.signal
.manager
.helper
.PreKeyHelper
;
44 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
45 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
46 import org
.asamk
.signal
.manager
.helper
.StorageHelper
;
47 import org
.asamk
.signal
.manager
.helper
.SyncHelper
;
48 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
49 import org
.asamk
.signal
.manager
.jobs
.Context
;
50 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
51 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
52 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
53 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
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
.RecipientId
;
58 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
59 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
60 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
61 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
62 import org
.asamk
.signal
.manager
.util
.Utils
;
63 import org
.slf4j
.Logger
;
64 import org
.slf4j
.LoggerFactory
;
65 import org
.whispersystems
.libsignal
.IdentityKey
;
66 import org
.whispersystems
.libsignal
.InvalidKeyException
;
67 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
68 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
69 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintParsingException
;
70 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintVersionMismatchException
;
71 import org
.whispersystems
.libsignal
.util
.Pair
;
72 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
73 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
74 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
75 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
76 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
77 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
78 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
79 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
80 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
81 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
82 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
83 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
84 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
85 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
86 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
87 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
88 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
89 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
90 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
91 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
92 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
93 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
95 import java
.io
.Closeable
;
97 import java
.io
.IOException
;
99 import java
.net
.URISyntaxException
;
100 import java
.net
.URLEncoder
;
101 import java
.nio
.charset
.StandardCharsets
;
102 import java
.security
.SignatureException
;
103 import java
.util
.Arrays
;
104 import java
.util
.Collection
;
105 import java
.util
.Date
;
106 import java
.util
.HashMap
;
107 import java
.util
.HashSet
;
108 import java
.util
.List
;
109 import java
.util
.Map
;
110 import java
.util
.Set
;
111 import java
.util
.UUID
;
112 import java
.util
.concurrent
.ExecutorService
;
113 import java
.util
.concurrent
.Executors
;
114 import java
.util
.concurrent
.TimeUnit
;
115 import java
.util
.concurrent
.TimeoutException
;
116 import java
.util
.concurrent
.locks
.ReentrantLock
;
117 import java
.util
.function
.Function
;
118 import java
.util
.stream
.Collectors
;
120 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
122 public class Manager
implements Closeable
{
124 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
126 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
127 private final SignalDependencies dependencies
;
129 private SignalAccount account
;
131 private final ExecutorService executor
= Executors
.newCachedThreadPool();
133 private final ProfileHelper profileHelper
;
134 private final PinHelper pinHelper
;
135 private final StorageHelper storageHelper
;
136 private final SendHelper sendHelper
;
137 private final SyncHelper syncHelper
;
138 private final AttachmentHelper attachmentHelper
;
139 private final GroupHelper groupHelper
;
140 private final ContactHelper contactHelper
;
141 private final IncomingMessageHandler incomingMessageHandler
;
142 private final PreKeyHelper preKeyHelper
;
144 private final Context context
;
145 private boolean hasCaughtUpWithOldMessages
= false;
148 SignalAccount account
,
149 PathConfig pathConfig
,
150 ServiceEnvironmentConfig serviceEnvironmentConfig
,
153 this.account
= account
;
154 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
156 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
157 account
.getUsername(),
158 account
.getPassword(),
159 account
.getDeviceId());
160 final var sessionLock
= new SignalSessionLock() {
161 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
164 public Lock
acquire() {
166 return LEGACY_LOCK
::unlock
;
169 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
172 account
.getSignalProtocolStore(),
175 final var avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
176 final var attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
177 final var stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
179 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
180 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
181 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
182 account
.getProfileStore()::getProfileKey
,
183 this::getRecipientProfile
,
184 this::getSenderCertificate
);
185 this.profileHelper
= new ProfileHelper(account
,
188 account
.getProfileStore()::getProfileKey
,
189 unidentifiedAccessHelper
::getAccessFor
,
190 this::resolveSignalServiceAddress
);
191 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
192 this::getRecipientProfile
,
193 account
::getSelfRecipientId
,
194 dependencies
.getGroupsV2Operations(),
195 dependencies
.getGroupsV2Api(),
196 this::resolveSignalServiceAddress
);
197 this.sendHelper
= new SendHelper(account
,
199 unidentifiedAccessHelper
,
200 this::resolveSignalServiceAddress
,
201 account
.getRecipientStore(),
202 this::handleIdentityFailure
,
204 this::refreshRegisteredUser
);
205 this.groupHelper
= new GroupHelper(account
,
211 this::resolveSignalServiceAddress
,
212 account
.getRecipientStore());
213 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
);
214 this.contactHelper
= new ContactHelper(account
);
215 this.syncHelper
= new SyncHelper(account
,
220 this::resolveSignalServiceAddress
);
221 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
223 this.context
= new Context(account
,
232 var jobExecutor
= new JobExecutor(context
);
234 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
236 account
.getRecipientStore(),
237 this::resolveSignalServiceAddress
,
242 this::getRecipientProfile
,
246 public String
getUsername() {
247 return account
.getUsername();
250 public RecipientId
getSelfRecipientId() {
251 return account
.getSelfRecipientId();
254 public int getDeviceId() {
255 return account
.getDeviceId();
258 public static Manager
init(
261 ServiceEnvironment serviceEnvironment
,
263 final TrustNewIdentity trustNewIdentity
264 ) throws IOException
, NotRegisteredException
{
265 var pathConfig
= PathConfig
.createDefault(settingsPath
);
267 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
268 throw new NotRegisteredException();
271 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true, trustNewIdentity
);
273 if (!account
.isRegistered()) {
274 throw new NotRegisteredException();
277 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
279 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
282 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
283 var pathConfig
= PathConfig
.createDefault(settingsPath
);
284 final var dataPath
= pathConfig
.getDataPath();
285 final var files
= dataPath
.listFiles();
291 return Arrays
.stream(files
)
292 .filter(File
::isFile
)
294 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
295 .collect(Collectors
.toList());
298 public void checkAccountState() throws IOException
{
299 if (account
.getLastReceiveTimestamp() == 0) {
300 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
302 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
303 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
306 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
310 preKeyHelper
.refreshPreKeysIfNecessary();
311 if (account
.getUuid() == null) {
312 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
314 updateAccountAttributes(null);
318 * This is used for checking a set of phone numbers for registration on Signal
320 * @param numbers The set of phone number in question
321 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
322 * @throws IOException if its unable to get the contacts to check if they're registered
324 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
325 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
327 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
328 } catch (InvalidNumberException e
) {
333 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
334 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
336 .filter(s
-> !s
.isEmpty())
337 .collect(Collectors
.toSet()));
339 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
340 final var number
= canonicalizedNumbers
.get(n
);
341 final var uuid
= registeredUsers
.get(number
);
342 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
346 public void updateAccountAttributes(String deviceName
) throws IOException
{
347 final String encryptedDeviceName
;
348 if (deviceName
== null) {
349 encryptedDeviceName
= account
.getEncryptedDeviceName();
351 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
352 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
353 account
.setEncryptedDeviceName(encryptedDeviceName
);
355 dependencies
.getAccountManager()
356 .setAccountAttributes(encryptedDeviceName
,
358 account
.getLocalRegistrationId(),
361 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
362 account
.getSelfUnidentifiedAccessKey(),
363 account
.isUnrestrictedUnidentifiedAccess(),
365 account
.isDiscoverableByPhoneNumber());
369 * @param givenName if null, the previous givenName will be kept
370 * @param familyName if null, the previous familyName will be kept
371 * @param about if null, the previous about text will be kept
372 * @param aboutEmoji if null, the previous about emoji will be kept
373 * @param avatar if avatar is null the image from the local avatar store is used (if present),
375 public void setProfile(
376 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
377 ) throws IOException
{
378 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
379 syncHelper
.sendSyncFetchProfileMessage();
382 public void unregister() throws IOException
{
383 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
384 // If this is the master device, other users can't send messages to this number anymore.
385 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
386 dependencies
.getAccountManager().setGcmId(Optional
.absent());
388 account
.setRegistered(false);
391 public void deleteAccount() throws IOException
{
393 pinHelper
.removeRegistrationLockPin();
394 } catch (UnauthenticatedResponseException e
) {
395 logger
.warn("Failed to remove registration lock pin");
397 account
.setRegistrationLockPin(null, null);
399 dependencies
.getAccountManager().deleteAccount();
401 account
.setRegistered(false);
404 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
405 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
408 public List
<Device
> getLinkedDevices() throws IOException
{
409 var devices
= dependencies
.getAccountManager().getDevices();
410 account
.setMultiDevice(devices
.size() > 1);
411 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
412 return devices
.stream().map(d
-> {
413 String deviceName
= d
.getName();
414 if (deviceName
!= null) {
416 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
417 } catch (IOException e
) {
418 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
421 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
422 }).collect(Collectors
.toList());
425 public void removeLinkedDevices(int deviceId
) throws IOException
{
426 dependencies
.getAccountManager().removeDevice(deviceId
);
427 var devices
= dependencies
.getAccountManager().getDevices();
428 account
.setMultiDevice(devices
.size() > 1);
431 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
432 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
434 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
437 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
438 var identityKeyPair
= account
.getIdentityKeyPair();
439 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
441 dependencies
.getAccountManager()
442 .addDevice(deviceIdentifier
,
445 Optional
.of(account
.getProfileKey().serialize()),
447 account
.setMultiDevice(true);
450 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
451 if (!account
.isMasterDevice()) {
452 throw new RuntimeException("Only master device can set a PIN");
454 if (pin
.isPresent()) {
455 final var masterKey
= account
.getPinMasterKey() != null
456 ? account
.getPinMasterKey()
457 : KeyUtils
.createMasterKey();
459 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
461 account
.setRegistrationLockPin(pin
.get(), masterKey
);
464 pinHelper
.removeRegistrationLockPin();
466 account
.setRegistrationLockPin(null, null);
470 void refreshPreKeys() throws IOException
{
471 preKeyHelper
.refreshPreKeys();
474 public Profile
getRecipientProfile(RecipientId recipientId
) {
475 return profileHelper
.getRecipientProfile(recipientId
);
478 public List
<GroupInfo
> getGroups() {
479 return account
.getGroupStore().getGroups();
482 public SendGroupMessageResults
quitGroup(
483 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
484 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
485 final var newAdmins
= resolveRecipients(groupAdmins
);
486 return groupHelper
.quitGroup(groupId
, newAdmins
);
489 public void deleteGroup(GroupId groupId
) throws IOException
{
490 groupHelper
.deleteGroup(groupId
);
493 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
494 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
495 ) throws IOException
, AttachmentInvalidException
{
496 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
499 public SendGroupMessageResults
updateGroup(
503 Set
<RecipientIdentifier
.Single
> members
,
504 Set
<RecipientIdentifier
.Single
> removeMembers
,
505 Set
<RecipientIdentifier
.Single
> admins
,
506 Set
<RecipientIdentifier
.Single
> removeAdmins
,
507 boolean resetGroupLink
,
508 GroupLinkState groupLinkState
,
509 GroupPermission addMemberPermission
,
510 GroupPermission editDetailsPermission
,
512 Integer expirationTimer
,
513 Boolean isAnnouncementGroup
514 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
515 return groupHelper
.updateGroup(groupId
,
518 members
== null ?
null : resolveRecipients(members
),
519 removeMembers
== null ?
null : resolveRecipients(removeMembers
),
520 admins
== null ?
null : resolveRecipients(admins
),
521 removeAdmins
== null ?
null : resolveRecipients(removeAdmins
),
525 editDetailsPermission
,
528 isAnnouncementGroup
);
531 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
532 GroupInviteLinkUrl inviteLinkUrl
533 ) throws IOException
, GroupLinkNotActiveException
{
534 return groupHelper
.joinGroup(inviteLinkUrl
);
537 public SendMessageResults
sendMessage(
538 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
539 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
540 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
541 long timestamp
= System
.currentTimeMillis();
542 messageBuilder
.withTimestamp(timestamp
);
543 for (final var recipient
: recipients
) {
544 if (recipient
instanceof RecipientIdentifier
.Single
) {
545 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
546 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
547 results
.put(recipient
, List
.of(result
));
548 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
549 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
550 results
.put(recipient
, List
.of(result
));
551 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
552 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
553 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
554 results
.put(recipient
, result
);
557 return new SendMessageResults(timestamp
, results
);
560 public void sendTypingMessage(
561 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
562 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
563 final var timestamp
= System
.currentTimeMillis();
564 for (var recipient
: recipients
) {
565 if (recipient
instanceof RecipientIdentifier
.Single
) {
566 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
567 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
568 sendHelper
.sendTypingMessage(message
, recipientId
);
569 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
570 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
571 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
572 sendHelper
.sendGroupTypingMessage(message
, groupId
);
577 public void sendReadReceipt(
578 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
579 ) throws IOException
, UntrustedIdentityException
{
580 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
582 System
.currentTimeMillis());
584 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
587 public void sendViewedReceipt(
588 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
589 ) throws IOException
, UntrustedIdentityException
{
590 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
592 System
.currentTimeMillis());
594 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
597 public SendMessageResults
sendMessage(
598 Message message
, Set
<RecipientIdentifier
> recipients
599 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
600 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
601 applyMessage(messageBuilder
, message
);
602 return sendMessage(messageBuilder
, recipients
);
605 private void applyMessage(
606 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
607 ) throws AttachmentInvalidException
, IOException
{
608 messageBuilder
.withBody(message
.getMessageText());
609 final var attachments
= message
.getAttachments();
610 if (attachments
!= null) {
611 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
615 public SendMessageResults
sendRemoteDeleteMessage(
616 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
617 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
618 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
619 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
620 return sendMessage(messageBuilder
, recipients
);
623 public SendMessageResults
sendMessageReaction(
626 RecipientIdentifier
.Single targetAuthor
,
627 long targetSentTimestamp
,
628 Set
<RecipientIdentifier
> recipients
629 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
630 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
631 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
633 resolveSignalServiceAddress(targetAuthorRecipientId
),
634 targetSentTimestamp
);
635 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
636 return sendMessage(messageBuilder
, recipients
);
639 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
640 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
643 return sendMessage(messageBuilder
,
644 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
645 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
646 throw new AssertionError(e
);
648 for (var recipient
: recipients
) {
649 final var recipientId
= resolveRecipient(recipient
);
650 account
.getSessionStore().deleteAllSessions(recipientId
);
655 public void setContactName(
656 RecipientIdentifier
.Single recipient
, String name
657 ) throws NotMasterDeviceException
, UnregisteredUserException
{
658 if (!account
.isMasterDevice()) {
659 throw new NotMasterDeviceException();
661 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
664 public void setContactBlocked(
665 RecipientIdentifier
.Single recipient
, boolean blocked
666 ) throws NotMasterDeviceException
, IOException
{
667 if (!account
.isMasterDevice()) {
668 throw new NotMasterDeviceException();
670 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
671 // TODO cycle our profile key
672 syncHelper
.sendBlockedList();
675 public void setGroupBlocked(
676 final GroupId groupId
, final boolean blocked
677 ) throws GroupNotFoundException
, IOException
{
678 groupHelper
.setGroupBlocked(groupId
, blocked
);
679 // TODO cycle our profile key
680 syncHelper
.sendBlockedList();
684 * Change the expiration timer for a contact
686 public void setExpirationTimer(
687 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
688 ) throws IOException
{
689 var recipientId
= resolveRecipient(recipient
);
690 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
691 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
693 sendMessage(messageBuilder
, Set
.of(recipient
));
694 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
695 throw new AssertionError(e
);
700 * Upload the sticker pack from path.
702 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
703 * @return if successful, returns the URL to install the sticker pack in the signal app
705 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
706 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
708 var messageSender
= dependencies
.getMessageSender();
710 var packKey
= KeyUtils
.createStickerUploadKey();
711 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
712 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
714 var sticker
= new Sticker(packId
, packKey
);
715 account
.getStickerStore().updateSticker(sticker
);
718 return new URI("https",
722 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
724 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
725 } catch (URISyntaxException e
) {
726 throw new AssertionError(e
);
730 public void requestAllSyncData() throws IOException
{
731 syncHelper
.requestAllSyncData();
732 retrieveRemoteStorage();
735 void retrieveRemoteStorage() throws IOException
{
736 if (account
.getStorageKey() != null) {
737 storageHelper
.readDataFromStorage();
741 private byte[] getSenderCertificate() {
744 if (account
.isPhoneNumberShared()) {
745 certificate
= dependencies
.getAccountManager().getSenderCertificate();
747 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
749 } catch (IOException e
) {
750 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
753 // TODO cache for a day
757 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
758 final var address
= resolveSignalServiceAddress(recipientId
);
759 if (!address
.getNumber().isPresent()) {
762 final var number
= address
.getNumber().get();
763 final var uuid
= getRegisteredUser(number
);
764 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
767 private UUID
getRegisteredUser(final String number
) throws IOException
{
768 final Map
<String
, UUID
> uuidMap
;
770 uuidMap
= getRegisteredUsers(Set
.of(number
));
771 } catch (NumberFormatException e
) {
772 throw new UnregisteredUserException(number
, e
);
774 final var uuid
= uuidMap
.get(number
);
776 throw new UnregisteredUserException(number
, null);
781 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
782 final Map
<String
, UUID
> registeredUsers
;
784 registeredUsers
= dependencies
.getAccountManager()
785 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
787 serviceEnvironmentConfig
.getCdsMrenclave());
788 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
789 throw new IOException(e
);
792 // Store numbers as recipients so we have the number/uuid association
793 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
795 return registeredUsers
;
798 public void sendTypingMessage(
799 TypingAction action
, Set
<RecipientIdentifier
> recipients
800 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
801 sendTypingMessage(action
.toSignalService(), recipients
);
804 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
805 Set
<HandleAction
> queuedActions
= new HashSet
<>();
806 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
807 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
808 if (actions
!= null) {
809 queuedActions
.addAll(actions
);
812 handleQueuedActions(queuedActions
);
815 private List
<HandleAction
> retryFailedReceivedMessage(
816 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
818 var envelope
= cachedMessage
.loadEnvelope();
819 if (envelope
== null) {
820 cachedMessage
.delete();
824 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
825 final var actions
= result
.first();
826 final var exception
= result
.second();
828 if (exception
instanceof UntrustedIdentityException
) {
829 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
830 // Envelope is more than a month old, cleaning up.
831 cachedMessage
.delete();
834 if (!envelope
.hasSourceUuid()) {
835 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
836 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
838 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
839 } catch (IOException ioException
) {
840 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
846 // If successful and for all other errors that are not recoverable, delete the cached message
847 cachedMessage
.delete();
851 public void receiveMessages(
854 boolean returnOnTimeout
,
855 boolean ignoreAttachments
,
856 ReceiveMessageHandler handler
857 ) throws IOException
{
858 retryFailedReceivedMessages(handler
, ignoreAttachments
);
860 Set
<HandleAction
> queuedActions
= new HashSet
<>();
862 final var signalWebSocket
= dependencies
.getSignalWebSocket();
863 signalWebSocket
.connect();
865 hasCaughtUpWithOldMessages
= false;
867 while (!Thread
.interrupted()) {
868 SignalServiceEnvelope envelope
;
869 final CachedMessage
[] cachedMessage
= {null};
870 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
871 logger
.debug("Checking for new message from server");
873 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
874 final var recipientId
= envelope1
.hasSourceUuid()
875 ?
resolveRecipient(envelope1
.getSourceAddress())
877 // store message on disk, before acknowledging receipt to the server
878 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
880 if (result
.isPresent()) {
881 envelope
= result
.get();
882 logger
.debug("New message received from server");
884 logger
.debug("Received indicator that server queue is empty");
885 handleQueuedActions(queuedActions
);
886 queuedActions
.clear();
888 hasCaughtUpWithOldMessages
= true;
889 synchronized (this) {
893 // Continue to wait another timeout for new messages
896 } catch (AssertionError e
) {
897 if (e
.getCause() instanceof InterruptedException
) {
898 Thread
.currentThread().interrupt();
903 } catch (WebSocketUnavailableException e
) {
904 logger
.debug("Pipe unexpectedly unavailable, connecting");
905 signalWebSocket
.connect();
907 } catch (TimeoutException e
) {
908 if (returnOnTimeout
) return;
912 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
913 queuedActions
.addAll(result
.first());
914 final var exception
= result
.second();
916 if (hasCaughtUpWithOldMessages
) {
917 handleQueuedActions(queuedActions
);
919 if (cachedMessage
[0] != null) {
920 if (exception
instanceof UntrustedIdentityException
) {
921 final var address
= ((UntrustedIdentityException
) exception
).getSender();
922 final var recipientId
= resolveRecipient(address
);
923 if (!envelope
.hasSourceUuid()) {
925 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
926 } catch (IOException ioException
) {
927 logger
.warn("Failed to move cached message to recipient folder: {}",
928 ioException
.getMessage());
932 cachedMessage
[0].delete();
936 handleQueuedActions(queuedActions
);
939 public boolean hasCaughtUpWithOldMessages() {
940 return hasCaughtUpWithOldMessages
;
943 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
944 var interrupted
= false;
945 for (var action
: queuedActions
) {
947 action
.execute(context
);
948 } catch (Throwable e
) {
949 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
950 && e
.getCause() instanceof InterruptedException
) {
954 logger
.warn("Message action failed.", e
);
958 Thread
.currentThread().interrupt();
962 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
963 final RecipientId recipientId
;
965 recipientId
= resolveRecipient(recipient
);
966 } catch (UnregisteredUserException e
) {
969 return contactHelper
.isContactBlocked(recipientId
);
972 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
973 return attachmentHelper
.getAttachmentFile(attachmentId
);
976 public void sendContacts() throws IOException
{
977 syncHelper
.sendContacts();
980 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
981 return account
.getContactStore().getContacts();
984 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
985 final RecipientId recipientId
;
987 recipientId
= resolveRecipient(recipientIdentifier
);
988 } catch (UnregisteredUserException e
) {
992 final var contact
= account
.getContactStore().getContact(recipientId
);
993 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
994 return contact
.getName();
997 final var profile
= getRecipientProfile(recipientId
);
998 if (profile
!= null) {
999 return profile
.getDisplayName();
1005 public GroupInfo
getGroup(GroupId groupId
) {
1006 return groupHelper
.getGroup(groupId
);
1009 public List
<IdentityInfo
> getIdentities() {
1010 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
1029 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1030 RecipientId recipientId
;
1032 recipientId
= resolveRecipient(recipient
);
1033 } catch (UnregisteredUserException e
) {
1036 return trustIdentity(recipientId
,
1037 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1038 TrustLevel
.TRUSTED_VERIFIED
);
1042 * Trust this the identity with this safety number
1044 * @param recipient username of the identity
1045 * @param safetyNumber Safety number
1047 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1048 RecipientId recipientId
;
1050 recipientId
= resolveRecipient(recipient
);
1051 } catch (UnregisteredUserException e
) {
1054 var address
= resolveSignalServiceAddress(recipientId
);
1055 return trustIdentity(recipientId
,
1056 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1057 TrustLevel
.TRUSTED_VERIFIED
);
1061 * Trust this the identity with this scannable safety number
1063 * @param recipient username of the identity
1064 * @param safetyNumber Scannable safety number
1066 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1067 RecipientId recipientId
;
1069 recipientId
= resolveRecipient(recipient
);
1070 } catch (UnregisteredUserException e
) {
1073 var address
= resolveSignalServiceAddress(recipientId
);
1074 return trustIdentity(recipientId
, identityKey
-> {
1075 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1077 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1078 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1081 }, TrustLevel
.TRUSTED_VERIFIED
);
1085 * Trust all keys of this identity without verification
1087 * @param recipient username of the identity
1089 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1090 RecipientId recipientId
;
1092 recipientId
= resolveRecipient(recipient
);
1093 } catch (UnregisteredUserException e
) {
1096 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1099 private boolean trustIdentity(
1100 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1102 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1103 if (identity
== null) {
1107 if (!verifier
.apply(identity
.getIdentityKey())) {
1111 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1113 var address
= resolveSignalServiceAddress(recipientId
);
1114 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1115 } catch (IOException e
) {
1116 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1122 private void handleIdentityFailure(
1123 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1125 final var identityKey
= identityFailure
.getIdentityKey();
1126 if (identityKey
!= null) {
1127 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1129 account
.getSessionStore().archiveSessions(recipientId
);
1132 // Retrieve profile to get the current identity key from the server
1133 profileHelper
.refreshRecipientProfile(recipientId
);
1137 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1138 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1139 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1142 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1143 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1144 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1147 private Fingerprint
computeSafetyNumberFingerprint(
1148 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1150 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1151 account
.getSelfAddress(),
1152 account
.getIdentityKeyPair().getPublicKey(),
1157 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1158 return resolveSignalServiceAddress(resolveRecipient(address
));
1161 public SignalServiceAddress
resolveSignalServiceAddress(UUID uuid
) {
1162 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1165 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1166 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1167 if (address
.getUuid().isPresent()) {
1168 return address
.toSignalServiceAddress();
1171 // Address in recipient store doesn't have a uuid, this shouldn't happen
1172 // Try to retrieve the uuid from the server
1173 final var number
= address
.getNumber().get();
1175 return resolveSignalServiceAddress(getRegisteredUser(number
));
1176 } catch (IOException e
) {
1177 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1178 // Return SignalServiceAddress with unknown UUID
1179 return address
.toSignalServiceAddress();
1183 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1184 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1185 for (var number
: recipients
) {
1186 final var recipientId
= resolveRecipient(number
);
1187 recipientIds
.add(recipientId
);
1189 return recipientIds
;
1192 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1193 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1194 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1196 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1197 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1199 return getRegisteredUser(number
);
1200 } catch (IOException e
) {
1207 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1208 return account
.getRecipientStore().resolveRecipient(address
);
1211 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1212 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1216 public void close() throws IOException
{
1220 private void close(boolean closeAccount
) throws IOException
{
1221 executor
.shutdown();
1223 dependencies
.getSignalWebSocket().disconnect();
1225 if (closeAccount
&& account
!= null) {
1231 public interface ReceiveMessageHandler
{
1233 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);