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
.ProfileHelper
;
44 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
45 import org
.asamk
.signal
.manager
.helper
.SyncHelper
;
46 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
47 import org
.asamk
.signal
.manager
.jobs
.Context
;
48 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
49 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
50 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
51 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
52 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
53 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
54 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
56 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
57 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
58 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
59 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
60 import org
.asamk
.signal
.manager
.util
.Utils
;
61 import org
.slf4j
.Logger
;
62 import org
.slf4j
.LoggerFactory
;
63 import org
.whispersystems
.libsignal
.IdentityKey
;
64 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
65 import org
.whispersystems
.libsignal
.InvalidKeyException
;
66 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
67 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
68 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintParsingException
;
69 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintVersionMismatchException
;
70 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
71 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
72 import org
.whispersystems
.libsignal
.util
.Pair
;
73 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
74 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
75 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
76 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
77 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
78 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
79 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
80 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
81 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
82 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
83 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
84 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
85 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
86 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
87 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
88 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
89 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
90 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
91 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
92 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
93 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
94 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
96 import java
.io
.Closeable
;
98 import java
.io
.IOException
;
100 import java
.net
.URISyntaxException
;
101 import java
.net
.URLEncoder
;
102 import java
.nio
.charset
.StandardCharsets
;
103 import java
.security
.SignatureException
;
104 import java
.util
.Arrays
;
105 import java
.util
.Collection
;
106 import java
.util
.Date
;
107 import java
.util
.HashMap
;
108 import java
.util
.HashSet
;
109 import java
.util
.List
;
110 import java
.util
.Map
;
111 import java
.util
.Set
;
112 import java
.util
.UUID
;
113 import java
.util
.concurrent
.ExecutorService
;
114 import java
.util
.concurrent
.Executors
;
115 import java
.util
.concurrent
.TimeUnit
;
116 import java
.util
.concurrent
.TimeoutException
;
117 import java
.util
.concurrent
.locks
.ReentrantLock
;
118 import java
.util
.function
.Function
;
119 import java
.util
.stream
.Collectors
;
121 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
123 public class Manager
implements Closeable
{
125 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
127 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
128 private final SignalDependencies dependencies
;
130 private SignalAccount account
;
132 private final ExecutorService executor
= Executors
.newCachedThreadPool();
134 private final ProfileHelper profileHelper
;
135 private final PinHelper pinHelper
;
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
;
143 private final Context context
;
146 SignalAccount account
,
147 PathConfig pathConfig
,
148 ServiceEnvironmentConfig serviceEnvironmentConfig
,
151 this.account
= account
;
152 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
154 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
155 account
.getUsername(),
156 account
.getPassword(),
157 account
.getDeviceId());
158 final var sessionLock
= new SignalSessionLock() {
159 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
162 public Lock
acquire() {
164 return LEGACY_LOCK
::unlock
;
167 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
170 account
.getSignalProtocolStore(),
173 final var avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
174 final var attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
175 final var stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
177 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
178 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
179 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
180 account
.getProfileStore()::getProfileKey
,
181 this::getRecipientProfile
,
182 this::getSenderCertificate
);
183 this.profileHelper
= new ProfileHelper(account
,
186 account
.getProfileStore()::getProfileKey
,
187 unidentifiedAccessHelper
::getAccessFor
,
188 this::resolveSignalServiceAddress
);
189 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
190 this::getRecipientProfile
,
191 account
::getSelfRecipientId
,
192 dependencies
.getGroupsV2Operations(),
193 dependencies
.getGroupsV2Api(),
194 this::resolveSignalServiceAddress
);
195 this.sendHelper
= new SendHelper(account
,
197 unidentifiedAccessHelper
,
198 this::resolveSignalServiceAddress
,
199 account
.getRecipientStore(),
200 this::handleIdentityFailure
,
202 this::refreshRegisteredUser
);
203 this.groupHelper
= new GroupHelper(account
,
209 this::resolveSignalServiceAddress
,
210 account
.getRecipientStore());
211 this.contactHelper
= new ContactHelper(account
);
212 this.syncHelper
= new SyncHelper(account
,
217 this::resolveSignalServiceAddress
);
219 this.context
= new Context(account
,
226 var jobExecutor
= new JobExecutor(context
);
228 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
230 account
.getRecipientStore(),
231 this::resolveSignalServiceAddress
,
239 public String
getUsername() {
240 return account
.getUsername();
243 public RecipientId
getSelfRecipientId() {
244 return account
.getSelfRecipientId();
247 private IdentityKeyPair
getIdentityKeyPair() {
248 return account
.getIdentityKeyPair();
251 public int getDeviceId() {
252 return account
.getDeviceId();
255 public static Manager
init(
258 ServiceEnvironment serviceEnvironment
,
260 final TrustNewIdentity trustNewIdentity
261 ) throws IOException
, NotRegisteredException
{
262 var pathConfig
= PathConfig
.createDefault(settingsPath
);
264 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
265 throw new NotRegisteredException();
268 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true, trustNewIdentity
);
270 if (!account
.isRegistered()) {
271 throw new NotRegisteredException();
274 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
276 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
279 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
280 var pathConfig
= PathConfig
.createDefault(settingsPath
);
281 final var dataPath
= pathConfig
.getDataPath();
282 final var files
= dataPath
.listFiles();
288 return Arrays
.stream(files
)
289 .filter(File
::isFile
)
291 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
292 .collect(Collectors
.toList());
295 public void checkAccountState() throws IOException
{
296 if (account
.getLastReceiveTimestamp() == 0) {
297 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
299 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
300 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
303 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
307 if (dependencies
.getAccountManager().getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
310 if (account
.getUuid() == null) {
311 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
313 updateAccountAttributes();
317 * This is used for checking a set of phone numbers for registration on Signal
319 * @param numbers The set of phone number in question
320 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
321 * @throws IOException if its unable to get the contacts to check if they're registered
323 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
324 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
326 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
327 } catch (InvalidNumberException e
) {
332 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
333 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
335 .filter(s
-> !s
.isEmpty())
336 .collect(Collectors
.toSet()));
338 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
339 final var number
= canonicalizedNumbers
.get(n
);
340 final var uuid
= registeredUsers
.get(number
);
341 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
345 public void updateAccountAttributes() throws IOException
{
346 dependencies
.getAccountManager()
347 .setAccountAttributes(account
.getEncryptedDeviceName(),
349 account
.getLocalRegistrationId(),
351 // set legacy pin only if no KBS master key is set
352 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
353 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
354 account
.getSelfUnidentifiedAccessKey(),
355 account
.isUnrestrictedUnidentifiedAccess(),
357 account
.isDiscoverableByPhoneNumber());
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),
367 public void setProfile(
368 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
369 ) throws IOException
{
370 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
371 syncHelper
.sendSyncFetchProfileMessage();
374 public void unregister() throws IOException
{
375 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
376 // If this is the master device, other users can't send messages to this number anymore.
377 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
378 dependencies
.getAccountManager().setGcmId(Optional
.absent());
380 account
.setRegistered(false);
383 public void deleteAccount() throws IOException
{
385 pinHelper
.removeRegistrationLockPin();
386 } catch (UnauthenticatedResponseException e
) {
387 logger
.warn("Failed to remove registration lock pin");
389 account
.setRegistrationLockPin(null, null);
391 dependencies
.getAccountManager().deleteAccount();
393 account
.setRegistered(false);
396 public List
<Device
> getLinkedDevices() throws IOException
{
397 var devices
= dependencies
.getAccountManager().getDevices();
398 account
.setMultiDevice(devices
.size() > 1);
399 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
400 return devices
.stream().map(d
-> {
401 String deviceName
= d
.getName();
402 if (deviceName
!= null) {
404 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
405 } catch (IOException e
) {
406 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
409 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
410 }).collect(Collectors
.toList());
413 public void removeLinkedDevices(int deviceId
) throws IOException
{
414 dependencies
.getAccountManager().removeDevice(deviceId
);
415 var devices
= dependencies
.getAccountManager().getDevices();
416 account
.setMultiDevice(devices
.size() > 1);
419 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
420 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
422 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
425 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
426 var identityKeyPair
= getIdentityKeyPair();
427 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
429 dependencies
.getAccountManager()
430 .addDevice(deviceIdentifier
,
433 Optional
.of(account
.getProfileKey().serialize()),
435 account
.setMultiDevice(true);
438 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
439 if (!account
.isMasterDevice()) {
440 throw new RuntimeException("Only master device can set a PIN");
442 if (pin
.isPresent()) {
443 final var masterKey
= account
.getPinMasterKey() != null
444 ? account
.getPinMasterKey()
445 : KeyUtils
.createMasterKey();
447 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
449 account
.setRegistrationLockPin(pin
.get(), masterKey
);
452 pinHelper
.removeRegistrationLockPin();
454 account
.setRegistrationLockPin(null, null);
458 void refreshPreKeys() throws IOException
{
459 var oneTimePreKeys
= generatePreKeys();
460 final var identityKeyPair
= getIdentityKeyPair();
461 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
463 dependencies
.getAccountManager().setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
466 private List
<PreKeyRecord
> generatePreKeys() {
467 final var offset
= account
.getPreKeyIdOffset();
469 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
470 account
.addPreKeys(records
);
475 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
476 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
478 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
479 account
.addSignedPreKey(record);
484 public Profile
getRecipientProfile(RecipientId recipientId
) {
485 return profileHelper
.getRecipientProfile(recipientId
);
488 public List
<GroupInfo
> getGroups() {
489 return account
.getGroupStore().getGroups();
492 public SendGroupMessageResults
quitGroup(
493 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
494 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
495 final var newAdmins
= resolveRecipients(groupAdmins
);
496 return groupHelper
.quitGroup(groupId
, newAdmins
);
499 public void deleteGroup(GroupId groupId
) throws IOException
{
500 groupHelper
.deleteGroup(groupId
);
503 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
504 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
505 ) throws IOException
, AttachmentInvalidException
{
506 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
509 public SendGroupMessageResults
updateGroup(
513 Set
<RecipientIdentifier
.Single
> members
,
514 Set
<RecipientIdentifier
.Single
> removeMembers
,
515 Set
<RecipientIdentifier
.Single
> admins
,
516 Set
<RecipientIdentifier
.Single
> removeAdmins
,
517 boolean resetGroupLink
,
518 GroupLinkState groupLinkState
,
519 GroupPermission addMemberPermission
,
520 GroupPermission editDetailsPermission
,
522 Integer expirationTimer
,
523 Boolean isAnnouncementGroup
524 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
525 return groupHelper
.updateGroup(groupId
,
528 members
== null ?
null : resolveRecipients(members
),
529 removeMembers
== null ?
null : resolveRecipients(removeMembers
),
530 admins
== null ?
null : resolveRecipients(admins
),
531 removeAdmins
== null ?
null : resolveRecipients(removeAdmins
),
535 editDetailsPermission
,
538 isAnnouncementGroup
);
541 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
542 GroupInviteLinkUrl inviteLinkUrl
543 ) throws IOException
, GroupLinkNotActiveException
{
544 return groupHelper
.joinGroup(inviteLinkUrl
);
547 public SendMessageResults
sendMessage(
548 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
549 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
550 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
551 long timestamp
= System
.currentTimeMillis();
552 messageBuilder
.withTimestamp(timestamp
);
553 for (final var recipient
: recipients
) {
554 if (recipient
instanceof RecipientIdentifier
.Single
) {
555 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
556 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
557 results
.put(recipient
, List
.of(result
));
558 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
559 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
560 results
.put(recipient
, List
.of(result
));
561 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
562 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
563 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
564 results
.put(recipient
, result
);
567 return new SendMessageResults(timestamp
, results
);
570 public void sendTypingMessage(
571 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
572 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
573 final var timestamp
= System
.currentTimeMillis();
574 for (var recipient
: recipients
) {
575 if (recipient
instanceof RecipientIdentifier
.Single
) {
576 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
577 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
578 sendHelper
.sendTypingMessage(message
, recipientId
);
579 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
580 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
581 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
582 sendHelper
.sendGroupTypingMessage(message
, groupId
);
587 public void sendReadReceipt(
588 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
589 ) throws IOException
, UntrustedIdentityException
{
590 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
592 System
.currentTimeMillis());
594 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
597 public void sendViewedReceipt(
598 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
599 ) throws IOException
, UntrustedIdentityException
{
600 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
602 System
.currentTimeMillis());
604 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
607 public SendMessageResults
sendMessage(
608 Message message
, Set
<RecipientIdentifier
> recipients
609 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
610 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
611 applyMessage(messageBuilder
, message
);
612 return sendMessage(messageBuilder
, recipients
);
615 private void applyMessage(
616 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
617 ) throws AttachmentInvalidException
, IOException
{
618 messageBuilder
.withBody(message
.getMessageText());
619 final var attachments
= message
.getAttachments();
620 if (attachments
!= null) {
621 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
625 public SendMessageResults
sendRemoteDeleteMessage(
626 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
627 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
628 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
629 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
630 return sendMessage(messageBuilder
, recipients
);
633 public SendMessageResults
sendMessageReaction(
636 RecipientIdentifier
.Single targetAuthor
,
637 long targetSentTimestamp
,
638 Set
<RecipientIdentifier
> recipients
639 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
640 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
641 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
643 resolveSignalServiceAddress(targetAuthorRecipientId
),
644 targetSentTimestamp
);
645 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
646 return sendMessage(messageBuilder
, recipients
);
649 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
650 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
653 return sendMessage(messageBuilder
,
654 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
655 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
656 throw new AssertionError(e
);
658 for (var recipient
: recipients
) {
659 final var recipientId
= resolveRecipient(recipient
);
660 account
.getSessionStore().deleteAllSessions(recipientId
);
665 public void setContactName(
666 RecipientIdentifier
.Single recipient
, String name
667 ) throws NotMasterDeviceException
, UnregisteredUserException
{
668 if (!account
.isMasterDevice()) {
669 throw new NotMasterDeviceException();
671 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
674 public void setContactBlocked(
675 RecipientIdentifier
.Single recipient
, boolean blocked
676 ) throws NotMasterDeviceException
, IOException
{
677 if (!account
.isMasterDevice()) {
678 throw new NotMasterDeviceException();
680 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
681 // TODO cycle our profile key
682 syncHelper
.sendBlockedList();
685 public void setGroupBlocked(
686 final GroupId groupId
, final boolean blocked
687 ) throws GroupNotFoundException
, IOException
{
688 groupHelper
.setGroupBlocked(groupId
, blocked
);
689 // TODO cycle our profile key
690 syncHelper
.sendBlockedList();
694 * Change the expiration timer for a contact
696 public void setExpirationTimer(
697 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
698 ) throws IOException
{
699 var recipientId
= resolveRecipient(recipient
);
700 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
701 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
703 sendMessage(messageBuilder
, Set
.of(recipient
));
704 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
705 throw new AssertionError(e
);
710 * Upload the sticker pack from path.
712 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
713 * @return if successful, returns the URL to install the sticker pack in the signal app
715 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
716 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
718 var messageSender
= dependencies
.getMessageSender();
720 var packKey
= KeyUtils
.createStickerUploadKey();
721 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
722 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
724 var sticker
= new Sticker(packId
, packKey
);
725 account
.getStickerStore().updateSticker(sticker
);
728 return new URI("https",
732 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
734 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
735 } catch (URISyntaxException e
) {
736 throw new AssertionError(e
);
740 public void requestAllSyncData() throws IOException
{
741 syncHelper
.requestAllSyncData();
744 private byte[] getSenderCertificate() {
747 if (account
.isPhoneNumberShared()) {
748 certificate
= dependencies
.getAccountManager().getSenderCertificate();
750 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
752 } catch (IOException e
) {
753 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
756 // TODO cache for a day
760 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
761 final var address
= resolveSignalServiceAddress(recipientId
);
762 if (!address
.getNumber().isPresent()) {
765 final var number
= address
.getNumber().get();
766 final var uuid
= getRegisteredUser(number
);
767 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
770 private UUID
getRegisteredUser(final String number
) throws IOException
{
771 final Map
<String
, UUID
> uuidMap
;
773 uuidMap
= getRegisteredUsers(Set
.of(number
));
774 } catch (NumberFormatException e
) {
775 throw new UnregisteredUserException(number
, e
);
777 final var uuid
= uuidMap
.get(number
);
779 throw new UnregisteredUserException(number
, null);
784 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
785 final Map
<String
, UUID
> registeredUsers
;
787 registeredUsers
= dependencies
.getAccountManager()
788 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
790 serviceEnvironmentConfig
.getCdsMrenclave());
791 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
792 throw new IOException(e
);
795 // Store numbers as recipients so we have the number/uuid association
796 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
798 return registeredUsers
;
801 public void sendTypingMessage(
802 TypingAction action
, Set
<RecipientIdentifier
> recipients
803 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
804 sendTypingMessage(action
.toSignalService(), recipients
);
807 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
808 Set
<HandleAction
> queuedActions
= new HashSet
<>();
809 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
810 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
811 if (actions
!= null) {
812 queuedActions
.addAll(actions
);
815 handleQueuedActions(queuedActions
);
818 private List
<HandleAction
> retryFailedReceivedMessage(
819 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
821 var envelope
= cachedMessage
.loadEnvelope();
822 if (envelope
== null) {
823 cachedMessage
.delete();
827 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
828 final var actions
= result
.first();
829 final var exception
= result
.second();
831 if (exception
instanceof UntrustedIdentityException
) {
832 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
833 // Envelope is more than a month old, cleaning up.
834 cachedMessage
.delete();
837 if (!envelope
.hasSourceUuid()) {
838 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
839 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
841 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
842 } catch (IOException ioException
) {
843 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
849 // If successful and for all other errors that are not recoverable, delete the cached message
850 cachedMessage
.delete();
854 public void receiveMessages(
857 boolean returnOnTimeout
,
858 boolean ignoreAttachments
,
859 ReceiveMessageHandler handler
860 ) throws IOException
{
861 retryFailedReceivedMessages(handler
, ignoreAttachments
);
863 Set
<HandleAction
> queuedActions
= new HashSet
<>();
865 final var signalWebSocket
= dependencies
.getSignalWebSocket();
866 signalWebSocket
.connect();
868 var hasCaughtUpWithOldMessages
= false;
870 while (!Thread
.interrupted()) {
871 SignalServiceEnvelope envelope
;
872 final CachedMessage
[] cachedMessage
= {null};
873 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
874 logger
.debug("Checking for new message from server");
876 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
877 final var recipientId
= envelope1
.hasSourceUuid()
878 ?
resolveRecipient(envelope1
.getSourceAddress())
880 // store message on disk, before acknowledging receipt to the server
881 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
883 logger
.debug("New message received from server");
884 if (result
.isPresent()) {
885 envelope
= result
.get();
887 // Received indicator that server queue is empty
888 hasCaughtUpWithOldMessages
= true;
890 handleQueuedActions(queuedActions
);
891 queuedActions
.clear();
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 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
940 for (var action
: queuedActions
) {
942 action
.execute(context
);
943 } catch (Throwable e
) {
944 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
945 Thread
.currentThread().interrupt();
947 logger
.warn("Message action failed.", e
);
952 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
953 final RecipientId recipientId
;
955 recipientId
= resolveRecipient(recipient
);
956 } catch (UnregisteredUserException e
) {
959 return contactHelper
.isContactBlocked(recipientId
);
962 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
963 return attachmentHelper
.getAttachmentFile(attachmentId
);
966 public void sendContacts() throws IOException
{
967 syncHelper
.sendContacts();
970 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
971 return account
.getContactStore().getContacts();
974 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
975 final RecipientId recipientId
;
977 recipientId
= resolveRecipient(recipientIdentifier
);
978 } catch (UnregisteredUserException e
) {
982 final var contact
= account
.getContactStore().getContact(recipientId
);
983 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
984 return contact
.getName();
987 final var profile
= getRecipientProfile(recipientId
);
988 if (profile
!= null) {
989 return profile
.getDisplayName();
995 public GroupInfo
getGroup(GroupId groupId
) {
996 return groupHelper
.getGroup(groupId
);
999 public List
<IdentityInfo
> getIdentities() {
1000 return account
.getIdentityKeyStore().getIdentities();
1003 public List
<IdentityInfo
> getIdentities(RecipientIdentifier
.Single recipient
) {
1004 IdentityInfo identity
;
1006 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1007 } catch (UnregisteredUserException e
) {
1010 return identity
== null ? List
.of() : List
.of(identity
);
1014 * Trust this the identity with this fingerprint
1016 * @param recipient username of the identity
1017 * @param fingerprint Fingerprint
1019 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1020 RecipientId recipientId
;
1022 recipientId
= resolveRecipient(recipient
);
1023 } catch (UnregisteredUserException e
) {
1026 return trustIdentity(recipientId
,
1027 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1028 TrustLevel
.TRUSTED_VERIFIED
);
1032 * Trust this the identity with this safety number
1034 * @param recipient username of the identity
1035 * @param safetyNumber Safety number
1037 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1038 RecipientId recipientId
;
1040 recipientId
= resolveRecipient(recipient
);
1041 } catch (UnregisteredUserException e
) {
1044 var address
= resolveSignalServiceAddress(recipientId
);
1045 return trustIdentity(recipientId
,
1046 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1047 TrustLevel
.TRUSTED_VERIFIED
);
1051 * Trust this the identity with this scannable safety number
1053 * @param recipient username of the identity
1054 * @param safetyNumber Scannable safety number
1056 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1057 RecipientId recipientId
;
1059 recipientId
= resolveRecipient(recipient
);
1060 } catch (UnregisteredUserException e
) {
1063 var address
= resolveSignalServiceAddress(recipientId
);
1064 return trustIdentity(recipientId
, identityKey
-> {
1065 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1067 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1068 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1071 }, TrustLevel
.TRUSTED_VERIFIED
);
1075 * Trust all keys of this identity without verification
1077 * @param recipient username of the identity
1079 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1080 RecipientId recipientId
;
1082 recipientId
= resolveRecipient(recipient
);
1083 } catch (UnregisteredUserException e
) {
1086 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1089 private boolean trustIdentity(
1090 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1092 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1093 if (identity
== null) {
1097 if (!verifier
.apply(identity
.getIdentityKey())) {
1101 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1103 var address
= resolveSignalServiceAddress(recipientId
);
1104 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1105 } catch (IOException e
) {
1106 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1112 private void handleIdentityFailure(
1113 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1115 final var identityKey
= identityFailure
.getIdentityKey();
1116 if (identityKey
!= null) {
1117 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1119 account
.getSessionStore().archiveSessions(recipientId
);
1122 // Retrieve profile to get the current identity key from the server
1123 profileHelper
.refreshRecipientProfile(recipientId
);
1127 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1128 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1129 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1132 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1133 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1134 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1137 private Fingerprint
computeSafetyNumberFingerprint(
1138 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1140 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1141 account
.getSelfAddress(),
1142 getIdentityKeyPair().getPublicKey(),
1147 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1148 return resolveSignalServiceAddress(resolveRecipient(address
));
1151 public SignalServiceAddress
resolveSignalServiceAddress(UUID uuid
) {
1152 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1155 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1156 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1157 if (address
.getUuid().isPresent()) {
1158 return address
.toSignalServiceAddress();
1161 // Address in recipient store doesn't have a uuid, this shouldn't happen
1162 // Try to retrieve the uuid from the server
1163 final var number
= address
.getNumber().get();
1165 return resolveSignalServiceAddress(getRegisteredUser(number
));
1166 } catch (IOException e
) {
1167 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1168 // Return SignalServiceAddress with unknown UUID
1169 return address
.toSignalServiceAddress();
1173 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1174 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1175 for (var number
: recipients
) {
1176 final var recipientId
= resolveRecipient(number
);
1177 recipientIds
.add(recipientId
);
1179 return recipientIds
;
1182 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1183 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1184 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1186 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1187 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1189 return getRegisteredUser(number
);
1190 } catch (IOException e
) {
1197 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1198 return account
.getRecipientStore().resolveRecipient(address
);
1201 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1202 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1206 public void close() throws IOException
{
1210 private void close(boolean closeAccount
) throws IOException
{
1211 executor
.shutdown();
1213 dependencies
.getSignalWebSocket().disconnect();
1215 if (closeAccount
&& account
!= null) {
1221 public interface ReceiveMessageHandler
{
1223 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);