2 Copyright (C) 2015-2021 AsamK and contributors
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org
.asamk
.signal
.manager
;
19 import org
.asamk
.signal
.manager
.actions
.HandleAction
;
20 import org
.asamk
.signal
.manager
.api
.Device
;
21 import org
.asamk
.signal
.manager
.api
.Message
;
22 import org
.asamk
.signal
.manager
.api
.RecipientIdentifier
;
23 import org
.asamk
.signal
.manager
.api
.SendGroupMessageResults
;
24 import org
.asamk
.signal
.manager
.api
.SendMessageResults
;
25 import org
.asamk
.signal
.manager
.api
.TypingAction
;
26 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
27 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
28 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
29 import org
.asamk
.signal
.manager
.groups
.GroupId
;
30 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
31 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
32 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
33 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
34 import org
.asamk
.signal
.manager
.groups
.GroupSendingNotAllowedException
;
35 import org
.asamk
.signal
.manager
.groups
.LastGroupAdminException
;
36 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
37 import org
.asamk
.signal
.manager
.helper
.AttachmentHelper
;
38 import org
.asamk
.signal
.manager
.helper
.ContactHelper
;
39 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
40 import org
.asamk
.signal
.manager
.helper
.GroupV2Helper
;
41 import org
.asamk
.signal
.manager
.helper
.IncomingMessageHandler
;
42 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
43 import org
.asamk
.signal
.manager
.helper
.PreKeyHelper
;
44 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
45 import org
.asamk
.signal
.manager
.helper
.SendHelper
;
46 import org
.asamk
.signal
.manager
.helper
.StorageHelper
;
47 import org
.asamk
.signal
.manager
.helper
.SyncHelper
;
48 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
49 import org
.asamk
.signal
.manager
.jobs
.Context
;
50 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
51 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
52 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
53 import org
.asamk
.signal
.manager
.storage
.identities
.TrustNewIdentity
;
54 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
55 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
56 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
57 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
58 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
59 import org
.asamk
.signal
.manager
.storage
.stickers
.StickerPackId
;
60 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
61 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
62 import org
.asamk
.signal
.manager
.util
.Utils
;
63 import org
.slf4j
.Logger
;
64 import org
.slf4j
.LoggerFactory
;
65 import org
.whispersystems
.libsignal
.IdentityKey
;
66 import org
.whispersystems
.libsignal
.InvalidKeyException
;
67 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
68 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
69 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintParsingException
;
70 import org
.whispersystems
.libsignal
.fingerprint
.FingerprintVersionMismatchException
;
71 import org
.whispersystems
.libsignal
.util
.Pair
;
72 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
73 import org
.whispersystems
.signalservice
.api
.SignalSessionLock
;
74 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
75 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
76 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
77 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
78 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
79 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
80 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
81 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceTypingMessage
;
82 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
83 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
84 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
85 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
86 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
87 import org
.whispersystems
.signalservice
.api
.websocket
.WebSocketUnavailableException
;
88 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
89 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
90 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
91 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
92 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
93 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
95 import java
.io
.Closeable
;
97 import java
.io
.IOException
;
99 import java
.net
.URISyntaxException
;
100 import java
.net
.URLEncoder
;
101 import java
.nio
.charset
.StandardCharsets
;
102 import java
.security
.SignatureException
;
103 import java
.util
.Arrays
;
104 import java
.util
.Collection
;
105 import java
.util
.Date
;
106 import java
.util
.HashMap
;
107 import java
.util
.HashSet
;
108 import java
.util
.List
;
109 import java
.util
.Map
;
110 import java
.util
.Set
;
111 import java
.util
.UUID
;
112 import java
.util
.concurrent
.ExecutorService
;
113 import java
.util
.concurrent
.Executors
;
114 import java
.util
.concurrent
.TimeUnit
;
115 import java
.util
.concurrent
.TimeoutException
;
116 import java
.util
.concurrent
.locks
.ReentrantLock
;
117 import java
.util
.function
.Function
;
118 import java
.util
.stream
.Collectors
;
120 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
122 public class Manager
implements Closeable
{
124 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
126 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
127 private final SignalDependencies dependencies
;
129 private SignalAccount account
;
131 private final ExecutorService executor
= Executors
.newCachedThreadPool();
133 private final ProfileHelper profileHelper
;
134 private final PinHelper pinHelper
;
135 private final StorageHelper storageHelper
;
136 private final SendHelper sendHelper
;
137 private final SyncHelper syncHelper
;
138 private final AttachmentHelper attachmentHelper
;
139 private final GroupHelper groupHelper
;
140 private final ContactHelper contactHelper
;
141 private final IncomingMessageHandler incomingMessageHandler
;
142 private final PreKeyHelper preKeyHelper
;
144 private final Context context
;
145 private boolean hasCaughtUpWithOldMessages
= false;
148 SignalAccount account
,
149 PathConfig pathConfig
,
150 ServiceEnvironmentConfig serviceEnvironmentConfig
,
153 this.account
= account
;
154 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
156 final var credentialsProvider
= new DynamicCredentialsProvider(account
.getUuid(),
157 account
.getUsername(),
158 account
.getPassword(),
159 account
.getDeviceId());
160 final var sessionLock
= new SignalSessionLock() {
161 private final ReentrantLock LEGACY_LOCK
= new ReentrantLock();
164 public Lock
acquire() {
166 return LEGACY_LOCK
::unlock
;
169 this.dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
172 account
.getSignalProtocolStore(),
175 final var avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
176 final var attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
177 final var stickerPackStore
= new StickerPackStore(pathConfig
.getStickerPacksPath());
179 this.attachmentHelper
= new AttachmentHelper(dependencies
, attachmentStore
);
180 this.pinHelper
= new PinHelper(dependencies
.getKeyBackupService());
181 final var unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
182 account
.getProfileStore()::getProfileKey
,
183 this::getRecipientProfile
,
184 this::getSenderCertificate
);
185 this.profileHelper
= new ProfileHelper(account
,
188 account
.getProfileStore()::getProfileKey
,
189 unidentifiedAccessHelper
::getAccessFor
,
190 this::resolveSignalServiceAddress
);
191 final GroupV2Helper groupV2Helper
= new GroupV2Helper(profileHelper
::getRecipientProfileKeyCredential
,
192 this::getRecipientProfile
,
193 account
::getSelfRecipientId
,
194 dependencies
.getGroupsV2Operations(),
195 dependencies
.getGroupsV2Api(),
196 this::resolveSignalServiceAddress
);
197 this.sendHelper
= new SendHelper(account
,
199 unidentifiedAccessHelper
,
200 this::resolveSignalServiceAddress
,
201 account
.getRecipientStore(),
202 this::handleIdentityFailure
,
204 this::refreshRegisteredUser
);
205 this.groupHelper
= new GroupHelper(account
,
211 this::resolveSignalServiceAddress
,
212 account
.getRecipientStore());
213 this.storageHelper
= new StorageHelper(account
, dependencies
, groupHelper
);
214 this.contactHelper
= new ContactHelper(account
);
215 this.syncHelper
= new SyncHelper(account
,
220 this::resolveSignalServiceAddress
);
221 preKeyHelper
= new PreKeyHelper(account
, dependencies
);
223 this.context
= new Context(account
,
232 var jobExecutor
= new JobExecutor(context
);
234 this.incomingMessageHandler
= new IncomingMessageHandler(account
,
236 account
.getRecipientStore(),
237 this::resolveSignalServiceAddress
,
245 public String
getUsername() {
246 return account
.getUsername();
249 public RecipientId
getSelfRecipientId() {
250 return account
.getSelfRecipientId();
253 public int getDeviceId() {
254 return account
.getDeviceId();
257 public static Manager
init(
260 ServiceEnvironment serviceEnvironment
,
262 final TrustNewIdentity trustNewIdentity
263 ) throws IOException
, NotRegisteredException
{
264 var pathConfig
= PathConfig
.createDefault(settingsPath
);
266 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
267 throw new NotRegisteredException();
270 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
, true, trustNewIdentity
);
272 if (!account
.isRegistered()) {
273 throw new NotRegisteredException();
276 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
278 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
281 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
282 var pathConfig
= PathConfig
.createDefault(settingsPath
);
283 final var dataPath
= pathConfig
.getDataPath();
284 final var files
= dataPath
.listFiles();
290 return Arrays
.stream(files
)
291 .filter(File
::isFile
)
293 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
294 .collect(Collectors
.toList());
297 public void checkAccountState() throws IOException
{
298 if (account
.getLastReceiveTimestamp() == 0) {
299 logger
.info("The Signal protocol expects that incoming messages are regularly received.");
301 var diffInMilliseconds
= System
.currentTimeMillis() - account
.getLastReceiveTimestamp();
302 long days
= TimeUnit
.DAYS
.convert(diffInMilliseconds
, TimeUnit
.MILLISECONDS
);
305 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
309 preKeyHelper
.refreshPreKeysIfNecessary();
310 if (account
.getUuid() == null) {
311 account
.setUuid(dependencies
.getAccountManager().getOwnUuid());
313 updateAccountAttributes(null);
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(String deviceName
) throws IOException
{
346 final String encryptedDeviceName
;
347 if (deviceName
== null) {
348 encryptedDeviceName
= account
.getEncryptedDeviceName();
350 final var privateKey
= account
.getIdentityKeyPair().getPrivateKey();
351 encryptedDeviceName
= DeviceNameUtil
.encryptDeviceName(deviceName
, privateKey
);
352 account
.setEncryptedDeviceName(encryptedDeviceName
);
354 dependencies
.getAccountManager()
355 .setAccountAttributes(encryptedDeviceName
,
357 account
.getLocalRegistrationId(),
360 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
361 account
.getSelfUnidentifiedAccessKey(),
362 account
.isUnrestrictedUnidentifiedAccess(),
364 account
.isDiscoverableByPhoneNumber());
368 * @param givenName if null, the previous givenName will be kept
369 * @param familyName if null, the previous familyName will be kept
370 * @param about if null, the previous about text will be kept
371 * @param aboutEmoji if null, the previous about emoji will be kept
372 * @param avatar if avatar is null the image from the local avatar store is used (if present),
374 public void setProfile(
375 String givenName
, final String familyName
, String about
, String aboutEmoji
, Optional
<File
> avatar
376 ) throws IOException
{
377 profileHelper
.setProfile(givenName
, familyName
, about
, aboutEmoji
, avatar
);
378 syncHelper
.sendSyncFetchProfileMessage();
381 public void unregister() throws IOException
{
382 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
383 // If this is the master device, other users can't send messages to this number anymore.
384 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
385 dependencies
.getAccountManager().setGcmId(Optional
.absent());
387 account
.setRegistered(false);
390 public void deleteAccount() throws IOException
{
392 pinHelper
.removeRegistrationLockPin();
393 } catch (UnauthenticatedResponseException e
) {
394 logger
.warn("Failed to remove registration lock pin");
396 account
.setRegistrationLockPin(null, null);
398 dependencies
.getAccountManager().deleteAccount();
400 account
.setRegistered(false);
403 public void submitRateLimitRecaptchaChallenge(String challenge
, String captcha
) throws IOException
{
404 dependencies
.getAccountManager().submitRateLimitRecaptchaChallenge(challenge
, captcha
);
407 public List
<Device
> getLinkedDevices() throws IOException
{
408 var devices
= dependencies
.getAccountManager().getDevices();
409 account
.setMultiDevice(devices
.size() > 1);
410 var identityKey
= account
.getIdentityKeyPair().getPrivateKey();
411 return devices
.stream().map(d
-> {
412 String deviceName
= d
.getName();
413 if (deviceName
!= null) {
415 deviceName
= DeviceNameUtil
.decryptDeviceName(deviceName
, identityKey
);
416 } catch (IOException e
) {
417 logger
.debug("Failed to decrypt device name, maybe plain text?", e
);
420 return new Device(d
.getId(), deviceName
, d
.getCreated(), d
.getLastSeen());
421 }).collect(Collectors
.toList());
424 public void removeLinkedDevices(int deviceId
) throws IOException
{
425 dependencies
.getAccountManager().removeDevice(deviceId
);
426 var devices
= dependencies
.getAccountManager().getDevices();
427 account
.setMultiDevice(devices
.size() > 1);
430 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
431 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
433 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
436 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
437 var identityKeyPair
= account
.getIdentityKeyPair();
438 var verificationCode
= dependencies
.getAccountManager().getNewDeviceVerificationCode();
440 dependencies
.getAccountManager()
441 .addDevice(deviceIdentifier
,
444 Optional
.of(account
.getProfileKey().serialize()),
446 account
.setMultiDevice(true);
449 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
450 if (!account
.isMasterDevice()) {
451 throw new RuntimeException("Only master device can set a PIN");
453 if (pin
.isPresent()) {
454 final var masterKey
= account
.getPinMasterKey() != null
455 ? account
.getPinMasterKey()
456 : KeyUtils
.createMasterKey();
458 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
460 account
.setRegistrationLockPin(pin
.get(), masterKey
);
463 pinHelper
.removeRegistrationLockPin();
465 account
.setRegistrationLockPin(null, null);
469 void refreshPreKeys() throws IOException
{
470 preKeyHelper
.refreshPreKeys();
473 public Profile
getRecipientProfile(RecipientId recipientId
) {
474 return profileHelper
.getRecipientProfile(recipientId
);
477 public List
<GroupInfo
> getGroups() {
478 return account
.getGroupStore().getGroups();
481 public SendGroupMessageResults
quitGroup(
482 GroupId groupId
, Set
<RecipientIdentifier
.Single
> groupAdmins
483 ) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
, LastGroupAdminException
{
484 final var newAdmins
= resolveRecipients(groupAdmins
);
485 return groupHelper
.quitGroup(groupId
, newAdmins
);
488 public void deleteGroup(GroupId groupId
) throws IOException
{
489 groupHelper
.deleteGroup(groupId
);
492 public Pair
<GroupId
, SendGroupMessageResults
> createGroup(
493 String name
, Set
<RecipientIdentifier
.Single
> members
, File avatarFile
494 ) throws IOException
, AttachmentInvalidException
{
495 return groupHelper
.createGroup(name
, members
== null ?
null : resolveRecipients(members
), avatarFile
);
498 public SendGroupMessageResults
updateGroup(
502 Set
<RecipientIdentifier
.Single
> members
,
503 Set
<RecipientIdentifier
.Single
> removeMembers
,
504 Set
<RecipientIdentifier
.Single
> admins
,
505 Set
<RecipientIdentifier
.Single
> removeAdmins
,
506 boolean resetGroupLink
,
507 GroupLinkState groupLinkState
,
508 GroupPermission addMemberPermission
,
509 GroupPermission editDetailsPermission
,
511 Integer expirationTimer
,
512 Boolean isAnnouncementGroup
513 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupSendingNotAllowedException
{
514 return groupHelper
.updateGroup(groupId
,
517 members
== null ?
null : resolveRecipients(members
),
518 removeMembers
== null ?
null : resolveRecipients(removeMembers
),
519 admins
== null ?
null : resolveRecipients(admins
),
520 removeAdmins
== null ?
null : resolveRecipients(removeAdmins
),
524 editDetailsPermission
,
527 isAnnouncementGroup
);
530 public Pair
<GroupId
, SendGroupMessageResults
> joinGroup(
531 GroupInviteLinkUrl inviteLinkUrl
532 ) throws IOException
, GroupLinkNotActiveException
{
533 return groupHelper
.joinGroup(inviteLinkUrl
);
536 public SendMessageResults
sendMessage(
537 SignalServiceDataMessage
.Builder messageBuilder
, Set
<RecipientIdentifier
> recipients
538 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
539 var results
= new HashMap
<RecipientIdentifier
, List
<SendMessageResult
>>();
540 long timestamp
= System
.currentTimeMillis();
541 messageBuilder
.withTimestamp(timestamp
);
542 for (final var recipient
: recipients
) {
543 if (recipient
instanceof RecipientIdentifier
.Single
) {
544 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
545 final var result
= sendHelper
.sendMessage(messageBuilder
, recipientId
);
546 results
.put(recipient
, List
.of(result
));
547 } else if (recipient
instanceof RecipientIdentifier
.NoteToSelf
) {
548 final var result
= sendHelper
.sendSelfMessage(messageBuilder
);
549 results
.put(recipient
, List
.of(result
));
550 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
551 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
552 final var result
= sendHelper
.sendAsGroupMessage(messageBuilder
, groupId
);
553 results
.put(recipient
, result
);
556 return new SendMessageResults(timestamp
, results
);
559 public void sendTypingMessage(
560 SignalServiceTypingMessage
.Action action
, Set
<RecipientIdentifier
> recipients
561 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
562 final var timestamp
= System
.currentTimeMillis();
563 for (var recipient
: recipients
) {
564 if (recipient
instanceof RecipientIdentifier
.Single
) {
565 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.absent());
566 final var recipientId
= resolveRecipient((RecipientIdentifier
.Single
) recipient
);
567 sendHelper
.sendTypingMessage(message
, recipientId
);
568 } else if (recipient
instanceof RecipientIdentifier
.Group
) {
569 final var groupId
= ((RecipientIdentifier
.Group
) recipient
).groupId
;
570 final var message
= new SignalServiceTypingMessage(action
, timestamp
, Optional
.of(groupId
.serialize()));
571 sendHelper
.sendGroupTypingMessage(message
, groupId
);
576 public void sendReadReceipt(
577 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
578 ) throws IOException
, UntrustedIdentityException
{
579 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.READ
,
581 System
.currentTimeMillis());
583 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
586 public void sendViewedReceipt(
587 RecipientIdentifier
.Single sender
, List
<Long
> messageIds
588 ) throws IOException
, UntrustedIdentityException
{
589 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.VIEWED
,
591 System
.currentTimeMillis());
593 sendHelper
.sendReceiptMessage(receiptMessage
, resolveRecipient(sender
));
596 public SendMessageResults
sendMessage(
597 Message message
, Set
<RecipientIdentifier
> recipients
598 ) throws IOException
, AttachmentInvalidException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
599 final var messageBuilder
= SignalServiceDataMessage
.newBuilder();
600 applyMessage(messageBuilder
, message
);
601 return sendMessage(messageBuilder
, recipients
);
604 private void applyMessage(
605 final SignalServiceDataMessage
.Builder messageBuilder
, final Message message
606 ) throws AttachmentInvalidException
, IOException
{
607 messageBuilder
.withBody(message
.getMessageText());
608 final var attachments
= message
.getAttachments();
609 if (attachments
!= null) {
610 messageBuilder
.withAttachments(attachmentHelper
.uploadAttachments(attachments
));
614 public SendMessageResults
sendRemoteDeleteMessage(
615 long targetSentTimestamp
, Set
<RecipientIdentifier
> recipients
616 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
617 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
618 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
619 return sendMessage(messageBuilder
, recipients
);
622 public SendMessageResults
sendMessageReaction(
625 RecipientIdentifier
.Single targetAuthor
,
626 long targetSentTimestamp
,
627 Set
<RecipientIdentifier
> recipients
628 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
629 var targetAuthorRecipientId
= resolveRecipient(targetAuthor
);
630 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
632 resolveSignalServiceAddress(targetAuthorRecipientId
),
633 targetSentTimestamp
);
634 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
635 return sendMessage(messageBuilder
, recipients
);
638 public SendMessageResults
sendEndSessionMessage(Set
<RecipientIdentifier
.Single
> recipients
) throws IOException
{
639 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
642 return sendMessage(messageBuilder
,
643 recipients
.stream().map(RecipientIdentifier
.class::cast
).collect(Collectors
.toSet()));
644 } catch (GroupNotFoundException
| NotAGroupMemberException
| GroupSendingNotAllowedException e
) {
645 throw new AssertionError(e
);
647 for (var recipient
: recipients
) {
648 final var recipientId
= resolveRecipient(recipient
);
649 account
.getSessionStore().deleteAllSessions(recipientId
);
654 public void setContactName(
655 RecipientIdentifier
.Single recipient
, String name
656 ) throws NotMasterDeviceException
, UnregisteredUserException
{
657 if (!account
.isMasterDevice()) {
658 throw new NotMasterDeviceException();
660 contactHelper
.setContactName(resolveRecipient(recipient
), name
);
663 public void setContactBlocked(
664 RecipientIdentifier
.Single recipient
, boolean blocked
665 ) throws NotMasterDeviceException
, IOException
{
666 if (!account
.isMasterDevice()) {
667 throw new NotMasterDeviceException();
669 contactHelper
.setContactBlocked(resolveRecipient(recipient
), blocked
);
670 // TODO cycle our profile key
671 syncHelper
.sendBlockedList();
674 public void setGroupBlocked(
675 final GroupId groupId
, final boolean blocked
676 ) throws GroupNotFoundException
, IOException
{
677 groupHelper
.setGroupBlocked(groupId
, blocked
);
678 // TODO cycle our profile key
679 syncHelper
.sendBlockedList();
683 * Change the expiration timer for a contact
685 public void setExpirationTimer(
686 RecipientIdentifier
.Single recipient
, int messageExpirationTimer
687 ) throws IOException
{
688 var recipientId
= resolveRecipient(recipient
);
689 contactHelper
.setExpirationTimer(recipientId
, messageExpirationTimer
);
690 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
692 sendMessage(messageBuilder
, Set
.of(recipient
));
693 } catch (NotAGroupMemberException
| GroupNotFoundException
| GroupSendingNotAllowedException e
) {
694 throw new AssertionError(e
);
699 * Upload the sticker pack from path.
701 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
702 * @return if successful, returns the URL to install the sticker pack in the signal app
704 public URI
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
705 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
707 var messageSender
= dependencies
.getMessageSender();
709 var packKey
= KeyUtils
.createStickerUploadKey();
710 var packIdString
= messageSender
.uploadStickerManifest(manifest
, packKey
);
711 var packId
= StickerPackId
.deserialize(Hex
.fromStringCondensed(packIdString
));
713 var sticker
= new Sticker(packId
, packKey
);
714 account
.getStickerStore().updateSticker(sticker
);
717 return new URI("https",
721 + URLEncoder
.encode(Hex
.toStringCondensed(packId
.serialize()), StandardCharsets
.UTF_8
)
723 + URLEncoder
.encode(Hex
.toStringCondensed(packKey
), StandardCharsets
.UTF_8
));
724 } catch (URISyntaxException e
) {
725 throw new AssertionError(e
);
729 public void requestAllSyncData() throws IOException
{
730 syncHelper
.requestAllSyncData();
731 retrieveRemoteStorage();
734 void retrieveRemoteStorage() throws IOException
{
735 if (account
.getStorageKey() != null) {
736 storageHelper
.readDataFromStorage();
740 private byte[] getSenderCertificate() {
743 if (account
.isPhoneNumberShared()) {
744 certificate
= dependencies
.getAccountManager().getSenderCertificate();
746 certificate
= dependencies
.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
748 } catch (IOException e
) {
749 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
752 // TODO cache for a day
756 private RecipientId
refreshRegisteredUser(RecipientId recipientId
) throws IOException
{
757 final var address
= resolveSignalServiceAddress(recipientId
);
758 if (!address
.getNumber().isPresent()) {
761 final var number
= address
.getNumber().get();
762 final var uuid
= getRegisteredUser(number
);
763 return resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
));
766 private UUID
getRegisteredUser(final String number
) throws IOException
{
767 final Map
<String
, UUID
> uuidMap
;
769 uuidMap
= getRegisteredUsers(Set
.of(number
));
770 } catch (NumberFormatException e
) {
771 throw new UnregisteredUserException(number
, e
);
773 final var uuid
= uuidMap
.get(number
);
775 throw new UnregisteredUserException(number
, null);
780 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbers
) throws IOException
{
781 final Map
<String
, UUID
> registeredUsers
;
783 registeredUsers
= dependencies
.getAccountManager()
784 .getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
786 serviceEnvironmentConfig
.getCdsMrenclave());
787 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
788 throw new IOException(e
);
791 // Store numbers as recipients so we have the number/uuid association
792 registeredUsers
.forEach((number
, uuid
) -> resolveRecipientTrusted(new SignalServiceAddress(uuid
, number
)));
794 return registeredUsers
;
797 public void sendTypingMessage(
798 TypingAction action
, Set
<RecipientIdentifier
> recipients
799 ) throws IOException
, UntrustedIdentityException
, NotAGroupMemberException
, GroupNotFoundException
, GroupSendingNotAllowedException
{
800 sendTypingMessage(action
.toSignalService(), recipients
);
803 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
804 Set
<HandleAction
> queuedActions
= new HashSet
<>();
805 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
806 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
807 if (actions
!= null) {
808 queuedActions
.addAll(actions
);
811 handleQueuedActions(queuedActions
);
814 private List
<HandleAction
> retryFailedReceivedMessage(
815 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
817 var envelope
= cachedMessage
.loadEnvelope();
818 if (envelope
== null) {
819 cachedMessage
.delete();
823 final var result
= incomingMessageHandler
.handleRetryEnvelope(envelope
, ignoreAttachments
, handler
);
824 final var actions
= result
.first();
825 final var exception
= result
.second();
827 if (exception
instanceof UntrustedIdentityException
) {
828 if (System
.currentTimeMillis() - envelope
.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
829 // Envelope is more than a month old, cleaning up.
830 cachedMessage
.delete();
833 if (!envelope
.hasSourceUuid()) {
834 final var identifier
= ((UntrustedIdentityException
) exception
).getSender();
835 final var recipientId
= account
.getRecipientStore().resolveRecipient(identifier
);
837 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
838 } catch (IOException ioException
) {
839 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
845 // If successful and for all other errors that are not recoverable, delete the cached message
846 cachedMessage
.delete();
850 public void receiveMessages(
853 boolean returnOnTimeout
,
854 boolean ignoreAttachments
,
855 ReceiveMessageHandler handler
856 ) throws IOException
{
857 retryFailedReceivedMessages(handler
, ignoreAttachments
);
859 Set
<HandleAction
> queuedActions
= new HashSet
<>();
861 final var signalWebSocket
= dependencies
.getSignalWebSocket();
862 signalWebSocket
.connect();
864 hasCaughtUpWithOldMessages
= false;
866 while (!Thread
.interrupted()) {
867 SignalServiceEnvelope envelope
;
868 final CachedMessage
[] cachedMessage
= {null};
869 account
.setLastReceiveTimestamp(System
.currentTimeMillis());
870 logger
.debug("Checking for new message from server");
872 var result
= signalWebSocket
.readOrEmpty(unit
.toMillis(timeout
), envelope1
-> {
873 final var recipientId
= envelope1
.hasSourceUuid()
874 ?
resolveRecipient(envelope1
.getSourceAddress())
876 // store message on disk, before acknowledging receipt to the server
877 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
879 logger
.debug("New message received from server");
880 if (result
.isPresent()) {
881 envelope
= result
.get();
883 // Received indicator that server queue is empty
884 handleQueuedActions(queuedActions
);
885 queuedActions
.clear();
887 hasCaughtUpWithOldMessages
= true;
888 synchronized (this) {
892 // Continue to wait another timeout for new messages
895 } catch (AssertionError e
) {
896 if (e
.getCause() instanceof InterruptedException
) {
897 Thread
.currentThread().interrupt();
902 } catch (WebSocketUnavailableException e
) {
903 logger
.debug("Pipe unexpectedly unavailable, connecting");
904 signalWebSocket
.connect();
906 } catch (TimeoutException e
) {
907 if (returnOnTimeout
) return;
911 final var result
= incomingMessageHandler
.handleEnvelope(envelope
, ignoreAttachments
, handler
);
912 queuedActions
.addAll(result
.first());
913 final var exception
= result
.second();
915 if (hasCaughtUpWithOldMessages
) {
916 handleQueuedActions(queuedActions
);
918 if (cachedMessage
[0] != null) {
919 if (exception
instanceof UntrustedIdentityException
) {
920 final var address
= ((UntrustedIdentityException
) exception
).getSender();
921 final var recipientId
= resolveRecipient(address
);
922 if (!envelope
.hasSourceUuid()) {
924 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
925 } catch (IOException ioException
) {
926 logger
.warn("Failed to move cached message to recipient folder: {}",
927 ioException
.getMessage());
931 cachedMessage
[0].delete();
935 handleQueuedActions(queuedActions
);
938 public boolean hasCaughtUpWithOldMessages() {
939 return hasCaughtUpWithOldMessages
;
942 private void handleQueuedActions(final Collection
<HandleAction
> queuedActions
) {
943 var interrupted
= false;
944 for (var action
: queuedActions
) {
946 action
.execute(context
);
947 } catch (Throwable e
) {
948 if ((e
instanceof AssertionError
|| e
instanceof RuntimeException
)
949 && e
.getCause() instanceof InterruptedException
) {
953 logger
.warn("Message action failed.", e
);
957 Thread
.currentThread().interrupt();
961 public boolean isContactBlocked(final RecipientIdentifier
.Single recipient
) {
962 final RecipientId recipientId
;
964 recipientId
= resolveRecipient(recipient
);
965 } catch (UnregisteredUserException e
) {
968 return contactHelper
.isContactBlocked(recipientId
);
971 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
972 return attachmentHelper
.getAttachmentFile(attachmentId
);
975 public void sendContacts() throws IOException
{
976 syncHelper
.sendContacts();
979 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
980 return account
.getContactStore().getContacts();
983 public String
getContactOrProfileName(RecipientIdentifier
.Single recipientIdentifier
) {
984 final RecipientId recipientId
;
986 recipientId
= resolveRecipient(recipientIdentifier
);
987 } catch (UnregisteredUserException e
) {
991 final var contact
= account
.getContactStore().getContact(recipientId
);
992 if (contact
!= null && !Util
.isEmpty(contact
.getName())) {
993 return contact
.getName();
996 final var profile
= getRecipientProfile(recipientId
);
997 if (profile
!= null) {
998 return profile
.getDisplayName();
1004 public GroupInfo
getGroup(GroupId groupId
) {
1005 return groupHelper
.getGroup(groupId
);
1008 public List
<IdentityInfo
> getIdentities() {
1009 return account
.getIdentityKeyStore().getIdentities();
1012 public List
<IdentityInfo
> getIdentities(RecipientIdentifier
.Single recipient
) {
1013 IdentityInfo identity
;
1015 identity
= account
.getIdentityKeyStore().getIdentity(resolveRecipient(recipient
));
1016 } catch (UnregisteredUserException e
) {
1019 return identity
== null ? List
.of() : List
.of(identity
);
1023 * Trust this the identity with this fingerprint
1025 * @param recipient username of the identity
1026 * @param fingerprint Fingerprint
1028 public boolean trustIdentityVerified(RecipientIdentifier
.Single recipient
, byte[] fingerprint
) {
1029 RecipientId recipientId
;
1031 recipientId
= resolveRecipient(recipient
);
1032 } catch (UnregisteredUserException e
) {
1035 return trustIdentity(recipientId
,
1036 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
1037 TrustLevel
.TRUSTED_VERIFIED
);
1041 * Trust this the identity with this safety number
1043 * @param recipient username of the identity
1044 * @param safetyNumber Safety number
1046 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, String safetyNumber
) {
1047 RecipientId recipientId
;
1049 recipientId
= resolveRecipient(recipient
);
1050 } catch (UnregisteredUserException e
) {
1053 var address
= resolveSignalServiceAddress(recipientId
);
1054 return trustIdentity(recipientId
,
1055 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
1056 TrustLevel
.TRUSTED_VERIFIED
);
1060 * Trust this the identity with this scannable safety number
1062 * @param recipient username of the identity
1063 * @param safetyNumber Scannable safety number
1065 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier
.Single recipient
, byte[] safetyNumber
) {
1066 RecipientId recipientId
;
1068 recipientId
= resolveRecipient(recipient
);
1069 } catch (UnregisteredUserException e
) {
1072 var address
= resolveSignalServiceAddress(recipientId
);
1073 return trustIdentity(recipientId
, identityKey
-> {
1074 final var fingerprint
= computeSafetyNumberFingerprint(address
, identityKey
);
1076 return fingerprint
!= null && fingerprint
.getScannableFingerprint().compareTo(safetyNumber
);
1077 } catch (FingerprintVersionMismatchException
| FingerprintParsingException e
) {
1080 }, TrustLevel
.TRUSTED_VERIFIED
);
1084 * Trust all keys of this identity without verification
1086 * @param recipient username of the identity
1088 public boolean trustIdentityAllKeys(RecipientIdentifier
.Single recipient
) {
1089 RecipientId recipientId
;
1091 recipientId
= resolveRecipient(recipient
);
1092 } catch (UnregisteredUserException e
) {
1095 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
1098 private boolean trustIdentity(
1099 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
1101 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
1102 if (identity
== null) {
1106 if (!verifier
.apply(identity
.getIdentityKey())) {
1110 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
1112 var address
= resolveSignalServiceAddress(recipientId
);
1113 syncHelper
.sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
1114 } catch (IOException e
) {
1115 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
1121 private void handleIdentityFailure(
1122 final RecipientId recipientId
, final SendMessageResult
.IdentityFailure identityFailure
1124 final var identityKey
= identityFailure
.getIdentityKey();
1125 if (identityKey
!= null) {
1126 final var newIdentity
= account
.getIdentityKeyStore().saveIdentity(recipientId
, identityKey
, new Date());
1128 account
.getSessionStore().archiveSessions(recipientId
);
1131 // Retrieve profile to get the current identity key from the server
1132 profileHelper
.refreshRecipientProfile(recipientId
);
1136 public String
computeSafetyNumber(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1137 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1138 return fingerprint
== null ?
null : fingerprint
.getDisplayableFingerprint().getDisplayText();
1141 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
) {
1142 final Fingerprint fingerprint
= computeSafetyNumberFingerprint(theirAddress
, theirIdentityKey
);
1143 return fingerprint
== null ?
null : fingerprint
.getScannableFingerprint().getSerialized();
1146 private Fingerprint
computeSafetyNumberFingerprint(
1147 final SignalServiceAddress theirAddress
, final IdentityKey theirIdentityKey
1149 return Utils
.computeSafetyNumber(capabilities
.isUuid(),
1150 account
.getSelfAddress(),
1151 account
.getIdentityKeyPair().getPublicKey(),
1156 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
1157 return resolveSignalServiceAddress(resolveRecipient(address
));
1160 public SignalServiceAddress
resolveSignalServiceAddress(UUID uuid
) {
1161 return resolveSignalServiceAddress(account
.getRecipientStore().resolveRecipient(uuid
));
1164 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
1165 final var address
= account
.getRecipientStore().resolveRecipientAddress(recipientId
);
1166 if (address
.getUuid().isPresent()) {
1167 return address
.toSignalServiceAddress();
1170 // Address in recipient store doesn't have a uuid, this shouldn't happen
1171 // Try to retrieve the uuid from the server
1172 final var number
= address
.getNumber().get();
1174 return resolveSignalServiceAddress(getRegisteredUser(number
));
1175 } catch (IOException e
) {
1176 logger
.warn("Failed to get uuid for e164 number: {}", number
, e
);
1177 // Return SignalServiceAddress with unknown UUID
1178 return address
.toSignalServiceAddress();
1182 private Set
<RecipientId
> resolveRecipients(Collection
<RecipientIdentifier
.Single
> recipients
) throws UnregisteredUserException
{
1183 final var recipientIds
= new HashSet
<RecipientId
>(recipients
.size());
1184 for (var number
: recipients
) {
1185 final var recipientId
= resolveRecipient(number
);
1186 recipientIds
.add(recipientId
);
1188 return recipientIds
;
1191 private RecipientId
resolveRecipient(final RecipientIdentifier
.Single recipient
) throws UnregisteredUserException
{
1192 if (recipient
instanceof RecipientIdentifier
.Uuid
) {
1193 return account
.getRecipientStore().resolveRecipient(((RecipientIdentifier
.Uuid
) recipient
).uuid
);
1195 final var number
= ((RecipientIdentifier
.Number
) recipient
).number
;
1196 return account
.getRecipientStore().resolveRecipient(number
, () -> {
1198 return getRegisteredUser(number
);
1199 } catch (IOException e
) {
1206 private RecipientId
resolveRecipient(SignalServiceAddress address
) {
1207 return account
.getRecipientStore().resolveRecipient(address
);
1210 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
1211 return account
.getRecipientStore().resolveRecipientTrusted(address
);
1215 public void close() throws IOException
{
1219 private void close(boolean closeAccount
) throws IOException
{
1220 executor
.shutdown();
1222 dependencies
.getSignalWebSocket().disconnect();
1224 if (closeAccount
&& account
!= null) {
1230 public interface ReceiveMessageHandler
{
1232 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);