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
,
231 var jobExecutor
= new JobExecutor(context
);
233 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
235 account
.getRecipientStore(),
236 this::resolveSignalServiceAddress
,
244 public String
getUsername() {
245 return account
.getUsername();
248 public RecipientId
getSelfRecipientId() {
249 return account
.getSelfRecipientId();
252 public int getDeviceId() {
253 return account
.getDeviceId();
256 public static Manager
init(
259 ServiceEnvironment serviceEnvironment
,
261 final TrustNewIdentity trustNewIdentity
262 ) throws IOException
, NotRegisteredException
{
263 var pathConfig
= PathConfig
.createDefault(settingsPath
);
265 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
266 throw new NotRegisteredException();
269 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true, trustNewIdentity
);
271 if (!account
.isRegistered()) {
272 throw new NotRegisteredException();
275 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
277 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
280 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
281 var pathConfig
= PathConfig
.createDefault(settingsPath
);
282 final var dataPath
= pathConfig
.getDataPath();
283 final var files
= dataPath
.listFiles();
289 return Arrays
.stream(files
)
290 .filter(File
::isFile
)
292 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
293 .collect(Collectors
.toList());
296 public void checkAccountState() throws IOException
{
297 if (account
.getLastReceiveTimestamp() == 0) {
298 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
300 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
301 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
304 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
308 preKeyHelper
.refreshPreKeysIfNecessary();
309 if (account
.getUuid() == null) {
310 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
312 updateAccountAttributes(null);
316 * This is used for checking a set of phone numbers for registration on Signal
318 * @param numbers The set of phone number in question
319 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
320 * @throws IOException if its unable to get the contacts to check if they're registered
322 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
323 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
325 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
326 } catch (InvalidNumberException e
) {
331 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
332 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
334 .filter(s
-> !s
.isEmpty())
335 .collect(Collectors
.toSet()));
337 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
338 final var number
= canonicalizedNumbers
.get(n
);
339 final var uuid
= registeredUsers
.get(number
);
340 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
344 public void updateAccountAttributes(String deviceName
) throws IOException
{
345 final String encryptedDeviceName
;
346 if (deviceName
== null) {
347 encryptedDeviceName
= account
.getEncryptedDeviceName();
349 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
350 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
351 account
.setEncryptedDeviceName(encryptedDeviceName
);
353 dependencies
.getAccountManager()
354 .setAccountAttributes(encryptedDeviceName
,
356 account
.getLocalRegistrationId(),
359 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
360 account
.getSelfUnidentifiedAccessKey(),
361 account
.isUnrestrictedUnidentifiedAccess(),
363 account
.isDiscoverableByPhoneNumber());
367 * @param givenName if null, the previous givenName will be kept
368 * @param familyName if null, the previous familyName will be kept
369 * @param about if null, the previous about text will be kept
370 * @param aboutEmoji if null, the previous about emoji will be kept
371 * @param avatar if avatar is null the image from the local avatar store is used (if present),
373 public void setProfile(
374 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
375 ) throws IOException
{
376 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
377 syncHelper
.sendSyncFetchProfileMessage();
380 public void unregister() throws IOException
{
381 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
382 // If this is the master device, other users can't send messages to this number anymore.
383 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
384 dependencies
.getAccountManager().setGcmId(Optional
.absent());
386 account
.setRegistered(false);
389 public void deleteAccount() throws IOException
{
391 pinHelper
.removeRegistrationLockPin();
392 } catch (UnauthenticatedResponseException e
) {
393 logger
.warn("Failed to remove registration lock pin");
395 account
.setRegistrationLockPin(null, null);
397 dependencies
.getAccountManager().deleteAccount();
399 account
.setRegistered(false);
402 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
403 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
406 public List
<Device
> getLinkedDevices() throws IOException
{
407 var devices
= dependencies
.getAccountManager().getDevices();
408 account
.setMultiDevice(devices
.size() > 1);
409 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
410 return devices
.stream().map(d
-> {
411 String deviceName
= d
.getName();
412 if (deviceName
!= null) {
414 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
415 } catch (IOException e
) {
416 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
419 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
420 }).collect(Collectors
.toList());
423 public void removeLinkedDevices(int deviceId
) throws IOException
{
424 dependencies
.getAccountManager().removeDevice(deviceId
);
425 var devices
= dependencies
.getAccountManager().getDevices();
426 account
.setMultiDevice(devices
.size() > 1);
429 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
430 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
432 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
435 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
436 var identityKeyPair
= account
.getIdentityKeyPair();
437 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
439 dependencies
.getAccountManager()
440 .addDevice(deviceIdentifier
,
443 Optional
.of(account
.getProfileKey().serialize()),
445 account
.setMultiDevice(true);
448 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
449 if (!account
.isMasterDevice()) {
450 throw new RuntimeException("Only master device can set a PIN");
452 if (pin
.isPresent()) {
453 final var masterKey
= account
.getPinMasterKey() != null
454 ? account
.getPinMasterKey()
455 : KeyUtils
.createMasterKey();
457 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
459 account
.setRegistrationLockPin(pin
.get(), masterKey
);
462 pinHelper
.removeRegistrationLockPin();
464 account
.setRegistrationLockPin(null, null);
468 void refreshPreKeys() throws IOException
{
469 preKeyHelper
.refreshPreKeys();
472 public Profile
getRecipientProfile(RecipientId recipientId
) {
473 return profileHelper
.getRecipientProfile(recipientId
);
476 public List
<GroupInfo
> getGroups() {
477 return account
.getGroupStore().getGroups();
480 public SendGroupMessageResults
quitGroup(
481 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
482 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
483 final var newAdmins
= resolveRecipients(groupAdmins
);
484 return groupHelper
.quitGroup(groupId
, newAdmins
);
487 public void deleteGroup(GroupId groupId
) throws IOException
{
488 groupHelper
.deleteGroup(groupId
);
491 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
492 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
493 ) throws IOException
, AttachmentInvalidException
{
494 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
497 public SendGroupMessageResults
updateGroup(
501 Set
<RecipientIdentifier
.Single
> members
,
502 Set
<RecipientIdentifier
.Single
> removeMembers
,
503 Set
<RecipientIdentifier
.Single
> admins
,
504 Set
<RecipientIdentifier
.Single
> removeAdmins
,
505 boolean resetGroupLink
,
506 GroupLinkState groupLinkState
,
507 GroupPermission addMemberPermission
,
508 GroupPermission editDetailsPermission
,
510 Integer expirationTimer
,
511 Boolean isAnnouncementGroup
512 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
513 return groupHelper
.updateGroup(groupId
,
516 members
== null ?
null : resolveRecipients(members
),
517 removeMembers
== null ?
null : resolveRecipients(removeMembers
),
518 admins
== null ?
null : resolveRecipients(admins
),
519 removeAdmins
== null ?
null : resolveRecipients(removeAdmins
),
523 editDetailsPermission
,
526 isAnnouncementGroup
);
529 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
530 GroupInviteLinkUrl inviteLinkUrl
531 ) throws IOException
, GroupLinkNotActiveException
{
532 return groupHelper
.joinGroup(inviteLinkUrl
);
535 public SendMessageResults
sendMessage(
536 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
537 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
538 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
539 long timestamp
= System
.currentTimeMillis();
540 messageBuilder
.withTimestamp(timestamp
);
541 for (final var recipient
: recipients
) {
542 if (recipient
instanceof RecipientIdentifier
.Single
) {
543 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
544 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
545 results
.put(recipient
, List
.of(result
));
546 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
547 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
548 results
.put(recipient
, List
.of(result
));
549 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
550 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
551 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
552 results
.put(recipient
, result
);
555 return new SendMessageResults(timestamp
, results
);
558 public void sendTypingMessage(
559 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
560 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
561 final var timestamp
= System
.currentTimeMillis();
562 for (var recipient
: recipients
) {
563 if (recipient
instanceof RecipientIdentifier
.Single
) {
564 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
565 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
566 sendHelper
.sendTypingMessage(message
, recipientId
);
567 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
568 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
569 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
570 sendHelper
.sendGroupTypingMessage(message
, groupId
);
575 public void sendReadReceipt(
576 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
577 ) throws IOException
, UntrustedIdentityException
{
578 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
580 System
.currentTimeMillis());
582 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
585 public void sendViewedReceipt(
586 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
587 ) throws IOException
, UntrustedIdentityException
{
588 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
590 System
.currentTimeMillis());
592 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
595 public SendMessageResults
sendMessage(
596 Message message
, Set
<RecipientIdentifier
> recipients
597 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
598 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
599 applyMessage(messageBuilder
, message
);
600 return sendMessage(messageBuilder
, recipients
);
603 private void applyMessage(
604 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
605 ) throws AttachmentInvalidException
, IOException
{
606 messageBuilder
.withBody(message
.getMessageText());
607 final var attachments
= message
.getAttachments();
608 if (attachments
!= null) {
609 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
613 public SendMessageResults
sendRemoteDeleteMessage(
614 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
615 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
616 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
617 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
618 return sendMessage(messageBuilder
, recipients
);
621 public SendMessageResults
sendMessageReaction(
624 RecipientIdentifier
.Single targetAuthor
,
625 long targetSentTimestamp
,
626 Set
<RecipientIdentifier
> recipients
627 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
628 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
629 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
631 resolveSignalServiceAddress(targetAuthorRecipientId
),
632 targetSentTimestamp
);
633 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
634 return sendMessage(messageBuilder
, recipients
);
637 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
638 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
641 return sendMessage(messageBuilder
,
642 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
643 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
644 throw new AssertionError(e
);
646 for (var recipient
: recipients
) {
647 final var recipientId
= resolveRecipient(recipient
);
648 account
.getSessionStore().deleteAllSessions(recipientId
);
653 public void setContactName(
654 RecipientIdentifier
.Single recipient
, String name
655 ) throws NotMasterDeviceException
, UnregisteredUserException
{
656 if (!account
.isMasterDevice()) {
657 throw new NotMasterDeviceException();
659 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
662 public void setContactBlocked(
663 RecipientIdentifier
.Single recipient
, boolean blocked
664 ) throws NotMasterDeviceException
, IOException
{
665 if (!account
.isMasterDevice()) {
666 throw new NotMasterDeviceException();
668 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
669 // TODO cycle our profile key
670 syncHelper
.sendBlockedList();
673 public void setGroupBlocked(
674 final GroupId groupId
, final boolean blocked
675 ) throws GroupNotFoundException
, IOException
{
676 groupHelper
.setGroupBlocked(groupId
, blocked
);
677 // TODO cycle our profile key
678 syncHelper
.sendBlockedList();
682 * Change the expiration timer for a contact
684 public void setExpirationTimer(
685 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
686 ) throws IOException
{
687 var recipientId
= resolveRecipient(recipient
);
688 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
689 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
691 sendMessage(messageBuilder
, Set
.of(recipient
));
692 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
693 throw new AssertionError(e
);
698 * Upload the sticker pack from path.
700 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
701 * @return if successful, returns the URL to install the sticker pack in the signal app
703 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
704 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
706 var messageSender
= dependencies
.getMessageSender();
708 var packKey
= KeyUtils
.createStickerUploadKey();
709 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
710 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
712 var sticker
= new Sticker(packId
, packKey
);
713 account
.getStickerStore().updateSticker(sticker
);
716 return new URI("https",
720 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
722 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
723 } catch (URISyntaxException e
) {
724 throw new AssertionError(e
);
728 public void requestAllSyncData() throws IOException
{
729 syncHelper
.requestAllSyncData();
730 retrieveRemoteStorage();
733 void retrieveRemoteStorage() throws IOException
{
734 if (account
.getStorageKey() != null) {
735 storageHelper
.readDataFromStorage();
739 private byte[] getSenderCertificate() {
742 if (account
.isPhoneNumberShared()) {
743 certificate
= dependencies
.getAccountManager().getSenderCertificate();
745 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
747 } catch (IOException e
) {
748 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
751 // TODO cache for a day
755 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
756 final var address
= resolveSignalServiceAddress(recipientId
);
757 if (!address
.getNumber().isPresent()) {
760 final var number
= address
.getNumber().get();
761 final var uuid
= getRegisteredUser(number
);
762 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
765 private UUID
getRegisteredUser(final String number
) throws IOException
{
766 final Map
<String
, UUID
> uuidMap
;
768 uuidMap
= getRegisteredUsers(Set
.of(number
));
769 } catch (NumberFormatException e
) {
770 throw new UnregisteredUserException(number
, e
);
772 final var uuid
= uuidMap
.get(number
);
774 throw new UnregisteredUserException(number
, null);
779 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
780 final Map
<String
, UUID
> registeredUsers
;
782 registeredUsers
= dependencies
.getAccountManager()
783 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
785 serviceEnvironmentConfig
.getCdsMrenclave());
786 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
787 throw new IOException(e
);
790 // Store numbers as recipients so we have the number/uuid association
791 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
793 return registeredUsers
;
796 public void sendTypingMessage(
797 TypingAction action
, Set
<RecipientIdentifier
> recipients
798 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
799 sendTypingMessage(action
.toSignalService(), recipients
);
802 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
803 Set
<HandleAction
> queuedActions
= new HashSet
<>();
804 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
805 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
806 if (actions
!= null) {
807 queuedActions
.addAll(actions
);
810 handleQueuedActions(queuedActions
);
813 private List
<HandleAction
> retryFailedReceivedMessage(
814 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
816 var envelope
= cachedMessage
.loadEnvelope();
817 if (envelope
== null) {
818 cachedMessage
.delete();
822 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
823 final var actions
= result
.first();
824 final var exception
= result
.second();
826 if (exception
instanceof UntrustedIdentityException
) {
827 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
828 // Envelope is more than a month old, cleaning up.
829 cachedMessage
.delete();
832 if (!envelope
.hasSourceUuid()) {
833 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
834 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
836 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
837 } catch (IOException ioException
) {
838 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
844 // If successful and for all other errors that are not recoverable, delete the cached message
845 cachedMessage
.delete();
849 public void receiveMessages(
852 boolean returnOnTimeout
,
853 boolean ignoreAttachments
,
854 ReceiveMessageHandler handler
855 ) throws IOException
{
856 retryFailedReceivedMessages(handler
, ignoreAttachments
);
858 Set
<HandleAction
> queuedActions
= new HashSet
<>();
860 final var signalWebSocket
= dependencies
.getSignalWebSocket();
861 signalWebSocket
.connect();
863 hasCaughtUpWithOldMessages
= false;
865 while (!Thread
.interrupted()) {
866 SignalServiceEnvelope envelope
;
867 final CachedMessage
[] cachedMessage
= {null};
868 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
869 logger
.debug("Checking for new message from server");
871 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
872 final var recipientId
= envelope1
.hasSourceUuid()
873 ?
resolveRecipient(envelope1
.getSourceAddress())
875 // store message on disk, before acknowledging receipt to the server
876 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
878 logger
.debug("New message received from server");
879 if (result
.isPresent()) {
880 envelope
= result
.get();
882 // Received indicator that server queue is empty
883 handleQueuedActions(queuedActions
);
884 queuedActions
.clear();
886 hasCaughtUpWithOldMessages
= true;
887 synchronized (this) {
891 // Continue to wait another timeout for new messages
894 } catch (AssertionError e
) {
895 if (e
.getCause() instanceof InterruptedException
) {
896 Thread
.currentThread().interrupt();
901 } catch (WebSocketUnavailableException e
) {
902 logger
.debug("Pipe unexpectedly unavailable, connecting");
903 signalWebSocket
.connect();
905 } catch (TimeoutException e
) {
906 if (returnOnTimeout
) return;
910 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
911 queuedActions
.addAll(result
.first());
912 final var exception
= result
.second();
914 if (hasCaughtUpWithOldMessages
) {
915 handleQueuedActions(queuedActions
);
917 if (cachedMessage
[0] != null) {
918 if (exception
instanceof UntrustedIdentityException
) {
919 final var address
= ((UntrustedIdentityException
) exception
).getSender();
920 final var recipientId
= resolveRecipient(address
);
921 if (!envelope
.hasSourceUuid()) {
923 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
924 } catch (IOException ioException
) {
925 logger
.warn("Failed to move cached message to recipient folder: {}",
926 ioException
.getMessage());
930 cachedMessage
[0].delete();
934 handleQueuedActions(queuedActions
);
937 public boolean hasCaughtUpWithOldMessages() {
938 return hasCaughtUpWithOldMessages
;
941 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
942 var interrupted
= false;
943 for (var action
: queuedActions
) {
945 action
.execute(context
);
946 } catch (Throwable e
) {
947 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
948 && e
.getCause() instanceof InterruptedException
) {
952 logger
.warn("Message action failed.", e
);
956 Thread
.currentThread().interrupt();
960 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
961 final RecipientId recipientId
;
963 recipientId
= resolveRecipient(recipient
);
964 } catch (UnregisteredUserException e
) {
967 return contactHelper
.isContactBlocked(recipientId
);
970 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
971 return attachmentHelper
.getAttachmentFile(attachmentId
);
974 public void sendContacts() throws IOException
{
975 syncHelper
.sendContacts();
978 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
979 return account
.getContactStore().getContacts();
982 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
983 final RecipientId recipientId
;
985 recipientId
= resolveRecipient(recipientIdentifier
);
986 } catch (UnregisteredUserException e
) {
990 final var contact
= account
.getContactStore().getContact(recipientId
);
991 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
992 return contact
.getName();
995 final var profile
= getRecipientProfile(recipientId
);
996 if (profile
!= null) {
997 return profile
.getDisplayName();
1003 public GroupInfo
getGroup(GroupId groupId
) {
1004 return groupHelper
.getGroup(groupId
);
1007 public List
<IdentityInfo
> getIdentities() {
1008 return account
.getIdentityKeyStore().getIdentities();
1011 public List
<IdentityInfo
> getIdentities(RecipientIdentifier
.Single recipient
) {
1012 IdentityInfo identity
;
1014 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1015 } catch (UnregisteredUserException e
) {
1018 return identity
== null ? List
.of() : List
.of(identity
);
1022 * Trust this the identity with this fingerprint
1024 * @param recipient username of the identity
1025 * @param fingerprint Fingerprint
1027 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1028 RecipientId recipientId
;
1030 recipientId
= resolveRecipient(recipient
);
1031 } catch (UnregisteredUserException e
) {
1034 return trustIdentity(recipientId
,
1035 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1036 TrustLevel
.TRUSTED_VERIFIED
);
1040 * Trust this the identity with this safety number
1042 * @param recipient username of the identity
1043 * @param safetyNumber Safety number
1045 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1046 RecipientId recipientId
;
1048 recipientId
= resolveRecipient(recipient
);
1049 } catch (UnregisteredUserException e
) {
1052 var address
= resolveSignalServiceAddress(recipientId
);
1053 return trustIdentity(recipientId
,
1054 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1055 TrustLevel
.TRUSTED_VERIFIED
);
1059 * Trust this the identity with this scannable safety number
1061 * @param recipient username of the identity
1062 * @param safetyNumber Scannable safety number
1064 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1065 RecipientId recipientId
;
1067 recipientId
= resolveRecipient(recipient
);
1068 } catch (UnregisteredUserException e
) {
1071 var address
= resolveSignalServiceAddress(recipientId
);
1072 return trustIdentity(recipientId
, identityKey
-> {
1073 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1075 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1076 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1079 }, TrustLevel
.TRUSTED_VERIFIED
);
1083 * Trust all keys of this identity without verification
1085 * @param recipient username of the identity
1087 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1088 RecipientId recipientId
;
1090 recipientId
= resolveRecipient(recipient
);
1091 } catch (UnregisteredUserException e
) {
1094 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1097 private boolean trustIdentity(
1098 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1100 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1101 if (identity
== null) {
1105 if (!verifier
.apply(identity
.getIdentityKey())) {
1109 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1111 var address
= resolveSignalServiceAddress(recipientId
);
1112 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1113 } catch (IOException e
) {
1114 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1120 private void handleIdentityFailure(
1121 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1123 final var identityKey
= identityFailure
.getIdentityKey();
1124 if (identityKey
!= null) {
1125 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1127 account
.getSessionStore().archiveSessions(recipientId
);
1130 // Retrieve profile to get the current identity key from the server
1131 profileHelper
.refreshRecipientProfile(recipientId
);
1135 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1136 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1137 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1140 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1141 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1142 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1145 private Fingerprint
computeSafetyNumberFingerprint(
1146 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1148 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1149 account
.getSelfAddress(),
1150 account
.getIdentityKeyPair().getPublicKey(),
1155 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1156 return resolveSignalServiceAddress(resolveRecipient(address
));
1159 public SignalServiceAddress
resolveSignalServiceAddress(UUID uuid
) {
1160 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1163 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1164 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1165 if (address
.getUuid().isPresent()) {
1166 return address
.toSignalServiceAddress();
1169 // Address in recipient store doesn't have a uuid, this shouldn't happen
1170 // Try to retrieve the uuid from the server
1171 final var number
= address
.getNumber().get();
1173 return resolveSignalServiceAddress(getRegisteredUser(number
));
1174 } catch (IOException e
) {
1175 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1176 // Return SignalServiceAddress with unknown UUID
1177 return address
.toSignalServiceAddress();
1181 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1182 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1183 for (var number
: recipients
) {
1184 final var recipientId
= resolveRecipient(number
);
1185 recipientIds
.add(recipientId
);
1187 return recipientIds
;
1190 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1191 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1192 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1194 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1195 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1197 return getRegisteredUser(number
);
1198 } catch (IOException e
) {
1205 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1206 return account
.getRecipientStore().resolveRecipient(address
);
1209 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1210 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1214 public void close() throws IOException
{
1218 private void close(boolean closeAccount
) throws IOException
{
1219 executor
.shutdown();
1221 dependencies
.getSignalWebSocket().disconnect();
1223 if (closeAccount
&& account
!= null) {
1229 public interface ReceiveMessageHandler
{
1231 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);