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
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
62 import org
.slf4j
.Logger
;
63 import org
.slf4j
.LoggerFactory
;
64 import org
.whispersystems
.libsignal
.IdentityKey
;
65 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
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
.state
.PreKeyRecord
;
72 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
73 import org
.whispersystems
.libsignal
.util
.Pair
;
74 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
75 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
76 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
77 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
78 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
79 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
80 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
81 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
82 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
83 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
84 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
85 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
86 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
87 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
88 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
89 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
90 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
91 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
92 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
93 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
94 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
95 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
97 import java
.io
.Closeable
;
99 import java
.io
.IOException
;
101 import java
.net
.URISyntaxException
;
102 import java
.net
.URLEncoder
;
103 import java
.nio
.charset
.StandardCharsets
;
104 import java
.security
.SignatureException
;
105 import java
.util
.Arrays
;
106 import java
.util
.Collection
;
107 import java
.util
.Date
;
108 import java
.util
.HashMap
;
109 import java
.util
.HashSet
;
110 import java
.util
.List
;
111 import java
.util
.Map
;
112 import java
.util
.Set
;
113 import java
.util
.UUID
;
114 import java
.util
.concurrent
.ExecutorService
;
115 import java
.util
.concurrent
.Executors
;
116 import java
.util
.concurrent
.TimeUnit
;
117 import java
.util
.concurrent
.TimeoutException
;
118 import java
.util
.concurrent
.locks
.ReentrantLock
;
119 import java
.util
.function
.Function
;
120 import java
.util
.stream
.Collectors
;
122 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
124 public class Manager
implements Closeable
{
126 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
128 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
129 private final SignalDependencies dependencies
;
131 private SignalAccount account
;
133 private final ExecutorService executor
= Executors
.newCachedThreadPool();
135 private final ProfileHelper profileHelper
;
136 private final PinHelper pinHelper
;
137 private final SendHelper sendHelper
;
138 private final SyncHelper syncHelper
;
139 private final AttachmentHelper attachmentHelper
;
140 private final GroupHelper groupHelper
;
141 private final ContactHelper contactHelper
;
142 private final IncomingMessageHandler incomingMessageHandler
;
144 private final Context context
;
147 SignalAccount account
,
148 PathConfig pathConfig
,
149 ServiceEnvironmentConfig serviceEnvironmentConfig
,
152 this.account
= account
;
153 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
155 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
156 account
.getUsername(),
157 account
.getPassword(),
158 account
.getDeviceId());
159 final var sessionLock
= new SignalSessionLock() {
160 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
163 public Lock
acquire() {
165 return LEGACY_LOCK
::unlock
;
168 this.dependencies
= new SignalDependencies(account
.getSelfAddress(),
169 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 dependencies
::getProfileService
,
191 dependencies
::getMessageReceiver
,
192 this::resolveSignalServiceAddress
);
193 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
194 this::getRecipientProfile
,
195 account
::getSelfRecipientId
,
196 dependencies
.getGroupsV2Operations(),
197 dependencies
.getGroupsV2Api(),
198 this::resolveSignalServiceAddress
);
199 this.sendHelper
= new SendHelper(account
,
201 unidentifiedAccessHelper
,
202 this::resolveSignalServiceAddress
,
203 account
.getRecipientStore(),
204 this::handleIdentityFailure
,
206 this::refreshRegisteredUser
);
207 this.groupHelper
= new GroupHelper(account
,
213 this::resolveSignalServiceAddress
,
214 account
.getRecipientStore());
215 this.contactHelper
= new ContactHelper(account
);
216 this.syncHelper
= new SyncHelper(account
,
221 this::resolveSignalServiceAddress
);
223 this.context
= new Context(account
,
224 dependencies
.getAccountManager(),
225 dependencies
.getMessageReceiver(),
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 private IdentityKeyPair
getIdentityKeyPair() {
253 return account
.getIdentityKeyPair();
256 public int getDeviceId() {
257 return account
.getDeviceId();
260 public static Manager
init(
263 ServiceEnvironment serviceEnvironment
,
265 final TrustNewIdentity trustNewIdentity
266 ) throws IOException
, NotRegisteredException
{
267 var pathConfig
= PathConfig
.createDefault(settingsPath
);
269 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
270 throw new NotRegisteredException();
273 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true, trustNewIdentity
);
275 if (!account
.isRegistered()) {
276 throw new NotRegisteredException();
279 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
281 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
284 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
285 var pathConfig
= PathConfig
.createDefault(settingsPath
);
286 final var dataPath
= pathConfig
.getDataPath();
287 final var files
= dataPath
.listFiles();
293 return Arrays
.stream(files
)
294 .filter(File
::isFile
)
296 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
297 .collect(Collectors
.toList());
300 public void checkAccountState() throws IOException
{
301 if (account
.getLastReceiveTimestamp() == 0) {
302 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
304 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
305 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
308 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
312 if (dependencies
.getAccountManager().getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
315 if (account
.getUuid() == null) {
316 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
318 updateAccountAttributes();
322 * This is used for checking a set of phone numbers for registration on Signal
324 * @param numbers The set of phone number in question
325 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
326 * @throws IOException if its unable to get the contacts to check if they're registered
328 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
329 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
331 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
332 } catch (InvalidNumberException e
) {
337 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
338 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
340 .filter(s
-> !s
.isEmpty())
341 .collect(Collectors
.toSet()));
343 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
344 final var number
= canonicalizedNumbers
.get(n
);
345 final var uuid
= registeredUsers
.get(number
);
346 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
350 public void updateAccountAttributes() throws IOException
{
351 dependencies
.getAccountManager()
352 .setAccountAttributes(account
.getEncryptedDeviceName(),
354 account
.getLocalRegistrationId(),
356 // set legacy pin only if no KBS master key is set
357 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
358 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
359 account
.getSelfUnidentifiedAccessKey(),
360 account
.isUnrestrictedUnidentifiedAccess(),
362 account
.isDiscoverableByPhoneNumber());
366 * @param givenName if null, the previous givenName will be kept
367 * @param familyName if null, the previous familyName will be kept
368 * @param about if null, the previous about text will be kept
369 * @param aboutEmoji if null, the previous about emoji will be kept
370 * @param avatar if avatar is null the image from the local avatar store is used (if present),
372 public void setProfile(
373 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
374 ) throws IOException
{
375 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
376 syncHelper
.sendSyncFetchProfileMessage();
379 public void unregister() throws IOException
{
380 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
381 // If this is the master device, other users can't send messages to this number anymore.
382 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
383 dependencies
.getAccountManager().setGcmId(Optional
.absent());
385 account
.setRegistered(false);
388 public void deleteAccount() throws IOException
{
389 dependencies
.getAccountManager().deleteAccount();
391 account
.setRegistered(false);
394 public List
<Device
> getLinkedDevices() throws IOException
{
395 var devices
= dependencies
.getAccountManager().getDevices();
396 account
.setMultiDevice(devices
.size() > 1);
397 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
398 return devices
.stream().map(d
-> {
399 String deviceName
= d
.getName();
400 if (deviceName
!= null) {
402 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
403 } catch (IOException e
) {
404 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
407 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
408 }).collect(Collectors
.toList());
411 public void removeLinkedDevices(int deviceId
) throws IOException
{
412 dependencies
.getAccountManager().removeDevice(deviceId
);
413 var devices
= dependencies
.getAccountManager().getDevices();
414 account
.setMultiDevice(devices
.size() > 1);
417 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
418 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
420 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
423 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
424 var identityKeyPair
= getIdentityKeyPair();
425 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
427 dependencies
.getAccountManager()
428 .addDevice(deviceIdentifier
,
431 Optional
.of(account
.getProfileKey().serialize()),
433 account
.setMultiDevice(true);
436 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
437 if (!account
.isMasterDevice()) {
438 throw new RuntimeException("Only master device can set a PIN");
440 if (pin
.isPresent()) {
441 final var masterKey
= account
.getPinMasterKey() != null
442 ? account
.getPinMasterKey()
443 : KeyUtils
.createMasterKey();
445 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
447 account
.setRegistrationLockPin(pin
.get(), masterKey
);
450 pinHelper
.removeRegistrationLockPin();
452 account
.setRegistrationLockPin(null, null);
456 void refreshPreKeys() throws IOException
{
457 var oneTimePreKeys
= generatePreKeys();
458 final var identityKeyPair
= getIdentityKeyPair();
459 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
461 dependencies
.getAccountManager().setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
464 private List
<PreKeyRecord
> generatePreKeys() {
465 final var offset
= account
.getPreKeyIdOffset();
467 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
468 account
.addPreKeys(records
);
473 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
474 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
476 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
477 account
.addSignedPreKey(record);
482 public Profile
getRecipientProfile(RecipientId recipientId
) {
483 return profileHelper
.getRecipientProfile(recipientId
);
486 public List
<GroupInfo
> getGroups() {
487 return account
.getGroupStore().getGroups();
490 public SendGroupMessageResults
quitGroup(
491 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
492 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
493 final var newAdmins
= resolveRecipients(groupAdmins
);
494 return groupHelper
.quitGroup(groupId
, newAdmins
);
497 public void deleteGroup(GroupId groupId
) throws IOException
{
498 groupHelper
.deleteGroup(groupId
);
501 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
502 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
503 ) throws IOException
, AttachmentInvalidException
{
504 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
507 public SendGroupMessageResults
updateGroup(
511 Set
<RecipientIdentifier
.Single
> members
,
512 Set
<RecipientIdentifier
.Single
> removeMembers
,
513 Set
<RecipientIdentifier
.Single
> admins
,
514 Set
<RecipientIdentifier
.Single
> removeAdmins
,
515 boolean resetGroupLink
,
516 GroupLinkState groupLinkState
,
517 GroupPermission addMemberPermission
,
518 GroupPermission editDetailsPermission
,
520 Integer expirationTimer
,
521 Boolean isAnnouncementGroup
522 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
523 return groupHelper
.updateGroup(groupId
,
526 members
== null ?
null : resolveRecipients(members
),
527 removeMembers
== null ?
null : resolveRecipients(removeMembers
),
528 admins
== null ?
null : resolveRecipients(admins
),
529 removeAdmins
== null ?
null : resolveRecipients(removeAdmins
),
533 editDetailsPermission
,
536 isAnnouncementGroup
);
539 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
540 GroupInviteLinkUrl inviteLinkUrl
541 ) throws IOException
, GroupLinkNotActiveException
{
542 return groupHelper
.joinGroup(inviteLinkUrl
);
545 public SendMessageResults
sendMessage(
546 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
547 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
548 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
549 long timestamp
= System
.currentTimeMillis();
550 messageBuilder
.withTimestamp(timestamp
);
551 for (final var recipient
: recipients
) {
552 if (recipient
instanceof RecipientIdentifier
.Single
) {
553 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
554 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
555 results
.put(recipient
, List
.of(result
));
556 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
557 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
558 results
.put(recipient
, List
.of(result
));
559 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
560 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
561 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
562 results
.put(recipient
, result
);
565 return new SendMessageResults(timestamp
, results
);
568 public void sendTypingMessage(
569 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
570 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
571 final var timestamp
= System
.currentTimeMillis();
572 for (var recipient
: recipients
) {
573 if (recipient
instanceof RecipientIdentifier
.Single
) {
574 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
575 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
576 sendHelper
.sendTypingMessage(message
, recipientId
);
577 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
578 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
579 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
580 sendHelper
.sendGroupTypingMessage(message
, groupId
);
585 public void sendReadReceipt(
586 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
587 ) throws IOException
, UntrustedIdentityException
{
588 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
590 System
.currentTimeMillis());
592 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
595 public void sendViewedReceipt(
596 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
597 ) throws IOException
, UntrustedIdentityException
{
598 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
600 System
.currentTimeMillis());
602 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
605 public SendMessageResults
sendMessage(
606 Message message
, Set
<RecipientIdentifier
> recipients
607 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
608 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
609 applyMessage(messageBuilder
, message
);
610 return sendMessage(messageBuilder
, recipients
);
613 private void applyMessage(
614 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
615 ) throws AttachmentInvalidException
, IOException
{
616 messageBuilder
.withBody(message
.getMessageText());
617 final var attachments
= message
.getAttachments();
618 if (attachments
!= null) {
619 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
623 public SendMessageResults
sendRemoteDeleteMessage(
624 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
625 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
626 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
627 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
628 return sendMessage(messageBuilder
, recipients
);
631 public SendMessageResults
sendMessageReaction(
634 RecipientIdentifier
.Single targetAuthor
,
635 long targetSentTimestamp
,
636 Set
<RecipientIdentifier
> recipients
637 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
638 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
639 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
641 resolveSignalServiceAddress(targetAuthorRecipientId
),
642 targetSentTimestamp
);
643 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
644 return sendMessage(messageBuilder
, recipients
);
647 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
648 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
651 return sendMessage(messageBuilder
,
652 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
653 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
654 throw new AssertionError(e
);
656 for (var recipient
: recipients
) {
657 final var recipientId
= resolveRecipient(recipient
);
658 account
.getSessionStore().deleteAllSessions(recipientId
);
663 public void setContactName(
664 RecipientIdentifier
.Single recipient
, String name
665 ) throws NotMasterDeviceException
, UnregisteredUserException
{
666 if (!account
.isMasterDevice()) {
667 throw new NotMasterDeviceException();
669 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
672 public void setContactBlocked(
673 RecipientIdentifier
.Single recipient
, boolean blocked
674 ) throws NotMasterDeviceException
, IOException
{
675 if (!account
.isMasterDevice()) {
676 throw new NotMasterDeviceException();
678 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
679 // TODO cycle our profile key
680 syncHelper
.sendBlockedList();
683 public void setGroupBlocked(
684 final GroupId groupId
, final boolean blocked
685 ) throws GroupNotFoundException
, IOException
{
686 groupHelper
.setGroupBlocked(groupId
, blocked
);
687 // TODO cycle our profile key
688 syncHelper
.sendBlockedList();
692 * Change the expiration timer for a contact
694 public void setExpirationTimer(
695 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
696 ) throws IOException
{
697 var recipientId
= resolveRecipient(recipient
);
698 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
699 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
701 sendMessage(messageBuilder
, Set
.of(recipient
));
702 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
703 throw new AssertionError(e
);
708 * Upload the sticker pack from path.
710 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
711 * @return if successful, returns the URL to install the sticker pack in the signal app
713 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
714 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
716 var messageSender
= dependencies
.getMessageSender();
718 var packKey
= KeyUtils
.createStickerUploadKey();
719 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
720 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
722 var sticker
= new Sticker(packId
, packKey
);
723 account
.getStickerStore().updateSticker(sticker
);
726 return new URI("https",
730 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
732 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
733 } catch (URISyntaxException e
) {
734 throw new AssertionError(e
);
738 public void requestAllSyncData() throws IOException
{
739 syncHelper
.requestAllSyncData();
742 private byte[] getSenderCertificate() {
745 if (account
.isPhoneNumberShared()) {
746 certificate
= dependencies
.getAccountManager().getSenderCertificate();
748 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
750 } catch (IOException e
) {
751 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
754 // TODO cache for a day
758 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
759 final var address
= resolveSignalServiceAddress(recipientId
);
760 if (!address
.getNumber().isPresent()) {
763 final var number
= address
.getNumber().get();
764 final var uuid
= getRegisteredUser(number
);
765 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
768 private UUID
getRegisteredUser(final String number
) throws IOException
{
769 final Map
<String
, UUID
> uuidMap
;
771 uuidMap
= getRegisteredUsers(Set
.of(number
));
772 } catch (NumberFormatException e
) {
773 throw new UnregisteredUserException(number
, e
);
775 final var uuid
= uuidMap
.get(number
);
777 throw new UnregisteredUserException(number
, null);
782 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
783 final Map
<String
, UUID
> registeredUsers
;
785 registeredUsers
= dependencies
.getAccountManager()
786 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
788 serviceEnvironmentConfig
.getCdsMrenclave());
789 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
790 throw new IOException(e
);
793 // Store numbers as recipients so we have the number/uuid association
794 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
796 return registeredUsers
;
799 public void sendTypingMessage(
800 TypingAction action
, Set
<RecipientIdentifier
> recipients
801 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
802 sendTypingMessage(action
.toSignalService(), recipients
);
805 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
806 Set
<HandleAction
> queuedActions
= new HashSet
<>();
807 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
808 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
809 if (actions
!= null) {
810 queuedActions
.addAll(actions
);
813 handleQueuedActions(queuedActions
);
816 private List
<HandleAction
> retryFailedReceivedMessage(
817 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
819 var envelope
= cachedMessage
.loadEnvelope();
820 if (envelope
== null) {
823 SignalServiceContent content
= null;
824 List
<HandleAction
> actions
= null;
825 if (!envelope
.isReceipt()) {
827 content
= dependencies
.getCipher().decrypt(envelope
);
828 } catch (ProtocolUntrustedIdentityException e
) {
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
= e
.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());
844 } catch (Exception er
) {
845 // All other errors are not recoverable, so delete the cached message
846 cachedMessage
.delete();
849 actions
= incomingMessageHandler
.handleMessage(envelope
, content
, ignoreAttachments
);
851 handler
.handleMessage(envelope
, content
, null);
852 cachedMessage
.delete();
856 public void receiveMessages(
859 boolean returnOnTimeout
,
860 boolean ignoreAttachments
,
861 ReceiveMessageHandler handler
862 ) throws IOException
{
863 retryFailedReceivedMessages(handler
, ignoreAttachments
);
865 Set
<HandleAction
> queuedActions
= new HashSet
<>();
867 final var signalWebSocket
= dependencies
.getSignalWebSocket();
868 signalWebSocket
.connect();
870 var hasCaughtUpWithOldMessages
= false;
872 while (!Thread
.interrupted()) {
873 SignalServiceEnvelope envelope
;
874 final CachedMessage
[] cachedMessage
= {null};
875 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
876 logger
.debug("Checking for new message from server");
878 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
879 final var recipientId
= envelope1
.hasSourceUuid()
880 ?
resolveRecipient(envelope1
.getSourceAddress())
882 // store message on disk, before acknowledging receipt to the server
883 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
885 logger
.debug("New message received from server");
886 if (result
.isPresent()) {
887 envelope
= result
.get();
889 // Received indicator that server queue is empty
890 hasCaughtUpWithOldMessages
= true;
892 handleQueuedActions(queuedActions
);
893 queuedActions
.clear();
895 // Continue to wait another timeout for new messages
898 } catch (AssertionError e
) {
899 if (e
.getCause() instanceof InterruptedException
) {
900 Thread
.currentThread().interrupt();
905 } catch (WebSocketUnavailableException e
) {
906 logger
.debug("Pipe unexpectedly unavailable, connecting");
907 signalWebSocket
.connect();
909 } catch (TimeoutException e
) {
910 if (returnOnTimeout
) return;
914 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
915 queuedActions
.addAll(result
.first());
916 final var exception
= result
.second();
918 if (hasCaughtUpWithOldMessages
) {
919 handleQueuedActions(queuedActions
);
921 if (cachedMessage
[0] != null) {
922 if (exception
instanceof UntrustedIdentityException
) {
923 final var address
= ((UntrustedIdentityException
) exception
).getSender();
924 final var recipientId
= resolveRecipient(address
);
925 if (!envelope
.hasSourceUuid()) {
927 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
928 } catch (IOException ioException
) {
929 logger
.warn("Failed to move cached message to recipient folder: {}",
930 ioException
.getMessage());
934 cachedMessage
[0].delete();
938 handleQueuedActions(queuedActions
);
941 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
942 for (var action
: queuedActions
) {
944 action
.execute(context
);
945 } catch (Throwable e
) {
946 if (e
instanceof AssertionError
&& e
.getCause() instanceof InterruptedException
) {
947 Thread
.currentThread().interrupt();
949 logger
.warn("Message action failed.", e
);
954 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
955 final RecipientId recipientId
;
957 recipientId
= resolveRecipient(recipient
);
958 } catch (UnregisteredUserException e
) {
961 return contactHelper
.isContactBlocked(recipientId
);
964 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
965 return attachmentHelper
.getAttachmentFile(attachmentId
);
968 public void sendContacts() throws IOException
{
969 syncHelper
.sendContacts();
972 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
973 return account
.getContactStore().getContacts();
976 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
977 final RecipientId recipientId
;
979 recipientId
= resolveRecipient(recipientIdentifier
);
980 } catch (UnregisteredUserException e
) {
984 final var contact
= account
.getContactStore().getContact(recipientId
);
985 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
986 return contact
.getName();
989 final var profile
= getRecipientProfile(recipientId
);
990 if (profile
!= null) {
991 return profile
.getDisplayName();
997 public GroupInfo
getGroup(GroupId groupId
) {
998 return groupHelper
.getGroup(groupId
);
1001 public List
<IdentityInfo
> getIdentities() {
1002 return account
.getIdentityKeyStore().getIdentities();
1005 public List
<IdentityInfo
> getIdentities(RecipientIdentifier
.Single recipient
) {
1006 IdentityInfo identity
;
1008 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1009 } catch (UnregisteredUserException e
) {
1012 return identity
== null ? List
.of() : List
.of(identity
);
1016 * Trust this the identity with this fingerprint
1018 * @param recipient username of the identity
1019 * @param fingerprint Fingerprint
1021 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1022 RecipientId recipientId
;
1024 recipientId
= resolveRecipient(recipient
);
1025 } catch (UnregisteredUserException e
) {
1028 return trustIdentity(recipientId
,
1029 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1030 TrustLevel
.TRUSTED_VERIFIED
);
1034 * Trust this the identity with this safety number
1036 * @param recipient username of the identity
1037 * @param safetyNumber Safety number
1039 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1040 RecipientId recipientId
;
1042 recipientId
= resolveRecipient(recipient
);
1043 } catch (UnregisteredUserException e
) {
1046 var address
= resolveSignalServiceAddress(recipientId
);
1047 return trustIdentity(recipientId
,
1048 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1049 TrustLevel
.TRUSTED_VERIFIED
);
1053 * Trust this the identity with this scannable safety number
1055 * @param recipient username of the identity
1056 * @param safetyNumber Scannable safety number
1058 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1059 RecipientId recipientId
;
1061 recipientId
= resolveRecipient(recipient
);
1062 } catch (UnregisteredUserException e
) {
1065 var address
= resolveSignalServiceAddress(recipientId
);
1066 return trustIdentity(recipientId
, identityKey
-> {
1067 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1069 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1070 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1073 }, TrustLevel
.TRUSTED_VERIFIED
);
1077 * Trust all keys of this identity without verification
1079 * @param recipient username of the identity
1081 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1082 RecipientId recipientId
;
1084 recipientId
= resolveRecipient(recipient
);
1085 } catch (UnregisteredUserException e
) {
1088 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1091 private boolean trustIdentity(
1092 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1094 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1095 if (identity
== null) {
1099 if (!verifier
.apply(identity
.getIdentityKey())) {
1103 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1105 var address
= resolveSignalServiceAddress(recipientId
);
1106 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1107 } catch (IOException e
) {
1108 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1114 private void handleIdentityFailure(
1115 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1117 final var identityKey
= identityFailure
.getIdentityKey();
1118 if (identityKey
!= null) {
1119 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1121 account
.getSessionStore().archiveSessions(recipientId
);
1124 // Retrieve profile to get the current identity key from the server
1125 profileHelper
.refreshRecipientProfile(recipientId
);
1129 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1130 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1131 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1134 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1135 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1136 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1139 private Fingerprint
computeSafetyNumberFingerprint(
1140 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1142 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1143 account
.getSelfAddress(),
1144 getIdentityKeyPair().getPublicKey(),
1149 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1150 if (address
.matches(account
.getSelfAddress())) {
1151 return account
.getSelfAddress();
1154 return resolveSignalServiceAddress(resolveRecipient(address
));
1157 public SignalServiceAddress
resolveSignalServiceAddress(UUID uuid
) {
1158 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1161 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1162 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1163 if (address
.getUuid().isPresent()) {
1164 return address
.toSignalServiceAddress();
1167 // Address in recipient store doesn't have a uuid, this shouldn't happen
1168 // Try to retrieve the uuid from the server
1169 final var number
= address
.getNumber().get();
1171 return resolveSignalServiceAddress(getRegisteredUser(number
));
1172 } catch (IOException e
) {
1173 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1174 // Return SignalServiceAddress with unknown UUID
1175 return address
.toSignalServiceAddress();
1179 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1180 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1181 for (var number
: recipients
) {
1182 final var recipientId
= resolveRecipient(number
);
1183 recipientIds
.add(recipientId
);
1185 return recipientIds
;
1188 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1189 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1190 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1192 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1193 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1195 return getRegisteredUser(number
);
1196 } catch (IOException e
) {
1203 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1204 return account
.getRecipientStore().resolveRecipient(address
);
1207 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1208 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1212 public void close() throws IOException
{
1216 private void close(boolean closeAccount
) throws IOException
{
1217 executor
.shutdown();
1219 dependencies
.getSignalWebSocket().disconnect();
1221 if (closeAccount
&& account
!= null) {
1227 public interface ReceiveMessageHandler
{
1229 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);