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
.config
.ServiceConfig
;
20 import org
.asamk
.signal
.manager
.config
.ServiceEnvironment
;
21 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
22 import org
.asamk
.signal
.manager
.groups
.GroupId
;
23 import org
.asamk
.signal
.manager
.groups
.GroupIdV1
;
24 import org
.asamk
.signal
.manager
.groups
.GroupInviteLinkUrl
;
25 import org
.asamk
.signal
.manager
.groups
.GroupNotFoundException
;
26 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
27 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
28 import org
.asamk
.signal
.manager
.helper
.GroupHelper
;
29 import org
.asamk
.signal
.manager
.helper
.PinHelper
;
30 import org
.asamk
.signal
.manager
.helper
.ProfileHelper
;
31 import org
.asamk
.signal
.manager
.helper
.UnidentifiedAccessHelper
;
32 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
33 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
34 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
35 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
36 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
37 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
38 import org
.asamk
.signal
.manager
.storage
.recipients
.Contact
;
39 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
40 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
41 import org
.asamk
.signal
.manager
.storage
.stickers
.Sticker
;
42 import org
.asamk
.signal
.manager
.util
.AttachmentUtils
;
43 import org
.asamk
.signal
.manager
.util
.IOUtils
;
44 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
45 import org
.asamk
.signal
.manager
.util
.ProfileUtils
;
46 import org
.asamk
.signal
.manager
.util
.StickerUtils
;
47 import org
.asamk
.signal
.manager
.util
.Utils
;
48 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
49 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
50 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
51 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
52 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
53 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
54 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
55 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
56 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
57 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
58 import org
.signal
.libsignal
.metadata
.SelfSendException
;
59 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
60 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
61 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
62 import org
.signal
.zkgroup
.InvalidInputException
;
63 import org
.signal
.zkgroup
.VerificationFailedException
;
64 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
65 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
66 import org
.signal
.zkgroup
.profiles
.ClientZkProfileOperations
;
67 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
68 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
69 import org
.slf4j
.Logger
;
70 import org
.slf4j
.LoggerFactory
;
71 import org
.whispersystems
.libsignal
.IdentityKey
;
72 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
73 import org
.whispersystems
.libsignal
.InvalidKeyException
;
74 import org
.whispersystems
.libsignal
.InvalidMessageException
;
75 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
76 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
77 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
78 import org
.whispersystems
.libsignal
.util
.Pair
;
79 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
80 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
81 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
82 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
83 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
84 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
85 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
86 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
87 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
88 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
89 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
90 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
91 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
92 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
93 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
94 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentRemoteId
;
95 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
96 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
97 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
98 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
99 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
100 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroupV2
;
101 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceReceiptMessage
;
102 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.BlockedListMessage
;
103 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
104 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
105 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
106 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
107 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
108 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
109 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
110 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
111 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
112 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
113 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
114 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.StickerPackOperationMessage
;
115 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
116 import org
.whispersystems
.signalservice
.api
.profiles
.ProfileAndCredential
;
117 import org
.whispersystems
.signalservice
.api
.profiles
.SignalServiceProfile
;
118 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
119 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.MissingConfigurationException
;
120 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
121 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
122 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
123 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
124 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
125 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.Quote
;
126 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedQuoteException
;
127 import org
.whispersystems
.signalservice
.internal
.contacts
.crypto
.UnauthenticatedResponseException
;
128 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
129 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
130 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
131 import org
.whispersystems
.signalservice
.internal
.util
.Hex
;
132 import org
.whispersystems
.signalservice
.internal
.util
.Util
;
134 import java
.io
.Closeable
;
136 import java
.io
.FileInputStream
;
137 import java
.io
.FileOutputStream
;
138 import java
.io
.IOException
;
139 import java
.io
.InputStream
;
140 import java
.io
.OutputStream
;
142 import java
.net
.URISyntaxException
;
143 import java
.net
.URLEncoder
;
144 import java
.nio
.charset
.StandardCharsets
;
145 import java
.nio
.file
.Files
;
146 import java
.security
.SignatureException
;
147 import java
.util
.ArrayList
;
148 import java
.util
.Arrays
;
149 import java
.util
.Base64
;
150 import java
.util
.Collection
;
151 import java
.util
.Date
;
152 import java
.util
.HashSet
;
153 import java
.util
.List
;
154 import java
.util
.Map
;
155 import java
.util
.Set
;
156 import java
.util
.UUID
;
157 import java
.util
.concurrent
.ExecutorService
;
158 import java
.util
.concurrent
.Executors
;
159 import java
.util
.concurrent
.TimeUnit
;
160 import java
.util
.concurrent
.TimeoutException
;
161 import java
.util
.function
.Function
;
162 import java
.util
.stream
.Collectors
;
164 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
166 public class Manager
implements Closeable
{
168 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
170 private final CertificateValidator certificateValidator
;
172 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
173 private final String userAgent
;
175 private SignalAccount account
;
176 private final SignalServiceAccountManager accountManager
;
177 private final GroupsV2Api groupsV2Api
;
178 private final GroupsV2Operations groupsV2Operations
;
179 private final SignalServiceMessageReceiver messageReceiver
;
180 private final ClientZkProfileOperations clientZkProfileOperations
;
182 private final ExecutorService executor
= Executors
.newCachedThreadPool();
184 private SignalServiceMessagePipe messagePipe
= null;
185 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
187 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
188 private final ProfileHelper profileHelper
;
189 private final GroupHelper groupHelper
;
190 private final PinHelper pinHelper
;
191 private final AvatarStore avatarStore
;
192 private final AttachmentStore attachmentStore
;
195 SignalAccount account
,
196 PathConfig pathConfig
,
197 ServiceEnvironmentConfig serviceEnvironmentConfig
,
200 this.account
= account
;
201 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
202 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
203 this.userAgent
= userAgent
;
204 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
205 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
206 final SleepTimer timer
= new UptimeSleepTimer();
207 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
208 new DynamicCredentialsProvider(account
.getUuid(),
209 account
.getUsername(),
210 account
.getPassword(),
211 account
.getDeviceId()),
214 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
216 this.groupsV2Api
= accountManager
.getGroupsV2Api();
217 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
218 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
219 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
220 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
223 this.pinHelper
= new PinHelper(keyBackupService
);
224 this.clientZkProfileOperations
= capabilities
.isGv2()
225 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
226 .getProfileOperations()
228 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
230 account
.getUsername(),
231 account
.getPassword(),
232 account
.getDeviceId(),
236 clientZkProfileOperations
,
237 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
239 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
240 account
.getProfileStore()::getProfileKey
,
241 this::getRecipientProfile
,
242 this::getSenderCertificate
);
243 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
244 unidentifiedAccessHelper
::getAccessFor
,
245 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
246 () -> messageReceiver
,
247 this::resolveSignalServiceAddress
);
248 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
249 this::getRecipientProfile
,
250 account
::getSelfRecipientId
,
253 this::getGroupAuthForToday
,
254 this::resolveSignalServiceAddress
);
255 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
256 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
259 public String
getUsername() {
260 return account
.getUsername();
263 public SignalServiceAddress
getSelfAddress() {
264 return account
.getSelfAddress();
267 private IdentityKeyPair
getIdentityKeyPair() {
268 return account
.getIdentityKeyPair();
271 public int getDeviceId() {
272 return account
.getDeviceId();
275 public static Manager
init(
276 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
277 ) throws IOException
, NotRegisteredException
{
278 var pathConfig
= PathConfig
.createDefault(settingsPath
);
280 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
281 throw new NotRegisteredException();
284 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
286 if (!account
.isRegistered()) {
287 throw new NotRegisteredException();
290 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
292 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
295 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
296 var pathConfig
= PathConfig
.createDefault(settingsPath
);
297 final var dataPath
= pathConfig
.getDataPath();
298 final var files
= dataPath
.listFiles();
304 return Arrays
.stream(files
)
305 .filter(File
::isFile
)
307 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
308 .collect(Collectors
.toList());
311 public void checkAccountState() throws IOException
{
312 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
316 if (account
.getUuid() == null) {
317 account
.setUuid(accountManager
.getOwnUuid());
320 updateAccountAttributes();
324 * This is used for checking a set of phone numbers for registration on Signal
326 * @param numbers The set of phone number in question
327 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
328 * @throws IOException if its unable to get the contacts to check if they're registered
330 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
331 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
332 var contactDetails
= getRegisteredUsers(numbers
);
334 var registeredUsers
= contactDetails
.keySet();
336 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
339 public void updateAccountAttributes() throws IOException
{
340 accountManager
.setAccountAttributes(null,
341 account
.getLocalRegistrationId(),
343 // set legacy pin only if no KBS master key is set
344 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
345 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
346 account
.getSelfUnidentifiedAccessKey(),
347 account
.isUnrestrictedUnidentifiedAccess(),
349 account
.isDiscoverableByPhoneNumber());
353 * @param name if null, the previous name will be kept
354 * @param about if null, the previous about text will be kept
355 * @param aboutEmoji if null, the previous about emoji will be kept
356 * @param avatar if avatar is null the image from the local avatar store is used (if present),
357 * if it's Optional.absent(), the avatar will be removed
359 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
360 var profile
= getRecipientProfile(account
.getSelfRecipientId());
361 var builder
= profile
== null ? Profile
.newBuilder() : Profile
.newBuilder(profile
);
363 builder
.withGivenName(name
);
364 builder
.withFamilyName(null);
367 builder
.withAbout(about
);
369 if (aboutEmoji
!= null) {
370 builder
.withAboutEmoji(aboutEmoji
);
372 var newProfile
= builder
.build();
374 try (final var streamDetails
= avatar
== null
375 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
376 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
377 accountManager
.setVersionedProfile(account
.getUuid(),
378 account
.getProfileKey(),
379 newProfile
.getInternalServiceName(),
380 newProfile
.getAbout(),
381 newProfile
.getAboutEmoji(),
385 if (avatar
!= null) {
386 if (avatar
.isPresent()) {
387 avatarStore
.storeProfileAvatar(getSelfAddress(),
388 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
390 avatarStore
.deleteProfileAvatar(getSelfAddress());
393 account
.getProfileStore().storeProfile(account
.getSelfRecipientId(), newProfile
);
396 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
397 } catch (UntrustedIdentityException ignored
) {
401 public void unregister() throws IOException
{
402 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
403 // If this is the master device, other users can't send messages to this number anymore.
404 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
405 accountManager
.setGcmId(Optional
.absent());
406 accountManager
.deleteAccount();
408 account
.setRegistered(false);
412 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
413 var devices
= accountManager
.getDevices();
414 account
.setMultiDevice(devices
.size() > 1);
419 public void removeLinkedDevices(int deviceId
) throws IOException
{
420 accountManager
.removeDevice(deviceId
);
421 var devices
= accountManager
.getDevices();
422 account
.setMultiDevice(devices
.size() > 1);
426 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
427 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
429 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
432 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
433 var identityKeyPair
= getIdentityKeyPair();
434 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
436 accountManager
.addDevice(deviceIdentifier
,
439 Optional
.of(account
.getProfileKey().serialize()),
441 account
.setMultiDevice(true);
445 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
446 if (!account
.isMasterDevice()) {
447 throw new RuntimeException("Only master device can set a PIN");
449 if (pin
.isPresent()) {
450 final var masterKey
= account
.getPinMasterKey() != null
451 ? account
.getPinMasterKey()
452 : KeyUtils
.createMasterKey();
454 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
456 account
.setRegistrationLockPin(pin
.get());
457 account
.setPinMasterKey(masterKey
);
459 // Remove legacy registration lock
460 accountManager
.removeRegistrationLockV1();
463 pinHelper
.removeRegistrationLockPin();
465 account
.setRegistrationLockPin(null);
466 account
.setPinMasterKey(null);
471 void refreshPreKeys() throws IOException
{
472 var oneTimePreKeys
= generatePreKeys();
473 final var identityKeyPair
= getIdentityKeyPair();
474 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
476 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
479 private List
<PreKeyRecord
> generatePreKeys() {
480 final var offset
= account
.getPreKeyIdOffset();
482 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
483 account
.addPreKeys(records
);
488 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
489 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
491 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
492 account
.addSignedPreKey(record);
497 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
498 if (messagePipe
== null) {
499 messagePipe
= messageReceiver
.createMessagePipe();
504 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
505 if (unidentifiedMessagePipe
== null) {
506 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
508 return unidentifiedMessagePipe
;
511 private SignalServiceMessageSender
createMessageSender() {
512 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
514 account
.getUsername(),
515 account
.getPassword(),
516 account
.getDeviceId(),
517 account
.getSignalProtocolStore(),
519 account
.isMultiDevice(),
520 Optional
.fromNullable(messagePipe
),
521 Optional
.fromNullable(unidentifiedMessagePipe
),
523 clientZkProfileOperations
,
525 ServiceConfig
.MAX_ENVELOPE_SIZE
,
526 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
529 public Profile
getRecipientProfile(
530 SignalServiceAddress address
532 return getRecipientProfile(resolveRecipient(address
), false);
535 public Profile
getRecipientProfile(
536 RecipientId recipientId
538 return getRecipientProfile(recipientId
, false);
541 private final Set
<RecipientId
> pendingProfileRequest
= new HashSet
<>();
543 Profile
getRecipientProfile(
544 RecipientId recipientId
, boolean force
546 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
547 if (profileKey
== null) {
549 // retrieve profile to get identity key
550 retrieveEncryptedProfile(recipientId
);
554 var profile
= account
.getProfileStore().getProfile(recipientId
);
556 var now
= new Date().getTime();
557 // Profiles are cached for 24h before retrieving them again, unless forced
558 if (!force
&& profile
!= null && now
- profile
.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
562 synchronized (pendingProfileRequest
) {
563 if (pendingProfileRequest
.contains(recipientId
)) {
566 pendingProfileRequest
.add(recipientId
);
568 final SignalServiceProfile encryptedProfile
;
570 encryptedProfile
= retrieveEncryptedProfile(recipientId
);
572 synchronized (pendingProfileRequest
) {
573 pendingProfileRequest
.remove(recipientId
);
576 if (encryptedProfile
== null) {
580 profile
= decryptProfileAndDownloadAvatar(recipientId
, profileKey
, encryptedProfile
);
581 account
.getProfileStore().storeProfile(recipientId
, profile
);
586 private SignalServiceProfile
retrieveEncryptedProfile(RecipientId recipientId
) {
588 return retrieveProfileAndCredential(recipientId
, SignalServiceProfile
.RequestType
.PROFILE
).getProfile();
589 } catch (IOException e
) {
590 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
595 private ProfileAndCredential
retrieveProfileAndCredential(
596 final RecipientId recipientId
, final SignalServiceProfile
.RequestType requestType
597 ) throws IOException
{
598 final var profileAndCredential
= profileHelper
.retrieveProfileSync(recipientId
, requestType
);
599 final var profile
= profileAndCredential
.getProfile();
602 account
.getIdentityKeyStore()
603 .saveIdentity(recipientId
,
604 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
606 } catch (InvalidKeyException ignored
) {
607 logger
.warn("Got invalid identity key in profile for {}",
608 resolveSignalServiceAddress(recipientId
).getLegacyIdentifier());
610 return profileAndCredential
;
613 private ProfileKeyCredential
getRecipientProfileKeyCredential(RecipientId recipientId
) {
614 var profileKeyCredential
= account
.getProfileStore().getProfileKeyCredential(recipientId
);
615 if (profileKeyCredential
!= null) {
616 return profileKeyCredential
;
619 ProfileAndCredential profileAndCredential
;
621 profileAndCredential
= retrieveProfileAndCredential(recipientId
,
622 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
623 } catch (IOException e
) {
624 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
628 profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
629 account
.getProfileStore().storeProfileKeyCredential(recipientId
, profileKeyCredential
);
631 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
632 if (profileKey
!= null) {
633 final var profile
= decryptProfileAndDownloadAvatar(recipientId
,
635 profileAndCredential
.getProfile());
636 account
.getProfileStore().storeProfile(recipientId
, profile
);
639 return profileKeyCredential
;
642 private Profile
decryptProfileAndDownloadAvatar(
643 final RecipientId recipientId
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
645 if (encryptedProfile
.getAvatar() != null) {
646 downloadProfileAvatar(resolveSignalServiceAddress(recipientId
), encryptedProfile
.getAvatar(), profileKey
);
649 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
652 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
653 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
654 if (streamDetails
== null) {
655 return Optional
.absent();
658 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
661 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
662 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
663 if (streamDetails
== null) {
664 return Optional
.absent();
667 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
670 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
671 var g
= getGroup(groupId
);
673 throw new GroupNotFoundException(groupId
);
675 if (!g
.isMember(account
.getSelfAddress())) {
676 throw new NotAGroupMemberException(groupId
, g
.getTitle());
681 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
682 var g
= getGroup(groupId
);
684 throw new GroupNotFoundException(groupId
);
686 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
687 throw new NotAGroupMemberException(groupId
, g
.getTitle());
692 public List
<GroupInfo
> getGroups() {
693 return account
.getGroupStore().getGroups();
696 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
697 String messageText
, List
<String
> attachments
, GroupId groupId
698 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
699 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
700 if (attachments
!= null) {
701 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
704 return sendGroupMessage(messageBuilder
, groupId
);
707 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
708 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
709 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
710 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
712 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
713 targetSentTimestamp
);
714 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
716 return sendGroupMessage(messageBuilder
, groupId
);
719 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
720 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
721 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
722 final var g
= getGroupForSending(groupId
);
724 GroupUtils
.setGroupContext(messageBuilder
, g
);
725 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
727 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
730 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
731 SignalServiceDataMessage
.Builder messageBuilder
;
733 final var g
= getGroupForUpdating(groupId
);
734 if (g
instanceof GroupInfoV1
) {
735 var groupInfoV1
= (GroupInfoV1
) g
;
736 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
737 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
738 groupInfoV1
.removeMember(account
.getSelfAddress());
739 account
.getGroupStore().updateGroup(groupInfoV1
);
741 final var groupInfoV2
= (GroupInfoV2
) g
;
742 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
743 groupInfoV2
.setGroup(groupGroupChangePair
.first());
744 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
745 account
.getGroupStore().updateGroup(groupInfoV2
);
748 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
751 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
752 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
753 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
754 return sendUpdateGroupMessage(groupId
,
758 : getSignalServiceAddresses(members
).stream()
759 .map(this::resolveRecipient
)
760 .collect(Collectors
.toSet()),
764 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
765 GroupId groupId
, String name
, Set
<RecipientId
> members
, File avatarFile
766 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
768 SignalServiceDataMessage
.Builder messageBuilder
;
769 if (groupId
== null) {
771 var gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
772 members
== null ? Set
.of() : members
,
775 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
776 gv1
.addMembers(List
.of(account
.getSelfAddress()));
777 updateGroupV1(gv1
, name
, members
, avatarFile
);
778 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
781 if (avatarFile
!= null) {
782 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
783 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
785 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
789 var group
= getGroupForUpdating(groupId
);
790 if (group
instanceof GroupInfoV2
) {
791 final var groupInfoV2
= (GroupInfoV2
) group
;
793 Pair
<Long
, List
<SendMessageResult
>> result
= null;
794 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
795 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
796 result
= sendUpdateGroupMessage(groupInfoV2
,
797 groupGroupChangePair
.first(),
798 groupGroupChangePair
.second());
801 if (members
!= null) {
802 final var newMembers
= new HashSet
<>(members
);
803 newMembers
.removeAll(group
.getMembers()
805 .map(this::resolveRecipient
)
806 .collect(Collectors
.toSet()));
807 if (newMembers
.size() > 0) {
808 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
809 result
= sendUpdateGroupMessage(groupInfoV2
,
810 groupGroupChangePair
.first(),
811 groupGroupChangePair
.second());
814 if (result
== null || name
!= null || avatarFile
!= null) {
815 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
816 if (avatarFile
!= null) {
817 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
818 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
820 result
= sendUpdateGroupMessage(groupInfoV2
,
821 groupGroupChangePair
.first(),
822 groupGroupChangePair
.second());
825 return new Pair
<>(group
.getGroupId(), result
.second());
827 var gv1
= (GroupInfoV1
) group
;
828 updateGroupV1(gv1
, name
, members
, avatarFile
);
829 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
834 account
.getGroupStore().updateGroup(g
);
836 final var result
= sendMessage(messageBuilder
, g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
837 return new Pair
<>(g
.getGroupId(), result
.second());
840 private void updateGroupV1(
841 final GroupInfoV1 g
, final String name
, final Collection
<RecipientId
> members
, final File avatarFile
842 ) throws IOException
{
847 if (members
!= null) {
848 final var memberAddresses
= members
.stream()
849 .map(this::resolveSignalServiceAddress
)
850 .collect(Collectors
.toList());
851 final var newE164Members
= new HashSet
<String
>();
852 for (var member
: memberAddresses
) {
853 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
856 newE164Members
.add(member
.getNumber().get());
859 final var registeredUsers
= getRegisteredUsers(newE164Members
);
860 if (registeredUsers
.size() != newE164Members
.size()) {
861 // Some of the new members are not registered on Signal
862 newE164Members
.removeAll(registeredUsers
.keySet());
863 throw new IOException("Failed to add members "
864 + String
.join(", ", newE164Members
)
865 + " to group: Not registered on Signal");
868 g
.addMembers(memberAddresses
);
871 if (avatarFile
!= null) {
872 avatarStore
.storeGroupAvatar(g
.getGroupId(),
873 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
877 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
878 GroupInviteLinkUrl inviteLinkUrl
879 ) throws IOException
, GroupLinkNotActiveException
{
880 return sendJoinGroupMessage(inviteLinkUrl
);
883 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
884 GroupInviteLinkUrl inviteLinkUrl
885 ) throws IOException
, GroupLinkNotActiveException
{
886 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
887 inviteLinkUrl
.getPassword());
888 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
889 inviteLinkUrl
.getPassword(),
891 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
892 groupJoinInfo
.getRevision() + 1,
893 groupChange
.toByteArray());
895 if (group
.getGroup() == null) {
896 // Only requested member, can't send update to group members
897 return new Pair
<>(group
.getGroupId(), List
.of());
900 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
902 return new Pair
<>(group
.getGroupId(), result
.second());
905 private static int currentTimeDays() {
906 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
909 private GroupsV2AuthorizationString
getGroupAuthForToday(
910 final GroupSecretParams groupSecretParams
911 ) throws IOException
{
912 final var today
= currentTimeDays();
913 // Returns credentials for the next 7 days
914 final var credentials
= groupsV2Api
.getCredentials(today
);
915 // TODO cache credentials until they expire
916 var authCredentialResponse
= credentials
.get(today
);
918 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
921 authCredentialResponse
);
922 } catch (VerificationFailedException e
) {
923 throw new IOException(e
);
927 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
928 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
929 ) throws IOException
{
930 group
.setGroup(newDecryptedGroup
);
931 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
932 account
.getGroupStore().updateGroup(group
);
933 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
936 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
937 GroupIdV1 groupId
, SignalServiceAddress recipient
938 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
940 var group
= getGroupForSending(groupId
);
941 if (!(group
instanceof GroupInfoV1
)) {
942 throw new RuntimeException("Received an invalid group request for a v2 group!");
944 g
= (GroupInfoV1
) group
;
946 if (!g
.isMember(recipient
)) {
947 throw new NotAGroupMemberException(groupId
, g
.name
);
950 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
952 // Send group message only to the recipient who requested it
953 return sendMessage(messageBuilder
, List
.of(recipient
));
956 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
957 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
958 .withId(g
.getGroupId().serialize())
960 .withMembers(new ArrayList
<>(g
.getMembers()));
963 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
964 if (attachment
.isPresent()) {
965 group
.withAvatar(attachment
.get());
967 } catch (IOException e
) {
968 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
971 return SignalServiceDataMessage
.newBuilder()
972 .asGroupMessage(group
.build())
973 .withExpiration(g
.getMessageExpirationTime());
976 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
977 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
978 .withRevision(g
.getGroup().getRevision())
979 .withSignedGroupChange(signedGroupChange
);
980 return SignalServiceDataMessage
.newBuilder()
981 .asGroupMessage(group
.build())
982 .withExpiration(g
.getMessageExpirationTime());
985 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
986 GroupIdV1 groupId
, SignalServiceAddress recipient
987 ) throws IOException
{
988 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
990 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
992 // Send group info request message to the recipient who sent us a message with this groupId
993 return sendMessage(messageBuilder
, List
.of(recipient
));
997 SignalServiceAddress remoteAddress
, long messageId
998 ) throws IOException
, UntrustedIdentityException
{
999 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
1001 System
.currentTimeMillis());
1003 createMessageSender().sendReceipt(remoteAddress
,
1004 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(remoteAddress
)),
1008 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1009 String messageText
, List
<String
> attachments
, List
<String
> recipients
1010 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
1011 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1012 if (attachments
!= null) {
1013 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
1015 // Upload attachments here, so we only upload once even for multiple recipients
1016 var messageSender
= createMessageSender();
1017 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
1018 for (var attachment
: attachmentStreams
) {
1019 if (attachment
.isStream()) {
1020 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
1021 } else if (attachment
.isPointer()) {
1022 attachmentPointers
.add(attachment
.asPointer());
1026 messageBuilder
.withAttachments(attachmentPointers
);
1028 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1031 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1032 String messageText
, List
<String
> attachments
1033 ) throws IOException
, AttachmentInvalidException
{
1034 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1035 if (attachments
!= null) {
1036 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1038 return sendSelfMessage(messageBuilder
);
1041 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1042 long targetSentTimestamp
, List
<String
> recipients
1043 ) throws IOException
, InvalidNumberException
{
1044 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1045 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1046 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1049 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1050 long targetSentTimestamp
, GroupId groupId
1051 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1052 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1053 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1054 return sendGroupMessage(messageBuilder
, groupId
);
1057 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1058 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1059 ) throws IOException
, InvalidNumberException
{
1060 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1062 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1063 targetSentTimestamp
);
1064 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1065 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1068 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1069 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1071 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1073 return sendMessage(messageBuilder
, signalServiceAddresses
);
1074 } catch (Exception e
) {
1075 for (var address
: signalServiceAddresses
) {
1076 handleEndSession(address
);
1083 public String
getContactName(String number
) throws InvalidNumberException
{
1084 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveRecipient(number
));
1085 return contact
== null || contact
.getName() == null ?
"" : contact
.getName();
1088 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1089 final var recipientId
= canonicalizeAndResolveRecipient(number
);
1090 var contact
= account
.getContactStore().getContact(recipientId
);
1091 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1092 account
.getContactStore().storeContact(recipientId
, builder
.withName(name
).build());
1096 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1097 setContactBlocked(canonicalizeAndResolveRecipient(number
), blocked
);
1100 private void setContactBlocked(RecipientId recipientId
, boolean blocked
) {
1101 var contact
= account
.getContactStore().getContact(recipientId
);
1102 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1103 account
.getContactStore().storeContact(recipientId
, builder
.withBlocked(blocked
).build());
1107 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1108 var group
= getGroup(groupId
);
1109 if (group
== null) {
1110 throw new GroupNotFoundException(groupId
);
1113 group
.setBlocked(blocked
);
1114 account
.getGroupStore().updateGroup(group
);
1118 private void setExpirationTimer(RecipientId recipientId
, int messageExpirationTimer
) {
1119 var contact
= account
.getContactStore().getContact(recipientId
);
1120 if (contact
!= null && contact
.getMessageExpirationTime() == messageExpirationTimer
) {
1123 final var builder
= contact
== null ? Contact
.newBuilder() : Contact
.newBuilder(contact
);
1124 account
.getContactStore()
1125 .storeContact(recipientId
, builder
.withMessageExpirationTime(messageExpirationTimer
).build());
1128 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1129 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1130 sendMessage(messageBuilder
, List
.of(address
));
1134 * Change the expiration timer for a contact
1136 public void setExpirationTimer(
1137 String number
, int messageExpirationTimer
1138 ) throws IOException
, InvalidNumberException
{
1139 var recipientId
= canonicalizeAndResolveRecipient(number
);
1140 setExpirationTimer(recipientId
, messageExpirationTimer
);
1141 sendExpirationTimerUpdate(resolveSignalServiceAddress(recipientId
));
1146 * Change the expiration timer for a group
1148 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1149 var g
= getGroup(groupId
);
1150 if (g
instanceof GroupInfoV1
) {
1151 var groupInfoV1
= (GroupInfoV1
) g
;
1152 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1153 account
.getGroupStore().updateGroup(groupInfoV1
);
1155 throw new RuntimeException("TODO Not implemented!");
1160 * Upload the sticker pack from path.
1162 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1163 * @return if successful, returns the URL to install the sticker pack in the signal app
1165 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1166 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1168 var messageSender
= createMessageSender();
1170 var packKey
= KeyUtils
.createStickerUploadKey();
1171 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1173 var sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1174 account
.getStickerStore().updateSticker(sticker
);
1178 return new URI("https",
1181 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1182 Hex
.toStringCondensed(packKey
),
1183 StandardCharsets
.UTF_8
)).toString();
1184 } catch (URISyntaxException e
) {
1185 throw new AssertionError(e
);
1189 void requestSyncGroups() throws IOException
{
1190 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1191 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1193 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1195 sendSyncMessage(message
);
1196 } catch (UntrustedIdentityException e
) {
1197 throw new AssertionError(e
);
1201 void requestSyncContacts() throws IOException
{
1202 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1203 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1205 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1207 sendSyncMessage(message
);
1208 } catch (UntrustedIdentityException e
) {
1209 throw new AssertionError(e
);
1213 void requestSyncBlocked() throws IOException
{
1214 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1215 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1217 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1219 sendSyncMessage(message
);
1220 } catch (UntrustedIdentityException e
) {
1221 throw new AssertionError(e
);
1225 void requestSyncConfiguration() throws IOException
{
1226 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1227 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1229 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1231 sendSyncMessage(message
);
1232 } catch (UntrustedIdentityException e
) {
1233 throw new AssertionError(e
);
1237 void requestSyncKeys() throws IOException
{
1238 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1239 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1241 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1243 sendSyncMessage(message
);
1244 } catch (UntrustedIdentityException e
) {
1245 throw new AssertionError(e
);
1249 private byte[] getSenderCertificate() {
1250 // TODO support UUID capable sender certificates
1251 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1254 certificate
= accountManager
.getSenderCertificate();
1255 } catch (IOException e
) {
1256 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1259 // TODO cache for a day
1263 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1264 var messageSender
= createMessageSender();
1265 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1268 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1269 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1270 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1272 for (var number
: numbers
) {
1273 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1274 if (resolvedAddress
.getUuid().isPresent()) {
1275 signalServiceAddresses
.add(resolvedAddress
);
1277 addressesMissingUuid
.add(resolvedAddress
);
1281 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1282 .map(a
-> a
.getNumber().get())
1283 .collect(Collectors
.toSet());
1284 Map
<String
, UUID
> registeredUsers
;
1286 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1287 } catch (IOException e
) {
1288 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1289 registeredUsers
= Map
.of();
1292 for (var address
: addressesMissingUuid
) {
1293 final var number
= address
.getNumber().get();
1294 if (registeredUsers
.containsKey(number
)) {
1295 final var newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(registeredUsers
.get(number
),
1297 signalServiceAddresses
.add(newAddress
);
1299 signalServiceAddresses
.add(address
);
1303 return signalServiceAddresses
;
1306 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1308 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1310 serviceEnvironmentConfig
.getCdsMrenclave());
1311 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1312 throw new IOException(e
);
1316 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1317 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1318 ) throws IOException
{
1319 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1320 final var recipientIds
= recipients
.stream().map(this::resolveRecipient
).collect(Collectors
.toSet());
1321 final var timestamp
= System
.currentTimeMillis();
1322 messageBuilder
.withTimestamp(timestamp
);
1323 getOrCreateMessagePipe();
1324 getOrCreateUnidentifiedMessagePipe();
1325 SignalServiceDataMessage message
= null;
1327 message
= messageBuilder
.build();
1328 if (message
.getGroupContext().isPresent()) {
1330 var messageSender
= createMessageSender();
1331 final var isRecipientUpdate
= false;
1332 var result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1333 unidentifiedAccessHelper
.getAccessFor(recipientIds
),
1337 for (var r
: result
) {
1338 if (r
.getIdentityFailure() != null) {
1339 account
.getIdentityKeyStore().
1340 saveIdentity(resolveRecipient(r
.getAddress()),
1341 r
.getIdentityFailure().getIdentityKey(),
1346 return new Pair
<>(timestamp
, result
);
1347 } catch (UntrustedIdentityException e
) {
1348 return new Pair
<>(timestamp
, List
.of());
1351 // Send to all individually, so sync messages are sent correctly
1352 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1353 var results
= new ArrayList
<SendMessageResult
>(recipients
.size());
1354 for (var address
: recipients
) {
1355 final var contact
= account
.getContactStore().getContact(resolveRecipient(address
));
1356 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1357 messageBuilder
.withExpiration(expirationTime
);
1358 message
= messageBuilder
.build();
1359 results
.add(sendMessage(address
, message
));
1361 return new Pair
<>(timestamp
, results
);
1364 if (message
!= null && message
.isEndSession()) {
1365 for (var recipient
: recipients
) {
1366 handleEndSession(recipient
);
1373 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1374 SignalServiceDataMessage
.Builder messageBuilder
1375 ) throws IOException
{
1376 final var timestamp
= System
.currentTimeMillis();
1377 messageBuilder
.withTimestamp(timestamp
);
1378 getOrCreateMessagePipe();
1379 getOrCreateUnidentifiedMessagePipe();
1381 final var recipientId
= account
.getSelfRecipientId();
1383 final var contact
= account
.getContactStore().getContact(recipientId
);
1384 final var expirationTime
= contact
!= null ? contact
.getMessageExpirationTime() : 0;
1385 messageBuilder
.withExpiration(expirationTime
);
1387 var message
= messageBuilder
.build();
1388 final var result
= sendSelfMessage(message
);
1389 return new Pair
<>(timestamp
, result
);
1395 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1396 var messageSender
= createMessageSender();
1398 var recipient
= account
.getSelfAddress();
1400 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(resolveRecipient(recipient
));
1401 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1402 message
.getTimestamp(),
1404 message
.getExpiresInSeconds(),
1405 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1407 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1410 var startTime
= System
.currentTimeMillis();
1411 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1412 return SendMessageResult
.success(recipient
,
1413 unidentifiedAccess
.isPresent(),
1415 System
.currentTimeMillis() - startTime
);
1416 } catch (UntrustedIdentityException e
) {
1417 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1421 private SendMessageResult
sendMessage(
1422 SignalServiceAddress address
, SignalServiceDataMessage message
1423 ) throws IOException
{
1424 var messageSender
= createMessageSender();
1427 return messageSender
.sendMessage(address
,
1428 unidentifiedAccessHelper
.getAccessFor(resolveRecipient(address
)),
1430 } catch (UntrustedIdentityException e
) {
1431 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1435 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1436 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1437 account
.getSignalProtocolStore(),
1438 certificateValidator
);
1440 return cipher
.decrypt(envelope
);
1441 } catch (ProtocolUntrustedIdentityException e
) {
1442 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1443 throw (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1445 throw new AssertionError(e
);
1449 private void handleEndSession(SignalServiceAddress source
) {
1450 account
.getSessionStore().deleteAllSessions(source
.getIdentifier());
1453 private List
<HandleAction
> handleSignalServiceDataMessage(
1454 SignalServiceDataMessage message
,
1456 SignalServiceAddress source
,
1457 SignalServiceAddress destination
,
1458 boolean ignoreAttachments
1460 var actions
= new ArrayList
<HandleAction
>();
1461 if (message
.getGroupContext().isPresent()) {
1462 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1463 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1464 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1465 var group
= getGroup(groupId
);
1466 if (group
== null || group
instanceof GroupInfoV1
) {
1467 var groupV1
= (GroupInfoV1
) group
;
1468 switch (groupInfo
.getType()) {
1470 if (groupV1
== null) {
1471 groupV1
= new GroupInfoV1(groupId
);
1474 if (groupInfo
.getAvatar().isPresent()) {
1475 var avatar
= groupInfo
.getAvatar().get();
1476 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1479 if (groupInfo
.getName().isPresent()) {
1480 groupV1
.name
= groupInfo
.getName().get();
1483 if (groupInfo
.getMembers().isPresent()) {
1484 groupV1
.addMembers(groupInfo
.getMembers()
1487 .map(this::resolveSignalServiceAddress
)
1488 .collect(Collectors
.toSet()));
1491 account
.getGroupStore().updateGroup(groupV1
);
1495 if (groupV1
== null && !isSync
) {
1496 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1500 if (groupV1
!= null) {
1501 groupV1
.removeMember(source
);
1502 account
.getGroupStore().updateGroup(groupV1
);
1507 if (groupV1
!= null && !isSync
) {
1508 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1513 // Received a group v1 message for a v2 group
1516 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1517 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1518 final var groupMasterKey
= groupContext
.getMasterKey();
1520 getOrMigrateGroup(groupMasterKey
,
1521 groupContext
.getRevision(),
1522 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1526 final var conversationPartnerAddress
= isSync ? destination
: source
;
1527 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1528 handleEndSession(conversationPartnerAddress
);
1530 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1531 if (message
.getGroupContext().isPresent()) {
1532 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1533 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1534 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1535 if (group
!= null) {
1536 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1537 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1538 account
.getGroupStore().updateGroup(group
);
1541 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1542 // disappearing message timer already stored in the DecryptedGroup
1544 } else if (conversationPartnerAddress
!= null) {
1545 setExpirationTimer(resolveRecipient(conversationPartnerAddress
), message
.getExpiresInSeconds());
1548 if (!ignoreAttachments
) {
1549 if (message
.getAttachments().isPresent()) {
1550 for (var attachment
: message
.getAttachments().get()) {
1551 downloadAttachment(attachment
);
1554 if (message
.getSharedContacts().isPresent()) {
1555 for (var contact
: message
.getSharedContacts().get()) {
1556 if (contact
.getAvatar().isPresent()) {
1557 downloadAttachment(contact
.getAvatar().get().getAttachment());
1562 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1563 final ProfileKey profileKey
;
1565 profileKey
= new ProfileKey(message
.getProfileKey().get());
1566 } catch (InvalidInputException e
) {
1567 throw new AssertionError(e
);
1569 if (source
.matches(account
.getSelfAddress())) {
1570 this.account
.setProfileKey(profileKey
);
1572 this.account
.getProfileStore().storeProfileKey(resolveRecipient(source
), profileKey
);
1574 if (message
.getPreviews().isPresent()) {
1575 final var previews
= message
.getPreviews().get();
1576 for (var preview
: previews
) {
1577 if (preview
.getImage().isPresent()) {
1578 downloadAttachment(preview
.getImage().get());
1582 if (message
.getQuote().isPresent()) {
1583 final var quote
= message
.getQuote().get();
1585 for (var quotedAttachment
: quote
.getAttachments()) {
1586 final var thumbnail
= quotedAttachment
.getThumbnail();
1587 if (thumbnail
!= null) {
1588 downloadAttachment(thumbnail
);
1592 if (message
.getSticker().isPresent()) {
1593 final var messageSticker
= message
.getSticker().get();
1594 var sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1595 if (sticker
== null) {
1596 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1597 account
.getStickerStore().updateSticker(sticker
);
1603 private GroupInfoV2
getOrMigrateGroup(
1604 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1606 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1608 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1609 var groupInfo
= getGroup(groupId
);
1610 final GroupInfoV2 groupInfoV2
;
1611 if (groupInfo
instanceof GroupInfoV1
) {
1612 // Received a v2 group message for a v1 group, we need to locally migrate the group
1613 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1614 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1615 logger
.info("Locally migrated group {} to group v2, id: {}",
1616 groupInfo
.getGroupId().toBase64(),
1617 groupInfoV2
.getGroupId().toBase64());
1618 } else if (groupInfo
instanceof GroupInfoV2
) {
1619 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1621 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1624 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1625 DecryptedGroup group
= null;
1626 if (signedGroupChange
!= null
1627 && groupInfoV2
.getGroup() != null
1628 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1629 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1631 if (group
== null) {
1632 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1634 if (group
!= null) {
1635 storeProfileKeysFromMembers(group
);
1636 final var avatar
= group
.getAvatar();
1637 if (avatar
!= null && !avatar
.isEmpty()) {
1638 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1641 groupInfoV2
.setGroup(group
);
1642 account
.getGroupStore().updateGroup(groupInfoV2
);
1648 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1649 for (var member
: group
.getMembersList()) {
1650 final var address
= resolveRecipient(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1651 .toByteArray()), null));
1653 account
.getProfileStore()
1654 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1655 } catch (InvalidInputException ignored
) {
1660 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1661 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1662 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1663 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1664 if (actions
!= null) {
1665 queuedActions
.addAll(actions
);
1668 for (var action
: queuedActions
) {
1670 action
.execute(this);
1671 } catch (Throwable e
) {
1672 logger
.warn("Message action failed.", e
);
1677 private List
<HandleAction
> retryFailedReceivedMessage(
1678 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1680 var envelope
= cachedMessage
.loadEnvelope();
1681 if (envelope
== null) {
1684 SignalServiceContent content
= null;
1685 List
<HandleAction
> actions
= null;
1686 if (!envelope
.isReceipt()) {
1688 content
= decryptMessage(envelope
);
1689 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1690 if (!envelope
.hasSource()) {
1691 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
)
1694 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1695 } catch (IOException ioException
) {
1696 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1700 } catch (Exception er
) {
1701 // All other errors are not recoverable, so delete the cached message
1702 cachedMessage
.delete();
1705 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1708 handler
.handleMessage(envelope
, content
, null);
1709 cachedMessage
.delete();
1713 public void receiveMessages(
1716 boolean returnOnTimeout
,
1717 boolean ignoreAttachments
,
1718 ReceiveMessageHandler handler
1719 ) throws IOException
{
1720 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1722 Set
<HandleAction
> queuedActions
= null;
1724 final var messagePipe
= getOrCreateMessagePipe();
1726 var hasCaughtUpWithOldMessages
= false;
1729 SignalServiceEnvelope envelope
;
1730 SignalServiceContent content
= null;
1731 Exception exception
= null;
1732 final CachedMessage
[] cachedMessage
= {null};
1734 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1735 final var recipientId
= envelope1
.hasSource()
1736 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1738 // store message on disk, before acknowledging receipt to the server
1739 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1741 if (result
.isPresent()) {
1742 envelope
= result
.get();
1744 // Received indicator that server queue is empty
1745 hasCaughtUpWithOldMessages
= true;
1747 if (queuedActions
!= null) {
1748 for (var action
: queuedActions
) {
1750 action
.execute(this);
1751 } catch (Throwable e
) {
1752 logger
.warn("Message action failed.", e
);
1756 queuedActions
.clear();
1757 queuedActions
= null;
1760 // Continue to wait another timeout for new messages
1763 } catch (TimeoutException e
) {
1764 if (returnOnTimeout
) return;
1768 if (envelope
.hasSource()) {
1769 // Store uuid if we don't have it already
1770 resolveRecipientTrusted(envelope
.getSourceAddress());
1772 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1773 if (!envelope
.isReceipt()) {
1775 content
= decryptMessage(envelope
);
1776 } catch (Exception e
) {
1779 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1780 if (hasCaughtUpWithOldMessages
) {
1781 for (var action
: actions
) {
1783 action
.execute(this);
1784 } catch (Throwable e
) {
1785 logger
.warn("Message action failed.", e
);
1789 if (queuedActions
== null) {
1790 queuedActions
= new HashSet
<>();
1792 queuedActions
.addAll(actions
);
1796 if (isMessageBlocked(envelope
, content
)) {
1797 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1798 } else if (notAGroupMember
) {
1799 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1801 handler
.handleMessage(envelope
, content
, exception
);
1803 if (cachedMessage
[0] != null) {
1804 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1805 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
)
1807 queuedActions
.add(new RetrieveProfileAction(recipientId
));
1808 if (!envelope
.hasSource()) {
1810 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1811 } catch (IOException ioException
) {
1812 logger
.warn("Failed to move cached message to recipient folder: {}",
1813 ioException
.getMessage());
1817 cachedMessage
[0].delete();
1823 private boolean isMessageBlocked(
1824 SignalServiceEnvelope envelope
, SignalServiceContent content
1826 SignalServiceAddress source
;
1827 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1828 source
= envelope
.getSourceAddress();
1829 } else if (content
!= null) {
1830 source
= content
.getSender();
1834 final var recipientId
= resolveRecipient(source
);
1835 if (isContactBlocked(recipientId
)) {
1839 if (content
!= null && content
.getDataMessage().isPresent()) {
1840 var message
= content
.getDataMessage().get();
1841 if (message
.getGroupContext().isPresent()) {
1842 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1843 var group
= getGroup(groupId
);
1844 if (group
!= null && group
.isBlocked()) {
1852 public boolean isContactBlocked(final String identifier
) throws InvalidNumberException
{
1853 final var recipientId
= canonicalizeAndResolveRecipient(identifier
);
1854 return isContactBlocked(recipientId
);
1857 private boolean isContactBlocked(final RecipientId recipientId
) {
1858 var sourceContact
= account
.getContactStore().getContact(recipientId
);
1859 return sourceContact
!= null && sourceContact
.isBlocked();
1862 private boolean isNotAGroupMember(
1863 SignalServiceEnvelope envelope
, SignalServiceContent content
1865 SignalServiceAddress source
;
1866 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1867 source
= envelope
.getSourceAddress();
1868 } else if (content
!= null) {
1869 source
= content
.getSender();
1874 if (content
!= null && content
.getDataMessage().isPresent()) {
1875 var message
= content
.getDataMessage().get();
1876 if (message
.getGroupContext().isPresent()) {
1877 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1878 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1879 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1883 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1884 var group
= getGroup(groupId
);
1885 if (group
!= null && !group
.isMember(source
)) {
1893 private List
<HandleAction
> handleMessage(
1894 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1896 var actions
= new ArrayList
<HandleAction
>();
1897 if (content
!= null) {
1898 final SignalServiceAddress sender
;
1899 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1900 sender
= envelope
.getSourceAddress();
1902 sender
= content
.getSender();
1905 if (content
.getDataMessage().isPresent()) {
1906 var message
= content
.getDataMessage().get();
1908 if (content
.isNeedsReceipt()) {
1909 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1912 actions
.addAll(handleSignalServiceDataMessage(message
,
1915 account
.getSelfAddress(),
1916 ignoreAttachments
));
1918 if (content
.getSyncMessage().isPresent()) {
1919 account
.setMultiDevice(true);
1920 var syncMessage
= content
.getSyncMessage().get();
1921 if (syncMessage
.getSent().isPresent()) {
1922 var message
= syncMessage
.getSent().get();
1923 final var destination
= message
.getDestination().orNull();
1924 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1928 ignoreAttachments
));
1930 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
1931 var rm
= syncMessage
.getRequest().get();
1932 if (rm
.isContactsRequest()) {
1933 actions
.add(SendSyncContactsAction
.create());
1935 if (rm
.isGroupsRequest()) {
1936 actions
.add(SendSyncGroupsAction
.create());
1938 if (rm
.isBlockedListRequest()) {
1939 actions
.add(SendSyncBlockedListAction
.create());
1941 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1943 if (syncMessage
.getGroups().isPresent()) {
1944 File tmpFile
= null;
1946 tmpFile
= IOUtils
.createTempFile();
1947 final var groupsMessage
= syncMessage
.getGroups().get();
1948 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1949 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1951 while ((g
= s
.read()) != null) {
1952 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1953 if (syncGroup
!= null) {
1954 if (g
.getName().isPresent()) {
1955 syncGroup
.name
= g
.getName().get();
1957 syncGroup
.addMembers(g
.getMembers()
1959 .map(this::resolveSignalServiceAddress
)
1960 .collect(Collectors
.toSet()));
1961 if (!g
.isActive()) {
1962 syncGroup
.removeMember(account
.getSelfAddress());
1964 // Add ourself to the member set as it's marked as active
1965 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1967 syncGroup
.blocked
= g
.isBlocked();
1968 if (g
.getColor().isPresent()) {
1969 syncGroup
.color
= g
.getColor().get();
1972 if (g
.getAvatar().isPresent()) {
1973 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1975 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1976 syncGroup
.archived
= g
.isArchived();
1977 account
.getGroupStore().updateGroup(syncGroup
);
1981 } catch (Exception e
) {
1982 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1986 if (tmpFile
!= null) {
1988 Files
.delete(tmpFile
.toPath());
1989 } catch (IOException e
) {
1990 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1997 if (syncMessage
.getBlockedList().isPresent()) {
1998 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1999 for (var address
: blockedListMessage
.getAddresses()) {
2000 setContactBlocked(resolveRecipient(address
), true);
2002 for (var groupId
: blockedListMessage
.getGroupIds()
2004 .map(GroupId
::unknownVersion
)
2005 .collect(Collectors
.toSet())) {
2007 setGroupBlocked(groupId
, true);
2008 } catch (GroupNotFoundException e
) {
2009 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2010 groupId
.toBase64());
2014 if (syncMessage
.getContacts().isPresent()) {
2015 File tmpFile
= null;
2017 tmpFile
= IOUtils
.createTempFile();
2018 final var contactsMessage
= syncMessage
.getContacts().get();
2019 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
2020 .asPointer(), tmpFile
)) {
2021 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2023 while ((c
= s
.read()) != null) {
2024 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2025 account
.setProfileKey(c
.getProfileKey().get());
2027 final var recipientId
= resolveRecipientTrusted(c
.getAddress());
2028 var contact
= account
.getContactStore().getContact(recipientId
);
2029 final var builder
= contact
== null
2030 ? Contact
.newBuilder()
2031 : Contact
.newBuilder(contact
);
2032 if (c
.getName().isPresent()) {
2033 builder
.withName(c
.getName().get());
2035 if (c
.getColor().isPresent()) {
2036 builder
.withColor(c
.getColor().get());
2038 if (c
.getProfileKey().isPresent()) {
2039 account
.getProfileStore().storeProfileKey(recipientId
, c
.getProfileKey().get());
2041 if (c
.getVerified().isPresent()) {
2042 final var verifiedMessage
= c
.getVerified().get();
2043 account
.getIdentityKeyStore()
2044 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2045 verifiedMessage
.getIdentityKey(),
2046 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2048 if (c
.getExpirationTimer().isPresent()) {
2049 builder
.withMessageExpirationTime(c
.getExpirationTimer().get());
2051 builder
.withBlocked(c
.isBlocked());
2052 builder
.withArchived(c
.isArchived());
2053 account
.getContactStore().storeContact(recipientId
, builder
.build());
2055 if (c
.getAvatar().isPresent()) {
2056 downloadContactAvatar(c
.getAvatar().get(), c
.getAddress());
2060 } catch (Exception e
) {
2061 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2065 if (tmpFile
!= null) {
2067 Files
.delete(tmpFile
.toPath());
2068 } catch (IOException e
) {
2069 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2076 if (syncMessage
.getVerified().isPresent()) {
2077 final var verifiedMessage
= syncMessage
.getVerified().get();
2078 account
.getIdentityKeyStore()
2079 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2080 verifiedMessage
.getIdentityKey(),
2081 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2083 if (syncMessage
.getStickerPackOperations().isPresent()) {
2084 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2085 for (var m
: stickerPackOperationMessages
) {
2086 if (!m
.getPackId().isPresent()) {
2089 var sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2090 if (sticker
== null) {
2091 if (!m
.getPackKey().isPresent()) {
2094 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2096 sticker
.setInstalled(!m
.getType().isPresent()
2097 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2098 account
.getStickerStore().updateSticker(sticker
);
2101 if (syncMessage
.getFetchType().isPresent()) {
2102 switch (syncMessage
.getFetchType().get()) {
2104 getRecipientProfile(account
.getSelfRecipientId(), true);
2105 case STORAGE_MANIFEST
:
2109 if (syncMessage
.getKeys().isPresent()) {
2110 final var keysMessage
= syncMessage
.getKeys().get();
2111 if (keysMessage
.getStorageService().isPresent()) {
2112 final var storageKey
= keysMessage
.getStorageService().get();
2113 account
.setStorageKey(storageKey
);
2116 if (syncMessage
.getConfiguration().isPresent()) {
2124 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2126 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2127 } catch (IOException e
) {
2128 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2132 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2134 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2135 } catch (IOException e
) {
2136 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2140 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2142 avatarStore
.storeGroupAvatar(groupId
,
2143 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2144 } catch (IOException e
) {
2145 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2149 private void downloadProfileAvatar(
2150 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2153 avatarStore
.storeProfileAvatar(address
,
2154 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2155 } catch (Throwable e
) {
2156 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2160 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2161 return attachmentStore
.getAttachmentFile(attachmentId
);
2164 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2165 if (!attachment
.isPointer()) {
2166 logger
.warn("Invalid state, can't store an attachment stream.");
2169 var pointer
= attachment
.asPointer();
2170 if (pointer
.getPreview().isPresent()) {
2171 final var preview
= pointer
.getPreview().get();
2173 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2174 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2175 } catch (IOException e
) {
2176 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2181 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2182 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2183 } catch (IOException e
) {
2184 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2188 private void retrieveGroupV2Avatar(
2189 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2190 ) throws IOException
{
2191 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2193 var tmpFile
= IOUtils
.createTempFile();
2194 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2196 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2197 var encryptedData
= IOUtils
.readFully(input
);
2199 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2200 outputStream
.write(decryptedData
);
2203 Files
.delete(tmpFile
.toPath());
2204 } catch (IOException e
) {
2205 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2212 private void retrieveProfileAvatar(
2213 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2214 ) throws IOException
{
2215 var tmpFile
= IOUtils
.createTempFile();
2216 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2219 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2220 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2221 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2224 Files
.delete(tmpFile
.toPath());
2225 } catch (IOException e
) {
2226 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2233 private void retrieveAttachment(
2234 final SignalServiceAttachment attachment
, final OutputStream outputStream
2235 ) throws IOException
{
2236 if (attachment
.isPointer()) {
2237 var pointer
= attachment
.asPointer();
2238 retrieveAttachmentPointer(pointer
, outputStream
);
2240 var stream
= attachment
.asStream();
2241 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2245 private void retrieveAttachmentPointer(
2246 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2247 ) throws IOException
{
2248 var tmpFile
= IOUtils
.createTempFile();
2249 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2250 IOUtils
.copyStream(input
, outputStream
);
2251 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2252 throw new IOException(e
);
2255 Files
.delete(tmpFile
.toPath());
2256 } catch (IOException e
) {
2257 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2264 private InputStream
retrieveAttachmentAsStream(
2265 SignalServiceAttachmentPointer pointer
, File tmpFile
2266 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2267 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2270 void sendGroups() throws IOException
, UntrustedIdentityException
{
2271 var groupsFile
= IOUtils
.createTempFile();
2274 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2275 var out
= new DeviceGroupsOutputStream(fos
);
2276 for (var record : getGroups()) {
2277 if (record instanceof GroupInfoV1
) {
2278 var groupInfo
= (GroupInfoV1
) record;
2279 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2280 Optional
.fromNullable(groupInfo
.name
),
2281 new ArrayList
<>(groupInfo
.getMembers()),
2282 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2283 groupInfo
.isMember(account
.getSelfAddress()),
2284 Optional
.of(groupInfo
.messageExpirationTime
),
2285 Optional
.fromNullable(groupInfo
.color
),
2287 Optional
.fromNullable(groupInfo
.inboxPosition
),
2288 groupInfo
.archived
));
2293 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2294 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2295 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2296 .withStream(groupsFileStream
)
2297 .withContentType("application/octet-stream")
2298 .withLength(groupsFile
.length())
2301 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2306 Files
.delete(groupsFile
.toPath());
2307 } catch (IOException e
) {
2308 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2313 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2314 var contactsFile
= IOUtils
.createTempFile();
2317 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2318 var out
= new DeviceContactsOutputStream(fos
);
2319 for (var contactPair
: account
.getContactStore().getContacts()) {
2320 final var recipientId
= contactPair
.first();
2321 final var contact
= contactPair
.second();
2322 final var address
= resolveSignalServiceAddress(recipientId
);
2324 var currentIdentity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2325 VerifiedMessage verifiedMessage
= null;
2326 if (currentIdentity
!= null) {
2327 verifiedMessage
= new VerifiedMessage(address
,
2328 currentIdentity
.getIdentityKey(),
2329 currentIdentity
.getTrustLevel().toVerifiedState(),
2330 currentIdentity
.getDateAdded().getTime());
2333 var profileKey
= account
.getProfileStore().getProfileKey(recipientId
);
2334 out
.write(new DeviceContact(address
,
2335 Optional
.fromNullable(contact
.getName()),
2336 createContactAvatarAttachment(address
),
2337 Optional
.fromNullable(contact
.getColor()),
2338 Optional
.fromNullable(verifiedMessage
),
2339 Optional
.fromNullable(profileKey
),
2340 contact
.isBlocked(),
2341 Optional
.of(contact
.getMessageExpirationTime()),
2343 contact
.isArchived()));
2346 if (account
.getProfileKey() != null) {
2347 // Send our own profile key as well
2348 out
.write(new DeviceContact(account
.getSelfAddress(),
2353 Optional
.of(account
.getProfileKey()),
2361 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2362 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2363 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2364 .withStream(contactsFileStream
)
2365 .withContentType("application/octet-stream")
2366 .withLength(contactsFile
.length())
2369 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2374 Files
.delete(contactsFile
.toPath());
2375 } catch (IOException e
) {
2376 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2381 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2382 var addresses
= new ArrayList
<SignalServiceAddress
>();
2383 for (var record : account
.getContactStore().getContacts()) {
2384 if (record.second().isBlocked()) {
2385 addresses
.add(resolveSignalServiceAddress(record.first()));
2388 var groupIds
= new ArrayList
<byte[]>();
2389 for (var record : getGroups()) {
2390 if (record.isBlocked()) {
2391 groupIds
.add(record.getGroupId().serialize());
2394 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2397 private void sendVerifiedMessage(
2398 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2399 ) throws IOException
, UntrustedIdentityException
{
2400 var verifiedMessage
= new VerifiedMessage(destination
,
2402 trustLevel
.toVerifiedState(),
2403 System
.currentTimeMillis());
2404 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2407 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
2408 return account
.getContactStore().getContacts();
2411 public String
getContactOrProfileName(String number
) throws InvalidNumberException
{
2412 final var recipientId
= canonicalizeAndResolveRecipient(number
);
2413 final var recipient
= account
.getRecipientStore().getRecipient(recipientId
);
2414 if (recipient
== null) {
2418 if (recipient
.getContact() != null && !Util
.isEmpty(recipient
.getContact().getName())) {
2419 return recipient
.getContact().getName();
2422 if (recipient
.getProfile() != null && recipient
.getProfile() != null) {
2423 return recipient
.getProfile().getDisplayName();
2429 public GroupInfo
getGroup(GroupId groupId
) {
2430 final var group
= account
.getGroupStore().getGroup(groupId
);
2431 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2432 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2433 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2434 account
.getGroupStore().updateGroup(group
);
2439 public List
<IdentityInfo
> getIdentities() {
2440 return account
.getIdentityKeyStore().getIdentities();
2443 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2444 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2445 return identity
== null ? List
.of() : List
.of(identity
);
2449 * Trust this the identity with this fingerprint
2451 * @param name username of the identity
2452 * @param fingerprint Fingerprint
2454 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2455 var recipientId
= canonicalizeAndResolveRecipient(name
);
2456 return trustIdentity(recipientId
,
2457 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2458 TrustLevel
.TRUSTED_VERIFIED
);
2462 * Trust this the identity with this safety number
2464 * @param name username of the identity
2465 * @param safetyNumber Safety number
2467 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2468 var recipientId
= canonicalizeAndResolveRecipient(name
);
2469 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2470 return trustIdentity(recipientId
,
2471 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2472 TrustLevel
.TRUSTED_VERIFIED
);
2476 * Trust all keys of this identity without verification
2478 * @param name username of the identity
2480 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2481 var recipientId
= canonicalizeAndResolveRecipient(name
);
2482 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2485 private boolean trustIdentity(
2486 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2488 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2489 if (identity
== null) {
2493 if (!verifier
.apply(identity
.getIdentityKey())) {
2497 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2499 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2500 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2501 } catch (IOException
| UntrustedIdentityException e
) {
2502 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2508 public String
computeSafetyNumber(
2509 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2511 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2512 account
.getSelfAddress(),
2513 getIdentityKeyPair().getPublicKey(),
2519 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2520 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2522 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2523 return resolveSignalServiceAddress(canonicalizedNumber
);
2527 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2528 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2530 return resolveSignalServiceAddress(address
);
2534 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2535 if (address
.matches(account
.getSelfAddress())) {
2536 return account
.getSelfAddress();
2539 return account
.getRecipientStore().resolveServiceAddress(address
);
2542 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2543 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2546 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2547 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2549 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2551 return resolveRecipient(canonicalizedNumber
);
2554 private RecipientId
resolveRecipient(final String identifier
) {
2555 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2557 return resolveRecipient(address
);
2560 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2561 return account
.getRecipientStore().resolveRecipient(address
);
2564 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2565 return account
.getRecipientStore().resolveRecipientTrusted(address
);
2569 public void close() throws IOException
{
2573 void close(boolean closeAccount
) throws IOException
{
2574 executor
.shutdown();
2576 if (messagePipe
!= null) {
2577 messagePipe
.shutdown();
2581 if (unidentifiedMessagePipe
!= null) {
2582 unidentifiedMessagePipe
.shutdown();
2583 unidentifiedMessagePipe
= null;
2586 if (closeAccount
&& account
!= null) {
2592 public interface ReceiveMessageHandler
{
2594 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);