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
;
144 private boolean hasCaughtUpWithOldMessages
= false;
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(serviceEnvironmentConfig
,
171 account
.getSignalProtocolStore(),
174 final var avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
175 final var attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
176 final var stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
178 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
179 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
180 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
181 account
.getProfileStore()::getProfileKey
,
182 this::getRecipientProfile
,
183 this::getSenderCertificate
);
184 this.profileHelper
= new ProfileHelper(account
,
187 account
.getProfileStore()::getProfileKey
,
188 unidentifiedAccessHelper
::getAccessFor
,
189 this::resolveSignalServiceAddress
);
190 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
191 this::getRecipientProfile
,
192 account
::getSelfRecipientId
,
193 dependencies
.getGroupsV2Operations(),
194 dependencies
.getGroupsV2Api(),
195 this::resolveSignalServiceAddress
);
196 this.sendHelper
= new SendHelper(account
,
198 unidentifiedAccessHelper
,
199 this::resolveSignalServiceAddress
,
200 account
.getRecipientStore(),
201 this::handleIdentityFailure
,
203 this::refreshRegisteredUser
);
204 this.groupHelper
= new GroupHelper(account
,
210 this::resolveSignalServiceAddress
,
211 account
.getRecipientStore());
212 this.contactHelper
= new ContactHelper(account
);
213 this.syncHelper
= new SyncHelper(account
,
218 this::resolveSignalServiceAddress
);
220 this.context
= new Context(account
,
227 var jobExecutor
= new JobExecutor(context
);
229 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
231 account
.getRecipientStore(),
232 this::resolveSignalServiceAddress
,
240 public String
getUsername() {
241 return account
.getUsername();
244 public RecipientId
getSelfRecipientId() {
245 return account
.getSelfRecipientId();
248 private IdentityKeyPair
getIdentityKeyPair() {
249 return account
.getIdentityKeyPair();
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 if (dependencies
.getAccountManager().getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
311 if (account
.getUuid() == null) {
312 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
314 updateAccountAttributes(null);
318 * This is used for checking a set of phone numbers for registration on Signal
320 * @param numbers The set of phone number in question
321 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
322 * @throws IOException if its unable to get the contacts to check if they're registered
324 public Map
<String
, Pair
<String
, UUID
>> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
325 Map
<String
, String
> canonicalizedNumbers
= numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
327 return PhoneNumberFormatter
.formatNumber(n
, account
.getUsername());
328 } catch (InvalidNumberException e
) {
333 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
334 var registeredUsers
= getRegisteredUsers(canonicalizedNumbers
.values()
336 .filter(s
-> !s
.isEmpty())
337 .collect(Collectors
.toSet()));
339 return numbers
.stream().collect(Collectors
.toMap(n
-> n
, n
-> {
340 final var number
= canonicalizedNumbers
.get(n
);
341 final var uuid
= registeredUsers
.get(number
);
342 return new Pair
<>(number
.isEmpty() ?
null : number
, uuid
);
346 public void updateAccountAttributes(String deviceName
) throws IOException
{
347 final String encryptedDeviceName
;
348 if (deviceName
== null) {
349 encryptedDeviceName
= account
.getEncryptedDeviceName();
351 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
352 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
353 account
.setEncryptedDeviceName(encryptedDeviceName
);
355 dependencies
.getAccountManager()
356 .setAccountAttributes(encryptedDeviceName
,
358 account
.getLocalRegistrationId(),
361 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
362 account
.getSelfUnidentifiedAccessKey(),
363 account
.isUnrestrictedUnidentifiedAccess(),
365 account
.isDiscoverableByPhoneNumber());
369 * @param givenName if null, the previous givenName will be kept
370 * @param familyName if null, the previous familyName will be kept
371 * @param about if null, the previous about text will be kept
372 * @param aboutEmoji if null, the previous about emoji will be kept
373 * @param avatar if avatar is null the image from the local avatar store is used (if present),
375 public void setProfile(
376 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
377 ) throws IOException
{
378 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
379 syncHelper
.sendSyncFetchProfileMessage();
382 public void unregister() throws IOException
{
383 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
384 // If this is the master device, other users can't send messages to this number anymore.
385 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
386 dependencies
.getAccountManager().setGcmId(Optional
.absent());
388 account
.setRegistered(false);
391 public void deleteAccount() throws IOException
{
393 pinHelper
.removeRegistrationLockPin();
394 } catch (UnauthenticatedResponseException e
) {
395 logger
.warn("Failed to remove registration lock pin");
397 account
.setRegistrationLockPin(null, null);
399 dependencies
.getAccountManager().deleteAccount();
401 account
.setRegistered(false);
404 public List
<Device
> getLinkedDevices() throws IOException
{
405 var devices
= dependencies
.getAccountManager().getDevices();
406 account
.setMultiDevice(devices
.size() > 1);
407 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
408 return devices
.stream().map(d
-> {
409 String deviceName
= d
.getName();
410 if (deviceName
!= null) {
412 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
413 } catch (IOException e
) {
414 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
417 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
418 }).collect(Collectors
.toList());
421 public void removeLinkedDevices(int deviceId
) throws IOException
{
422 dependencies
.getAccountManager().removeDevice(deviceId
);
423 var devices
= dependencies
.getAccountManager().getDevices();
424 account
.setMultiDevice(devices
.size() > 1);
427 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
428 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
430 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
433 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
434 var identityKeyPair
= getIdentityKeyPair();
435 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
437 dependencies
.getAccountManager()
438 .addDevice(deviceIdentifier
,
441 Optional
.of(account
.getProfileKey().serialize()),
443 account
.setMultiDevice(true);
446 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
447 if (!account
.isMasterDevice()) {
448 throw new RuntimeException("Only master device can set a PIN");
450 if (pin
.isPresent()) {
451 final var masterKey
= account
.getPinMasterKey() != null
452 ? account
.getPinMasterKey()
453 : KeyUtils
.createMasterKey();
455 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
457 account
.setRegistrationLockPin(pin
.get(), masterKey
);
460 pinHelper
.removeRegistrationLockPin();
462 account
.setRegistrationLockPin(null, null);
466 void refreshPreKeys() throws IOException
{
467 var oneTimePreKeys
= generatePreKeys();
468 final var identityKeyPair
= getIdentityKeyPair();
469 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
471 dependencies
.getAccountManager().setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
474 private List
<PreKeyRecord
> generatePreKeys() {
475 final var offset
= account
.getPreKeyIdOffset();
477 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
478 account
.addPreKeys(records
);
483 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
484 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
486 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
487 account
.addSignedPreKey(record);
492 public Profile
getRecipientProfile(RecipientId recipientId
) {
493 return profileHelper
.getRecipientProfile(recipientId
);
496 public List
<GroupInfo
> getGroups() {
497 return account
.getGroupStore().getGroups();
500 public SendGroupMessageResults
quitGroup(
501 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
502 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
503 final var newAdmins
= resolveRecipients(groupAdmins
);
504 return groupHelper
.quitGroup(groupId
, newAdmins
);
507 public void deleteGroup(GroupId groupId
) throws IOException
{
508 groupHelper
.deleteGroup(groupId
);
511 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
512 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
513 ) throws IOException
, AttachmentInvalidException
{
514 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
517 public SendGroupMessageResults
updateGroup(
521 Set
<RecipientIdentifier
.Single
> members
,
522 Set
<RecipientIdentifier
.Single
> removeMembers
,
523 Set
<RecipientIdentifier
.Single
> admins
,
524 Set
<RecipientIdentifier
.Single
> removeAdmins
,
525 boolean resetGroupLink
,
526 GroupLinkState groupLinkState
,
527 GroupPermission addMemberPermission
,
528 GroupPermission editDetailsPermission
,
530 Integer expirationTimer
,
531 Boolean isAnnouncementGroup
532 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
533 return groupHelper
.updateGroup(groupId
,
536 members
== null ?
null : resolveRecipients(members
),
537 removeMembers
== null ?
null : resolveRecipients(removeMembers
),
538 admins
== null ?
null : resolveRecipients(admins
),
539 removeAdmins
== null ?
null : resolveRecipients(removeAdmins
),
543 editDetailsPermission
,
546 isAnnouncementGroup
);
549 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
550 GroupInviteLinkUrl inviteLinkUrl
551 ) throws IOException
, GroupLinkNotActiveException
{
552 return groupHelper
.joinGroup(inviteLinkUrl
);
555 public SendMessageResults
sendMessage(
556 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
557 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
558 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
559 long timestamp
= System
.currentTimeMillis();
560 messageBuilder
.withTimestamp(timestamp
);
561 for (final var recipient
: recipients
) {
562 if (recipient
instanceof RecipientIdentifier
.Single
) {
563 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
564 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
565 results
.put(recipient
, List
.of(result
));
566 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
567 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
568 results
.put(recipient
, List
.of(result
));
569 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
570 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
571 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
572 results
.put(recipient
, result
);
575 return new SendMessageResults(timestamp
, results
);
578 public void sendTypingMessage(
579 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
580 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
581 final var timestamp
= System
.currentTimeMillis();
582 for (var recipient
: recipients
) {
583 if (recipient
instanceof RecipientIdentifier
.Single
) {
584 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
585 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
586 sendHelper
.sendTypingMessage(message
, recipientId
);
587 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
588 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
589 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
590 sendHelper
.sendGroupTypingMessage(message
, groupId
);
595 public void sendReadReceipt(
596 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
597 ) throws IOException
, UntrustedIdentityException
{
598 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
600 System
.currentTimeMillis());
602 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
605 public void sendViewedReceipt(
606 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
607 ) throws IOException
, UntrustedIdentityException
{
608 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
610 System
.currentTimeMillis());
612 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
615 public SendMessageResults
sendMessage(
616 Message message
, Set
<RecipientIdentifier
> recipients
617 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
618 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
619 applyMessage(messageBuilder
, message
);
620 return sendMessage(messageBuilder
, recipients
);
623 private void applyMessage(
624 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
625 ) throws AttachmentInvalidException
, IOException
{
626 messageBuilder
.withBody(message
.getMessageText());
627 final var attachments
= message
.getAttachments();
628 if (attachments
!= null) {
629 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
633 public SendMessageResults
sendRemoteDeleteMessage(
634 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
635 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
636 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
637 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
638 return sendMessage(messageBuilder
, recipients
);
641 public SendMessageResults
sendMessageReaction(
644 RecipientIdentifier
.Single targetAuthor
,
645 long targetSentTimestamp
,
646 Set
<RecipientIdentifier
> recipients
647 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
648 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
649 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
651 resolveSignalServiceAddress(targetAuthorRecipientId
),
652 targetSentTimestamp
);
653 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
654 return sendMessage(messageBuilder
, recipients
);
657 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
658 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
661 return sendMessage(messageBuilder
,
662 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
663 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
664 throw new AssertionError(e
);
666 for (var recipient
: recipients
) {
667 final var recipientId
= resolveRecipient(recipient
);
668 account
.getSessionStore().deleteAllSessions(recipientId
);
673 public void setContactName(
674 RecipientIdentifier
.Single recipient
, String name
675 ) throws NotMasterDeviceException
, UnregisteredUserException
{
676 if (!account
.isMasterDevice()) {
677 throw new NotMasterDeviceException();
679 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
682 public void setContactBlocked(
683 RecipientIdentifier
.Single recipient
, boolean blocked
684 ) throws NotMasterDeviceException
, IOException
{
685 if (!account
.isMasterDevice()) {
686 throw new NotMasterDeviceException();
688 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
689 // TODO cycle our profile key
690 syncHelper
.sendBlockedList();
693 public void setGroupBlocked(
694 final GroupId groupId
, final boolean blocked
695 ) throws GroupNotFoundException
, IOException
{
696 groupHelper
.setGroupBlocked(groupId
, blocked
);
697 // TODO cycle our profile key
698 syncHelper
.sendBlockedList();
702 * Change the expiration timer for a contact
704 public void setExpirationTimer(
705 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
706 ) throws IOException
{
707 var recipientId
= resolveRecipient(recipient
);
708 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
709 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
711 sendMessage(messageBuilder
, Set
.of(recipient
));
712 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
713 throw new AssertionError(e
);
718 * Upload the sticker pack from path.
720 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
721 * @return if successful, returns the URL to install the sticker pack in the signal app
723 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
724 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
726 var messageSender
= dependencies
.getMessageSender();
728 var packKey
= KeyUtils
.createStickerUploadKey();
729 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
730 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
732 var sticker
= new Sticker(packId
, packKey
);
733 account
.getStickerStore().updateSticker(sticker
);
736 return new URI("https",
740 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
742 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
743 } catch (URISyntaxException e
) {
744 throw new AssertionError(e
);
748 public void requestAllSyncData() throws IOException
{
749 syncHelper
.requestAllSyncData();
752 private byte[] getSenderCertificate() {
755 if (account
.isPhoneNumberShared()) {
756 certificate
= dependencies
.getAccountManager().getSenderCertificate();
758 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
760 } catch (IOException e
) {
761 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
764 // TODO cache for a day
768 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
769 final var address
= resolveSignalServiceAddress(recipientId
);
770 if (!address
.getNumber().isPresent()) {
773 final var number
= address
.getNumber().get();
774 final var uuid
= getRegisteredUser(number
);
775 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
778 private UUID
getRegisteredUser(final String number
) throws IOException
{
779 final Map
<String
, UUID
> uuidMap
;
781 uuidMap
= getRegisteredUsers(Set
.of(number
));
782 } catch (NumberFormatException e
) {
783 throw new UnregisteredUserException(number
, e
);
785 final var uuid
= uuidMap
.get(number
);
787 throw new UnregisteredUserException(number
, null);
792 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
793 final Map
<String
, UUID
> registeredUsers
;
795 registeredUsers
= dependencies
.getAccountManager()
796 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
798 serviceEnvironmentConfig
.getCdsMrenclave());
799 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
800 throw new IOException(e
);
803 // Store numbers as recipients so we have the number/uuid association
804 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
806 return registeredUsers
;
809 public void sendTypingMessage(
810 TypingAction action
, Set
<RecipientIdentifier
> recipients
811 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
812 sendTypingMessage(action
.toSignalService(), recipients
);
815 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
816 Set
<HandleAction
> queuedActions
= new HashSet
<>();
817 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
818 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
819 if (actions
!= null) {
820 queuedActions
.addAll(actions
);
823 handleQueuedActions(queuedActions
);
826 private List
<HandleAction
> retryFailedReceivedMessage(
827 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
829 var envelope
= cachedMessage
.loadEnvelope();
830 if (envelope
== null) {
831 cachedMessage
.delete();
835 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
836 final var actions
= result
.first();
837 final var exception
= result
.second();
839 if (exception
instanceof UntrustedIdentityException
) {
840 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
841 // Envelope is more than a month old, cleaning up.
842 cachedMessage
.delete();
845 if (!envelope
.hasSourceUuid()) {
846 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
847 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
849 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
850 } catch (IOException ioException
) {
851 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
857 // If successful and for all other errors that are not recoverable, delete the cached message
858 cachedMessage
.delete();
862 public void receiveMessages(
865 boolean returnOnTimeout
,
866 boolean ignoreAttachments
,
867 ReceiveMessageHandler handler
868 ) throws IOException
{
869 retryFailedReceivedMessages(handler
, ignoreAttachments
);
871 Set
<HandleAction
> queuedActions
= new HashSet
<>();
873 final var signalWebSocket
= dependencies
.getSignalWebSocket();
874 signalWebSocket
.connect();
876 hasCaughtUpWithOldMessages
= false;
878 while (!Thread
.interrupted()) {
879 SignalServiceEnvelope envelope
;
880 final CachedMessage
[] cachedMessage
= {null};
881 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
882 logger
.debug("Checking for new message from server");
884 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
885 final var recipientId
= envelope1
.hasSourceUuid()
886 ?
resolveRecipient(envelope1
.getSourceAddress())
888 // store message on disk, before acknowledging receipt to the server
889 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
891 logger
.debug("New message received from server");
892 if (result
.isPresent()) {
893 envelope
= result
.get();
895 // Received indicator that server queue is empty
896 handleQueuedActions(queuedActions
);
897 queuedActions
.clear();
899 hasCaughtUpWithOldMessages
= true;
900 synchronized (this) {
904 // Continue to wait another timeout for new messages
907 } catch (AssertionError e
) {
908 if (e
.getCause() instanceof InterruptedException
) {
909 Thread
.currentThread().interrupt();
914 } catch (WebSocketUnavailableException e
) {
915 logger
.debug("Pipe unexpectedly unavailable, connecting");
916 signalWebSocket
.connect();
918 } catch (TimeoutException e
) {
919 if (returnOnTimeout
) return;
923 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
924 queuedActions
.addAll(result
.first());
925 final var exception
= result
.second();
927 if (hasCaughtUpWithOldMessages
) {
928 handleQueuedActions(queuedActions
);
930 if (cachedMessage
[0] != null) {
931 if (exception
instanceof UntrustedIdentityException
) {
932 final var address
= ((UntrustedIdentityException
) exception
).getSender();
933 final var recipientId
= resolveRecipient(address
);
934 if (!envelope
.hasSourceUuid()) {
936 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
937 } catch (IOException ioException
) {
938 logger
.warn("Failed to move cached message to recipient folder: {}",
939 ioException
.getMessage());
943 cachedMessage
[0].delete();
947 handleQueuedActions(queuedActions
);
950 public boolean hasCaughtUpWithOldMessages() {
951 return hasCaughtUpWithOldMessages
;
954 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
955 var interrupted
= false;
956 for (var action
: queuedActions
) {
958 action
.execute(context
);
959 } catch (Throwable e
) {
960 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
961 && e
.getCause() instanceof InterruptedException
) {
965 logger
.warn("Message action failed.", e
);
969 Thread
.currentThread().interrupt();
973 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
974 final RecipientId recipientId
;
976 recipientId
= resolveRecipient(recipient
);
977 } catch (UnregisteredUserException e
) {
980 return contactHelper
.isContactBlocked(recipientId
);
983 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
984 return attachmentHelper
.getAttachmentFile(attachmentId
);
987 public void sendContacts() throws IOException
{
988 syncHelper
.sendContacts();
991 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
992 return account
.getContactStore().getContacts();
995 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
996 final RecipientId recipientId
;
998 recipientId
= resolveRecipient(recipientIdentifier
);
999 } catch (UnregisteredUserException e
) {
1003 final var contact
= account
.getContactStore().getContact(recipientId
);
1004 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
1005 return contact
.getName();
1008 final var profile
= getRecipientProfile(recipientId
);
1009 if (profile
!= null) {
1010 return profile
.getDisplayName();
1016 public GroupInfo
getGroup(GroupId groupId
) {
1017 return groupHelper
.getGroup(groupId
);
1020 public List
<IdentityInfo
> getIdentities() {
1021 return account
.getIdentityKeyStore().getIdentities();
1024 public List
<IdentityInfo
> getIdentities(RecipientIdentifier
.Single recipient
) {
1025 IdentityInfo identity
;
1027 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1028 } catch (UnregisteredUserException e
) {
1031 return identity
== null ? List
.of() : List
.of(identity
);
1035 * Trust this the identity with this fingerprint
1037 * @param recipient username of the identity
1038 * @param fingerprint Fingerprint
1040 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1041 RecipientId recipientId
;
1043 recipientId
= resolveRecipient(recipient
);
1044 } catch (UnregisteredUserException e
) {
1047 return trustIdentity(recipientId
,
1048 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1049 TrustLevel
.TRUSTED_VERIFIED
);
1053 * Trust this the identity with this safety number
1055 * @param recipient username of the identity
1056 * @param safetyNumber Safety number
1058 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1059 RecipientId recipientId
;
1061 recipientId
= resolveRecipient(recipient
);
1062 } catch (UnregisteredUserException e
) {
1065 var address
= resolveSignalServiceAddress(recipientId
);
1066 return trustIdentity(recipientId
,
1067 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1068 TrustLevel
.TRUSTED_VERIFIED
);
1072 * Trust this the identity with this scannable safety number
1074 * @param recipient username of the identity
1075 * @param safetyNumber Scannable safety number
1077 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1078 RecipientId recipientId
;
1080 recipientId
= resolveRecipient(recipient
);
1081 } catch (UnregisteredUserException e
) {
1084 var address
= resolveSignalServiceAddress(recipientId
);
1085 return trustIdentity(recipientId
, identityKey
-> {
1086 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1088 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1089 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1092 }, TrustLevel
.TRUSTED_VERIFIED
);
1096 * Trust all keys of this identity without verification
1098 * @param recipient username of the identity
1100 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1101 RecipientId recipientId
;
1103 recipientId
= resolveRecipient(recipient
);
1104 } catch (UnregisteredUserException e
) {
1107 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1110 private boolean trustIdentity(
1111 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1113 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1114 if (identity
== null) {
1118 if (!verifier
.apply(identity
.getIdentityKey())) {
1122 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1124 var address
= resolveSignalServiceAddress(recipientId
);
1125 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1126 } catch (IOException e
) {
1127 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1133 private void handleIdentityFailure(
1134 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1136 final var identityKey
= identityFailure
.getIdentityKey();
1137 if (identityKey
!= null) {
1138 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1140 account
.getSessionStore().archiveSessions(recipientId
);
1143 // Retrieve profile to get the current identity key from the server
1144 profileHelper
.refreshRecipientProfile(recipientId
);
1148 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1149 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1150 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1153 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1154 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1155 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1158 private Fingerprint
computeSafetyNumberFingerprint(
1159 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1161 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1162 account
.getSelfAddress(),
1163 getIdentityKeyPair().getPublicKey(),
1168 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1169 return resolveSignalServiceAddress(resolveRecipient(address
));
1172 public SignalServiceAddress
resolveSignalServiceAddress(UUID uuid
) {
1173 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1176 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1177 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1178 if (address
.getUuid().isPresent()) {
1179 return address
.toSignalServiceAddress();
1182 // Address in recipient store doesn't have a uuid, this shouldn't happen
1183 // Try to retrieve the uuid from the server
1184 final var number
= address
.getNumber().get();
1186 return resolveSignalServiceAddress(getRegisteredUser(number
));
1187 } catch (IOException e
) {
1188 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1189 // Return SignalServiceAddress with unknown UUID
1190 return address
.toSignalServiceAddress();
1194 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1195 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1196 for (var number
: recipients
) {
1197 final var recipientId
= resolveRecipient(number
);
1198 recipientIds
.add(recipientId
);
1200 return recipientIds
;
1203 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1204 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1205 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1207 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1208 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1210 return getRegisteredUser(number
);
1211 } catch (IOException e
) {
1218 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1219 return account
.getRecipientStore().resolveRecipient(address
);
1222 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1223 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1227 public void close() throws IOException
{
1231 private void close(boolean closeAccount
) throws IOException
{
1232 executor
.shutdown();
1234 dependencies
.getSignalWebSocket().disconnect();
1236 if (closeAccount
&& account
!= null) {
1242 public interface ReceiveMessageHandler
{
1244 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);