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
.contacts
.ContactInfo
;
34 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfo
;
35 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV1
;
36 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
37 import org
.asamk
.signal
.manager
.storage
.identities
.IdentityInfo
;
38 import org
.asamk
.signal
.manager
.storage
.messageCache
.CachedMessage
;
39 import org
.asamk
.signal
.manager
.storage
.profiles
.SignalProfile
;
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.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
248 this::getRecipientProfile
,
249 account
::getSelfAddress
,
252 this::getGroupAuthForToday
);
253 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
254 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
257 public String
getUsername() {
258 return account
.getUsername();
261 public SignalServiceAddress
getSelfAddress() {
262 return account
.getSelfAddress();
265 private IdentityKeyPair
getIdentityKeyPair() {
266 return account
.getIdentityKeyPair();
269 public int getDeviceId() {
270 return account
.getDeviceId();
273 public static Manager
init(
274 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
275 ) throws IOException
, NotRegisteredException
{
276 var pathConfig
= PathConfig
.createDefault(settingsPath
);
278 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
279 throw new NotRegisteredException();
282 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
284 if (!account
.isRegistered()) {
285 throw new NotRegisteredException();
288 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
290 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
293 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
294 var pathConfig
= PathConfig
.createDefault(settingsPath
);
295 final var dataPath
= pathConfig
.getDataPath();
296 final var files
= dataPath
.listFiles();
302 return Arrays
.stream(files
)
303 .filter(File
::isFile
)
305 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
306 .collect(Collectors
.toList());
309 public void checkAccountState() throws IOException
{
310 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
314 if (account
.getUuid() == null) {
315 account
.setUuid(accountManager
.getOwnUuid());
318 updateAccountAttributes();
322 * This is used for checking a set of phone numbers for registration on Signal
324 * @param numbers The set of phone number in question
325 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
326 * @throws IOException if its unable to get the contacts to check if they're registered
328 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
329 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
330 var contactDetails
= getRegisteredUsers(numbers
);
332 var registeredUsers
= contactDetails
.keySet();
334 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
337 public void updateAccountAttributes() throws IOException
{
338 accountManager
.setAccountAttributes(null,
339 account
.getLocalRegistrationId(),
341 // set legacy pin only if no KBS master key is set
342 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
343 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
344 account
.getSelfUnidentifiedAccessKey(),
345 account
.isUnrestrictedUnidentifiedAccess(),
347 account
.isDiscoverableByPhoneNumber());
351 * @param name if null, the previous name will be kept
352 * @param about if null, the previous about text will be kept
353 * @param aboutEmoji if null, the previous about emoji will be kept
354 * @param avatar if avatar is null the image from the local avatar store is used (if present),
355 * if it's Optional.absent(), the avatar will be removed
357 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
358 var profileEntry
= account
.getProfileStore().getProfileEntry(getSelfAddress());
359 var profile
= profileEntry
== null ?
null : profileEntry
.getProfile();
360 var newProfile
= new SignalProfile(profile
== null ?
null : profile
.getIdentityKey(),
361 name
!= null ? name
: profile
== null || profile
.getName() == null ?
"" : profile
.getName(),
362 about
!= null ? about
: profile
== null || profile
.getAbout() == null ?
"" : profile
.getAbout(),
365 : profile
== null || profile
.getAboutEmoji() == null ?
"" : profile
.getAboutEmoji(),
366 profile
== null ?
null : profile
.getUnidentifiedAccess(),
367 account
.isUnrestrictedUnidentifiedAccess(),
368 profile
== null ?
null : profile
.getCapabilities());
370 try (final var streamDetails
= avatar
== null
371 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
372 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
373 accountManager
.setVersionedProfile(account
.getUuid(),
374 account
.getProfileKey(),
375 newProfile
.getName(),
376 newProfile
.getAbout(),
377 newProfile
.getAboutEmoji(),
381 if (avatar
!= null) {
382 if (avatar
.isPresent()) {
383 avatarStore
.storeProfileAvatar(getSelfAddress(),
384 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
386 avatarStore
.deleteProfileAvatar(getSelfAddress());
389 account
.getProfileStore()
390 .updateProfile(getSelfAddress(),
391 account
.getProfileKey(),
392 System
.currentTimeMillis(),
394 profileEntry
== null ?
null : profileEntry
.getProfileKeyCredential());
397 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
398 } catch (UntrustedIdentityException ignored
) {
402 public void unregister() throws IOException
{
403 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
404 // If this is the master device, other users can't send messages to this number anymore.
405 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
406 accountManager
.setGcmId(Optional
.absent());
407 accountManager
.deleteAccount();
409 account
.setRegistered(false);
413 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
414 var devices
= accountManager
.getDevices();
415 account
.setMultiDevice(devices
.size() > 1);
420 public void removeLinkedDevices(int deviceId
) throws IOException
{
421 accountManager
.removeDevice(deviceId
);
422 var devices
= accountManager
.getDevices();
423 account
.setMultiDevice(devices
.size() > 1);
427 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
428 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
430 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
433 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
434 var identityKeyPair
= getIdentityKeyPair();
435 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
437 accountManager
.addDevice(deviceIdentifier
,
440 Optional
.of(account
.getProfileKey().serialize()),
442 account
.setMultiDevice(true);
446 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
447 if (!account
.isMasterDevice()) {
448 throw new RuntimeException("Only master device can set a PIN");
450 if (pin
.isPresent()) {
451 final var masterKey
= account
.getPinMasterKey() != null
452 ? account
.getPinMasterKey()
453 : KeyUtils
.createMasterKey();
455 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
457 account
.setRegistrationLockPin(pin
.get());
458 account
.setPinMasterKey(masterKey
);
460 // Remove legacy registration lock
461 accountManager
.removeRegistrationLockV1();
464 pinHelper
.removeRegistrationLockPin();
466 account
.setRegistrationLockPin(null);
467 account
.setPinMasterKey(null);
472 void refreshPreKeys() throws IOException
{
473 var oneTimePreKeys
= generatePreKeys();
474 final var identityKeyPair
= getIdentityKeyPair();
475 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
477 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
480 private List
<PreKeyRecord
> generatePreKeys() {
481 final var offset
= account
.getPreKeyIdOffset();
483 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
484 account
.addPreKeys(records
);
489 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
490 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
492 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
493 account
.addSignedPreKey(record);
498 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
499 if (messagePipe
== null) {
500 messagePipe
= messageReceiver
.createMessagePipe();
505 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
506 if (unidentifiedMessagePipe
== null) {
507 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
509 return unidentifiedMessagePipe
;
512 private SignalServiceMessageSender
createMessageSender() {
513 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
515 account
.getUsername(),
516 account
.getPassword(),
517 account
.getDeviceId(),
518 account
.getSignalProtocolStore(),
520 account
.isMultiDevice(),
521 Optional
.fromNullable(messagePipe
),
522 Optional
.fromNullable(unidentifiedMessagePipe
),
524 clientZkProfileOperations
,
526 ServiceConfig
.MAX_ENVELOPE_SIZE
,
527 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
530 public SignalProfile
getRecipientProfile(
531 SignalServiceAddress address
533 return getRecipientProfile(address
, false);
536 SignalProfile
getRecipientProfile(
537 SignalServiceAddress address
, boolean force
539 var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
540 if (profileEntry
== null) {
541 // retrieve profile to get identity key
542 retrieveEncryptedProfile(address
);
545 var now
= new Date().getTime();
546 // Profiles are cached for 24h before retrieving them again
547 if (!profileEntry
.isRequestPending() && (
549 || profileEntry
.getProfile() == null
550 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
552 profileEntry
.setRequestPending(true);
553 final SignalServiceProfile encryptedProfile
;
555 encryptedProfile
= retrieveEncryptedProfile(address
);
557 profileEntry
.setRequestPending(false);
559 if (encryptedProfile
== null) {
563 final var profileKey
= profileEntry
.getProfileKey();
564 final var profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
565 account
.getProfileStore()
566 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
569 return profileEntry
.getProfile();
572 private SignalServiceProfile
retrieveEncryptedProfile(SignalServiceAddress address
) {
574 final var profile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
577 account
.getIdentityKeyStore()
578 .saveIdentity(resolveRecipient(address
),
579 new IdentityKey(Base64
.getDecoder().decode(profile
.getIdentityKey())),
581 } catch (InvalidKeyException ignored
) {
582 logger
.warn("Got invalid identity key in profile for {}", address
.getLegacyIdentifier());
585 } catch (IOException e
) {
586 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
591 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
592 var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
593 if (profileEntry
== null) {
596 if (profileEntry
.getProfileKeyCredential() == null) {
597 ProfileAndCredential profileAndCredential
;
599 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
600 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
601 } catch (IOException e
) {
602 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
606 var now
= new Date().getTime();
607 final var profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
608 final var profile
= decryptProfileAndDownloadAvatar(address
,
609 profileEntry
.getProfileKey(),
610 profileAndCredential
.getProfile());
611 account
.getProfileStore()
612 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
613 return profileKeyCredential
;
615 return profileEntry
.getProfileKeyCredential();
618 private SignalProfile
decryptProfileAndDownloadAvatar(
619 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
621 if (encryptedProfile
.getAvatar() != null) {
622 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
625 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
628 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
629 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
630 if (streamDetails
== null) {
631 return Optional
.absent();
634 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
637 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
638 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
639 if (streamDetails
== null) {
640 return Optional
.absent();
643 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
646 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
647 var g
= getGroup(groupId
);
649 throw new GroupNotFoundException(groupId
);
651 if (!g
.isMember(account
.getSelfAddress())) {
652 throw new NotAGroupMemberException(groupId
, g
.getTitle());
657 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
658 var g
= getGroup(groupId
);
660 throw new GroupNotFoundException(groupId
);
662 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
663 throw new NotAGroupMemberException(groupId
, g
.getTitle());
668 public List
<GroupInfo
> getGroups() {
669 return account
.getGroupStore().getGroups();
672 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
673 String messageText
, List
<String
> attachments
, GroupId groupId
674 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
675 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
676 if (attachments
!= null) {
677 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
680 return sendGroupMessage(messageBuilder
, groupId
);
683 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
684 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
685 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
686 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
688 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
689 targetSentTimestamp
);
690 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
692 return sendGroupMessage(messageBuilder
, groupId
);
695 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
696 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
697 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
698 final var g
= getGroupForSending(groupId
);
700 GroupUtils
.setGroupContext(messageBuilder
, g
);
701 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
703 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
706 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
707 SignalServiceDataMessage
.Builder messageBuilder
;
709 final var g
= getGroupForUpdating(groupId
);
710 if (g
instanceof GroupInfoV1
) {
711 var groupInfoV1
= (GroupInfoV1
) g
;
712 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
713 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
714 groupInfoV1
.removeMember(account
.getSelfAddress());
715 account
.getGroupStore().updateGroup(groupInfoV1
);
717 final var groupInfoV2
= (GroupInfoV2
) g
;
718 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
719 groupInfoV2
.setGroup(groupGroupChangePair
.first());
720 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
721 account
.getGroupStore().updateGroup(groupInfoV2
);
724 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
727 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
728 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
729 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
730 return sendUpdateGroupMessage(groupId
,
732 members
== null ?
null : getSignalServiceAddresses(members
),
736 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
737 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
738 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
740 SignalServiceDataMessage
.Builder messageBuilder
;
741 if (groupId
== null) {
743 var gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
744 members
== null ? List
.of() : members
,
747 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
748 gv1
.addMembers(List
.of(account
.getSelfAddress()));
749 updateGroupV1(gv1
, name
, members
, avatarFile
);
750 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
753 if (avatarFile
!= null) {
754 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
755 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
757 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
761 var group
= getGroupForUpdating(groupId
);
762 if (group
instanceof GroupInfoV2
) {
763 final var groupInfoV2
= (GroupInfoV2
) group
;
765 Pair
<Long
, List
<SendMessageResult
>> result
= null;
766 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
767 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
768 result
= sendUpdateGroupMessage(groupInfoV2
,
769 groupGroupChangePair
.first(),
770 groupGroupChangePair
.second());
773 if (members
!= null) {
774 final var newMembers
= new HashSet
<>(members
);
775 newMembers
.removeAll(group
.getMembers()
777 .map(this::resolveSignalServiceAddress
)
778 .collect(Collectors
.toSet()));
779 if (newMembers
.size() > 0) {
780 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
781 result
= sendUpdateGroupMessage(groupInfoV2
,
782 groupGroupChangePair
.first(),
783 groupGroupChangePair
.second());
786 if (result
== null || name
!= null || avatarFile
!= null) {
787 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
788 if (avatarFile
!= null) {
789 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
790 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
792 result
= sendUpdateGroupMessage(groupInfoV2
,
793 groupGroupChangePair
.first(),
794 groupGroupChangePair
.second());
797 return new Pair
<>(group
.getGroupId(), result
.second());
799 var gv1
= (GroupInfoV1
) group
;
800 updateGroupV1(gv1
, name
, members
, avatarFile
);
801 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
806 account
.getGroupStore().updateGroup(g
);
808 final var result
= sendMessage(messageBuilder
, g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
809 return new Pair
<>(g
.getGroupId(), result
.second());
812 private void updateGroupV1(
815 final Collection
<SignalServiceAddress
> members
,
816 final File avatarFile
817 ) throws IOException
{
822 if (members
!= null) {
823 final var newE164Members
= new HashSet
<String
>();
824 for (var member
: members
) {
825 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
828 newE164Members
.add(member
.getNumber().get());
831 final var registeredUsers
= getRegisteredUsers(newE164Members
);
832 if (registeredUsers
.size() != newE164Members
.size()) {
833 // Some of the new members are not registered on Signal
834 newE164Members
.removeAll(registeredUsers
.keySet());
835 throw new IOException("Failed to add members "
836 + String
.join(", ", newE164Members
)
837 + " to group: Not registered on Signal");
840 g
.addMembers(members
);
843 if (avatarFile
!= null) {
844 avatarStore
.storeGroupAvatar(g
.getGroupId(),
845 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
849 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
850 GroupInviteLinkUrl inviteLinkUrl
851 ) throws IOException
, GroupLinkNotActiveException
{
852 return sendJoinGroupMessage(inviteLinkUrl
);
855 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
856 GroupInviteLinkUrl inviteLinkUrl
857 ) throws IOException
, GroupLinkNotActiveException
{
858 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
859 inviteLinkUrl
.getPassword());
860 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
861 inviteLinkUrl
.getPassword(),
863 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
864 groupJoinInfo
.getRevision() + 1,
865 groupChange
.toByteArray());
867 if (group
.getGroup() == null) {
868 // Only requested member, can't send update to group members
869 return new Pair
<>(group
.getGroupId(), List
.of());
872 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
874 return new Pair
<>(group
.getGroupId(), result
.second());
877 private static int currentTimeDays() {
878 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
881 private GroupsV2AuthorizationString
getGroupAuthForToday(
882 final GroupSecretParams groupSecretParams
883 ) throws IOException
{
884 final var today
= currentTimeDays();
885 // Returns credentials for the next 7 days
886 final var credentials
= groupsV2Api
.getCredentials(today
);
887 // TODO cache credentials until they expire
888 var authCredentialResponse
= credentials
.get(today
);
890 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
893 authCredentialResponse
);
894 } catch (VerificationFailedException e
) {
895 throw new IOException(e
);
899 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
900 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
901 ) throws IOException
{
902 group
.setGroup(newDecryptedGroup
);
903 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
904 account
.getGroupStore().updateGroup(group
);
905 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
908 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
909 GroupIdV1 groupId
, SignalServiceAddress recipient
910 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
912 var group
= getGroupForSending(groupId
);
913 if (!(group
instanceof GroupInfoV1
)) {
914 throw new RuntimeException("Received an invalid group request for a v2 group!");
916 g
= (GroupInfoV1
) group
;
918 if (!g
.isMember(recipient
)) {
919 throw new NotAGroupMemberException(groupId
, g
.name
);
922 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
924 // Send group message only to the recipient who requested it
925 return sendMessage(messageBuilder
, List
.of(recipient
));
928 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
929 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
930 .withId(g
.getGroupId().serialize())
932 .withMembers(new ArrayList
<>(g
.getMembers()));
935 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
936 if (attachment
.isPresent()) {
937 group
.withAvatar(attachment
.get());
939 } catch (IOException e
) {
940 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
943 return SignalServiceDataMessage
.newBuilder()
944 .asGroupMessage(group
.build())
945 .withExpiration(g
.getMessageExpirationTime());
948 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
949 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
950 .withRevision(g
.getGroup().getRevision())
951 .withSignedGroupChange(signedGroupChange
);
952 return SignalServiceDataMessage
.newBuilder()
953 .asGroupMessage(group
.build())
954 .withExpiration(g
.getMessageExpirationTime());
957 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
958 GroupIdV1 groupId
, SignalServiceAddress recipient
959 ) throws IOException
{
960 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
962 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
964 // Send group info request message to the recipient who sent us a message with this groupId
965 return sendMessage(messageBuilder
, List
.of(recipient
));
969 SignalServiceAddress remoteAddress
, long messageId
970 ) throws IOException
, UntrustedIdentityException
{
971 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
973 System
.currentTimeMillis());
975 createMessageSender().sendReceipt(remoteAddress
,
976 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
980 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
981 String messageText
, List
<String
> attachments
, List
<String
> recipients
982 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
983 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
984 if (attachments
!= null) {
985 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
987 // Upload attachments here, so we only upload once even for multiple recipients
988 var messageSender
= createMessageSender();
989 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
990 for (var attachment
: attachmentStreams
) {
991 if (attachment
.isStream()) {
992 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
993 } else if (attachment
.isPointer()) {
994 attachmentPointers
.add(attachment
.asPointer());
998 messageBuilder
.withAttachments(attachmentPointers
);
1000 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1003 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
1004 String messageText
, List
<String
> attachments
1005 ) throws IOException
, AttachmentInvalidException
{
1006 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
1007 if (attachments
!= null) {
1008 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
1010 return sendSelfMessage(messageBuilder
);
1013 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
1014 long targetSentTimestamp
, List
<String
> recipients
1015 ) throws IOException
, InvalidNumberException
{
1016 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1017 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1018 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1021 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1022 long targetSentTimestamp
, GroupId groupId
1023 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1024 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1025 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1026 return sendGroupMessage(messageBuilder
, groupId
);
1029 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1030 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1031 ) throws IOException
, InvalidNumberException
{
1032 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1034 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1035 targetSentTimestamp
);
1036 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1037 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1040 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1041 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1043 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1045 return sendMessage(messageBuilder
, signalServiceAddresses
);
1046 } catch (Exception e
) {
1047 for (var address
: signalServiceAddresses
) {
1048 handleEndSession(address
);
1055 public String
getContactName(String number
) throws InvalidNumberException
{
1056 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1057 if (contact
== null) {
1060 return contact
.name
;
1064 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1065 final var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1066 var contact
= account
.getContactStore().getContact(address
);
1067 if (contact
== null) {
1068 contact
= new ContactInfo(address
);
1070 contact
.name
= name
;
1071 account
.getContactStore().updateContact(contact
);
1075 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1076 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1079 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1080 var contact
= account
.getContactStore().getContact(address
);
1081 if (contact
== null) {
1082 contact
= new ContactInfo(address
);
1084 contact
.blocked
= blocked
;
1085 account
.getContactStore().updateContact(contact
);
1089 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1090 var group
= getGroup(groupId
);
1091 if (group
== null) {
1092 throw new GroupNotFoundException(groupId
);
1095 group
.setBlocked(blocked
);
1096 account
.getGroupStore().updateGroup(group
);
1101 * Change the expiration timer for a contact
1103 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1104 var contact
= account
.getContactStore().getContact(address
);
1105 contact
.messageExpirationTime
= messageExpirationTimer
;
1106 account
.getContactStore().updateContact(contact
);
1107 sendExpirationTimerUpdate(address
);
1111 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1112 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1113 sendMessage(messageBuilder
, List
.of(address
));
1117 * Change the expiration timer for a contact
1119 public void setExpirationTimer(
1120 String number
, int messageExpirationTimer
1121 ) throws IOException
, InvalidNumberException
{
1122 var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1123 setExpirationTimer(address
, messageExpirationTimer
);
1127 * Change the expiration timer for a group
1129 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1130 var g
= getGroup(groupId
);
1131 if (g
instanceof GroupInfoV1
) {
1132 var groupInfoV1
= (GroupInfoV1
) g
;
1133 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1134 account
.getGroupStore().updateGroup(groupInfoV1
);
1136 throw new RuntimeException("TODO Not implemented!");
1141 * Upload the sticker pack from path.
1143 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1144 * @return if successful, returns the URL to install the sticker pack in the signal app
1146 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1147 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1149 var messageSender
= createMessageSender();
1151 var packKey
= KeyUtils
.createStickerUploadKey();
1152 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1154 var sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1155 account
.getStickerStore().updateSticker(sticker
);
1159 return new URI("https",
1162 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1163 Hex
.toStringCondensed(packKey
),
1164 StandardCharsets
.UTF_8
)).toString();
1165 } catch (URISyntaxException e
) {
1166 throw new AssertionError(e
);
1170 void requestSyncGroups() throws IOException
{
1171 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1172 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1174 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1176 sendSyncMessage(message
);
1177 } catch (UntrustedIdentityException e
) {
1178 throw new AssertionError(e
);
1182 void requestSyncContacts() throws IOException
{
1183 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1184 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1186 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1188 sendSyncMessage(message
);
1189 } catch (UntrustedIdentityException e
) {
1190 throw new AssertionError(e
);
1194 void requestSyncBlocked() throws IOException
{
1195 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1196 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1198 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1200 sendSyncMessage(message
);
1201 } catch (UntrustedIdentityException e
) {
1202 throw new AssertionError(e
);
1206 void requestSyncConfiguration() throws IOException
{
1207 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1208 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1210 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1212 sendSyncMessage(message
);
1213 } catch (UntrustedIdentityException e
) {
1214 throw new AssertionError(e
);
1218 void requestSyncKeys() throws IOException
{
1219 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1220 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1222 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1224 sendSyncMessage(message
);
1225 } catch (UntrustedIdentityException e
) {
1226 throw new AssertionError(e
);
1230 private byte[] getSenderCertificate() {
1231 // TODO support UUID capable sender certificates
1232 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1235 certificate
= accountManager
.getSenderCertificate();
1236 } catch (IOException e
) {
1237 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1240 // TODO cache for a day
1244 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1245 var messageSender
= createMessageSender();
1246 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1249 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1250 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1251 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1253 for (var number
: numbers
) {
1254 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1255 if (resolvedAddress
.getUuid().isPresent()) {
1256 signalServiceAddresses
.add(resolvedAddress
);
1258 addressesMissingUuid
.add(resolvedAddress
);
1262 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1263 .map(a
-> a
.getNumber().get())
1264 .collect(Collectors
.toSet());
1265 Map
<String
, UUID
> registeredUsers
;
1267 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1268 } catch (IOException e
) {
1269 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1270 registeredUsers
= Map
.of();
1273 for (var address
: addressesMissingUuid
) {
1274 final var number
= address
.getNumber().get();
1275 if (registeredUsers
.containsKey(number
)) {
1276 final var newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(registeredUsers
.get(number
),
1278 signalServiceAddresses
.add(newAddress
);
1280 signalServiceAddresses
.add(address
);
1284 return signalServiceAddresses
;
1287 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1289 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1291 serviceEnvironmentConfig
.getCdsMrenclave());
1292 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1293 throw new IOException(e
);
1297 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1298 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1299 ) throws IOException
{
1300 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1301 final var timestamp
= System
.currentTimeMillis();
1302 messageBuilder
.withTimestamp(timestamp
);
1303 getOrCreateMessagePipe();
1304 getOrCreateUnidentifiedMessagePipe();
1305 SignalServiceDataMessage message
= null;
1307 message
= messageBuilder
.build();
1308 if (message
.getGroupContext().isPresent()) {
1310 var messageSender
= createMessageSender();
1311 final var isRecipientUpdate
= false;
1312 var result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1313 unidentifiedAccessHelper
.getAccessFor(recipients
),
1317 for (var r
: result
) {
1318 if (r
.getIdentityFailure() != null) {
1319 account
.getIdentityKeyStore().
1320 saveIdentity(resolveRecipient(r
.getAddress()),
1321 r
.getIdentityFailure().getIdentityKey(),
1326 return new Pair
<>(timestamp
, result
);
1327 } catch (UntrustedIdentityException e
) {
1328 return new Pair
<>(timestamp
, List
.of());
1331 // Send to all individually, so sync messages are sent correctly
1332 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1333 var results
= new ArrayList
<SendMessageResult
>(recipients
.size());
1334 for (var address
: recipients
) {
1335 final var contact
= account
.getContactStore().getContact(address
);
1336 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1337 messageBuilder
.withExpiration(expirationTime
);
1338 message
= messageBuilder
.build();
1339 results
.add(sendMessage(address
, message
));
1341 return new Pair
<>(timestamp
, results
);
1344 if (message
!= null && message
.isEndSession()) {
1345 for (var recipient
: recipients
) {
1346 handleEndSession(recipient
);
1353 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1354 SignalServiceDataMessage
.Builder messageBuilder
1355 ) throws IOException
{
1356 final var timestamp
= System
.currentTimeMillis();
1357 messageBuilder
.withTimestamp(timestamp
);
1358 getOrCreateMessagePipe();
1359 getOrCreateUnidentifiedMessagePipe();
1361 final var address
= getSelfAddress();
1363 final var contact
= account
.getContactStore().getContact(address
);
1364 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1365 messageBuilder
.withExpiration(expirationTime
);
1367 var message
= messageBuilder
.build();
1368 final var result
= sendSelfMessage(message
);
1369 return new Pair
<>(timestamp
, result
);
1375 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1376 var messageSender
= createMessageSender();
1378 var recipient
= account
.getSelfAddress();
1380 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1381 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1382 message
.getTimestamp(),
1384 message
.getExpiresInSeconds(),
1385 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1387 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1390 var startTime
= System
.currentTimeMillis();
1391 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1392 return SendMessageResult
.success(recipient
,
1393 unidentifiedAccess
.isPresent(),
1395 System
.currentTimeMillis() - startTime
);
1396 } catch (UntrustedIdentityException e
) {
1397 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1401 private SendMessageResult
sendMessage(
1402 SignalServiceAddress address
, SignalServiceDataMessage message
1403 ) throws IOException
{
1404 var messageSender
= createMessageSender();
1407 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1408 } catch (UntrustedIdentityException e
) {
1409 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1413 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1414 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1415 account
.getSignalProtocolStore(),
1416 certificateValidator
);
1418 return cipher
.decrypt(envelope
);
1419 } catch (ProtocolUntrustedIdentityException e
) {
1420 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1421 throw (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1423 throw new AssertionError(e
);
1427 private void handleEndSession(SignalServiceAddress source
) {
1428 account
.getSessionStore().deleteAllSessions(source
.getIdentifier());
1431 private List
<HandleAction
> handleSignalServiceDataMessage(
1432 SignalServiceDataMessage message
,
1434 SignalServiceAddress source
,
1435 SignalServiceAddress destination
,
1436 boolean ignoreAttachments
1438 var actions
= new ArrayList
<HandleAction
>();
1439 if (message
.getGroupContext().isPresent()) {
1440 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1441 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1442 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1443 var group
= getGroup(groupId
);
1444 if (group
== null || group
instanceof GroupInfoV1
) {
1445 var groupV1
= (GroupInfoV1
) group
;
1446 switch (groupInfo
.getType()) {
1448 if (groupV1
== null) {
1449 groupV1
= new GroupInfoV1(groupId
);
1452 if (groupInfo
.getAvatar().isPresent()) {
1453 var avatar
= groupInfo
.getAvatar().get();
1454 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1457 if (groupInfo
.getName().isPresent()) {
1458 groupV1
.name
= groupInfo
.getName().get();
1461 if (groupInfo
.getMembers().isPresent()) {
1462 groupV1
.addMembers(groupInfo
.getMembers()
1465 .map(this::resolveSignalServiceAddress
)
1466 .collect(Collectors
.toSet()));
1469 account
.getGroupStore().updateGroup(groupV1
);
1473 if (groupV1
== null && !isSync
) {
1474 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1478 if (groupV1
!= null) {
1479 groupV1
.removeMember(source
);
1480 account
.getGroupStore().updateGroup(groupV1
);
1485 if (groupV1
!= null && !isSync
) {
1486 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1491 // Received a group v1 message for a v2 group
1494 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1495 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1496 final var groupMasterKey
= groupContext
.getMasterKey();
1498 getOrMigrateGroup(groupMasterKey
,
1499 groupContext
.getRevision(),
1500 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1504 final var conversationPartnerAddress
= isSync ? destination
: source
;
1505 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1506 handleEndSession(conversationPartnerAddress
);
1508 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1509 if (message
.getGroupContext().isPresent()) {
1510 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1511 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1512 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1513 if (group
!= null) {
1514 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1515 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1516 account
.getGroupStore().updateGroup(group
);
1519 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1520 // disappearing message timer already stored in the DecryptedGroup
1522 } else if (conversationPartnerAddress
!= null) {
1523 var contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1524 if (contact
== null) {
1525 contact
= new ContactInfo(conversationPartnerAddress
);
1527 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1528 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1529 account
.getContactStore().updateContact(contact
);
1533 if (!ignoreAttachments
) {
1534 if (message
.getAttachments().isPresent()) {
1535 for (var attachment
: message
.getAttachments().get()) {
1536 downloadAttachment(attachment
);
1539 if (message
.getSharedContacts().isPresent()) {
1540 for (var contact
: message
.getSharedContacts().get()) {
1541 if (contact
.getAvatar().isPresent()) {
1542 downloadAttachment(contact
.getAvatar().get().getAttachment());
1547 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1548 final ProfileKey profileKey
;
1550 profileKey
= new ProfileKey(message
.getProfileKey().get());
1551 } catch (InvalidInputException e
) {
1552 throw new AssertionError(e
);
1554 if (source
.matches(account
.getSelfAddress())) {
1555 this.account
.setProfileKey(profileKey
);
1557 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1559 if (message
.getPreviews().isPresent()) {
1560 final var previews
= message
.getPreviews().get();
1561 for (var preview
: previews
) {
1562 if (preview
.getImage().isPresent()) {
1563 downloadAttachment(preview
.getImage().get());
1567 if (message
.getQuote().isPresent()) {
1568 final var quote
= message
.getQuote().get();
1570 for (var quotedAttachment
: quote
.getAttachments()) {
1571 final var thumbnail
= quotedAttachment
.getThumbnail();
1572 if (thumbnail
!= null) {
1573 downloadAttachment(thumbnail
);
1577 if (message
.getSticker().isPresent()) {
1578 final var messageSticker
= message
.getSticker().get();
1579 var sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1580 if (sticker
== null) {
1581 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1582 account
.getStickerStore().updateSticker(sticker
);
1588 private GroupInfoV2
getOrMigrateGroup(
1589 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1591 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1593 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1594 var groupInfo
= getGroup(groupId
);
1595 final GroupInfoV2 groupInfoV2
;
1596 if (groupInfo
instanceof GroupInfoV1
) {
1597 // Received a v2 group message for a v1 group, we need to locally migrate the group
1598 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1599 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1600 logger
.info("Locally migrated group {} to group v2, id: {}",
1601 groupInfo
.getGroupId().toBase64(),
1602 groupInfoV2
.getGroupId().toBase64());
1603 } else if (groupInfo
instanceof GroupInfoV2
) {
1604 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1606 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1609 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1610 DecryptedGroup group
= null;
1611 if (signedGroupChange
!= null
1612 && groupInfoV2
.getGroup() != null
1613 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1614 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1616 if (group
== null) {
1617 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1619 if (group
!= null) {
1620 storeProfileKeysFromMembers(group
);
1621 final var avatar
= group
.getAvatar();
1622 if (avatar
!= null && !avatar
.isEmpty()) {
1623 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1626 groupInfoV2
.setGroup(group
);
1627 account
.getGroupStore().updateGroup(groupInfoV2
);
1633 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1634 for (var member
: group
.getMembersList()) {
1635 final var address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1636 .toByteArray()), null));
1638 account
.getProfileStore()
1639 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1640 } catch (InvalidInputException ignored
) {
1645 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1646 Set
<HandleAction
> queuedActions
= new HashSet
<>();
1647 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1648 var actions
= retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1649 if (actions
!= null) {
1650 queuedActions
.addAll(actions
);
1653 for (var action
: queuedActions
) {
1655 action
.execute(this);
1656 } catch (Throwable e
) {
1657 logger
.warn("Message action failed.", e
);
1662 private List
<HandleAction
> retryFailedReceivedMessage(
1663 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1665 var envelope
= cachedMessage
.loadEnvelope();
1666 if (envelope
== null) {
1669 SignalServiceContent content
= null;
1670 List
<HandleAction
> actions
= null;
1671 if (!envelope
.isReceipt()) {
1673 content
= decryptMessage(envelope
);
1674 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1675 if (!envelope
.hasSource()) {
1676 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
)
1679 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1680 } catch (IOException ioException
) {
1681 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1685 } catch (Exception er
) {
1686 // All other errors are not recoverable, so delete the cached message
1687 cachedMessage
.delete();
1690 actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1693 handler
.handleMessage(envelope
, content
, null);
1694 cachedMessage
.delete();
1698 public void receiveMessages(
1701 boolean returnOnTimeout
,
1702 boolean ignoreAttachments
,
1703 ReceiveMessageHandler handler
1704 ) throws IOException
{
1705 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1707 Set
<HandleAction
> queuedActions
= null;
1709 final var messagePipe
= getOrCreateMessagePipe();
1711 var hasCaughtUpWithOldMessages
= false;
1714 SignalServiceEnvelope envelope
;
1715 SignalServiceContent content
= null;
1716 Exception exception
= null;
1717 final CachedMessage
[] cachedMessage
= {null};
1719 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1720 final var recipientId
= envelope1
.hasSource()
1721 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1723 // store message on disk, before acknowledging receipt to the server
1724 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1726 if (result
.isPresent()) {
1727 envelope
= result
.get();
1729 // Received indicator that server queue is empty
1730 hasCaughtUpWithOldMessages
= true;
1732 if (queuedActions
!= null) {
1733 for (var action
: queuedActions
) {
1735 action
.execute(this);
1736 } catch (Throwable e
) {
1737 logger
.warn("Message action failed.", e
);
1741 queuedActions
.clear();
1742 queuedActions
= null;
1745 // Continue to wait another timeout for new messages
1748 } catch (TimeoutException e
) {
1749 if (returnOnTimeout
) return;
1753 if (envelope
.hasSource()) {
1754 // Store uuid if we don't have it already
1755 resolveRecipientTrusted(envelope
.getSourceAddress());
1757 final var notAGroupMember
= isNotAGroupMember(envelope
, content
);
1758 if (!envelope
.isReceipt()) {
1760 content
= decryptMessage(envelope
);
1761 } catch (Exception e
) {
1764 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1765 if (hasCaughtUpWithOldMessages
) {
1766 for (var action
: actions
) {
1768 action
.execute(this);
1769 } catch (Throwable e
) {
1770 logger
.warn("Message action failed.", e
);
1774 if (queuedActions
== null) {
1775 queuedActions
= new HashSet
<>();
1777 queuedActions
.addAll(actions
);
1781 if (isMessageBlocked(envelope
, content
)) {
1782 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1783 } else if (notAGroupMember
) {
1784 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1786 handler
.handleMessage(envelope
, content
, exception
);
1788 if (cachedMessage
[0] != null) {
1789 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1790 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
)
1792 queuedActions
.add(new RetrieveProfileAction(resolveSignalServiceAddress(recipientId
)));
1793 if (!envelope
.hasSource()) {
1795 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1796 } catch (IOException ioException
) {
1797 logger
.warn("Failed to move cached message to recipient folder: {}",
1798 ioException
.getMessage());
1802 cachedMessage
[0].delete();
1808 private boolean isMessageBlocked(
1809 SignalServiceEnvelope envelope
, SignalServiceContent content
1811 SignalServiceAddress source
;
1812 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1813 source
= envelope
.getSourceAddress();
1814 } else if (content
!= null) {
1815 source
= content
.getSender();
1819 var sourceContact
= account
.getContactStore().getContact(source
);
1820 if (sourceContact
!= null && sourceContact
.blocked
) {
1824 if (content
!= null && content
.getDataMessage().isPresent()) {
1825 var message
= content
.getDataMessage().get();
1826 if (message
.getGroupContext().isPresent()) {
1827 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1828 var group
= getGroup(groupId
);
1829 if (group
!= null && group
.isBlocked()) {
1837 private boolean isNotAGroupMember(
1838 SignalServiceEnvelope envelope
, SignalServiceContent content
1840 SignalServiceAddress source
;
1841 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1842 source
= envelope
.getSourceAddress();
1843 } else if (content
!= null) {
1844 source
= content
.getSender();
1849 if (content
!= null && content
.getDataMessage().isPresent()) {
1850 var message
= content
.getDataMessage().get();
1851 if (message
.getGroupContext().isPresent()) {
1852 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1853 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1854 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1858 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1859 var group
= getGroup(groupId
);
1860 if (group
!= null && !group
.isMember(source
)) {
1868 private List
<HandleAction
> handleMessage(
1869 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1871 var actions
= new ArrayList
<HandleAction
>();
1872 if (content
!= null) {
1873 final SignalServiceAddress sender
;
1874 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1875 sender
= envelope
.getSourceAddress();
1877 sender
= content
.getSender();
1879 // Store uuid if we don't have it already
1880 resolveSignalServiceAddress(sender
);
1882 if (content
.getDataMessage().isPresent()) {
1883 var message
= content
.getDataMessage().get();
1885 if (content
.isNeedsReceipt()) {
1886 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1889 actions
.addAll(handleSignalServiceDataMessage(message
,
1892 account
.getSelfAddress(),
1893 ignoreAttachments
));
1895 if (content
.getSyncMessage().isPresent()) {
1896 account
.setMultiDevice(true);
1897 var syncMessage
= content
.getSyncMessage().get();
1898 if (syncMessage
.getSent().isPresent()) {
1899 var message
= syncMessage
.getSent().get();
1900 final var destination
= message
.getDestination().orNull();
1901 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1905 ignoreAttachments
));
1907 if (syncMessage
.getRequest().isPresent() && account
.isMasterDevice()) {
1908 var rm
= syncMessage
.getRequest().get();
1909 if (rm
.isContactsRequest()) {
1910 actions
.add(SendSyncContactsAction
.create());
1912 if (rm
.isGroupsRequest()) {
1913 actions
.add(SendSyncGroupsAction
.create());
1915 if (rm
.isBlockedListRequest()) {
1916 actions
.add(SendSyncBlockedListAction
.create());
1918 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1920 if (syncMessage
.getGroups().isPresent()) {
1921 File tmpFile
= null;
1923 tmpFile
= IOUtils
.createTempFile();
1924 final var groupsMessage
= syncMessage
.getGroups().get();
1925 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1926 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1928 while ((g
= s
.read()) != null) {
1929 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1930 if (syncGroup
!= null) {
1931 if (g
.getName().isPresent()) {
1932 syncGroup
.name
= g
.getName().get();
1934 syncGroup
.addMembers(g
.getMembers()
1936 .map(this::resolveSignalServiceAddress
)
1937 .collect(Collectors
.toSet()));
1938 if (!g
.isActive()) {
1939 syncGroup
.removeMember(account
.getSelfAddress());
1941 // Add ourself to the member set as it's marked as active
1942 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1944 syncGroup
.blocked
= g
.isBlocked();
1945 if (g
.getColor().isPresent()) {
1946 syncGroup
.color
= g
.getColor().get();
1949 if (g
.getAvatar().isPresent()) {
1950 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1952 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1953 syncGroup
.archived
= g
.isArchived();
1954 account
.getGroupStore().updateGroup(syncGroup
);
1958 } catch (Exception e
) {
1959 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1963 if (tmpFile
!= null) {
1965 Files
.delete(tmpFile
.toPath());
1966 } catch (IOException e
) {
1967 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1974 if (syncMessage
.getBlockedList().isPresent()) {
1975 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1976 for (var address
: blockedListMessage
.getAddresses()) {
1977 setContactBlocked(resolveSignalServiceAddress(address
), true);
1979 for (var groupId
: blockedListMessage
.getGroupIds()
1981 .map(GroupId
::unknownVersion
)
1982 .collect(Collectors
.toSet())) {
1984 setGroupBlocked(groupId
, true);
1985 } catch (GroupNotFoundException e
) {
1986 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1987 groupId
.toBase64());
1991 if (syncMessage
.getContacts().isPresent()) {
1992 File tmpFile
= null;
1994 tmpFile
= IOUtils
.createTempFile();
1995 final var contactsMessage
= syncMessage
.getContacts().get();
1996 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1997 .asPointer(), tmpFile
)) {
1998 var s
= new DeviceContactsInputStream(attachmentAsStream
);
2000 while ((c
= s
.read()) != null) {
2001 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
2002 account
.setProfileKey(c
.getProfileKey().get());
2004 final var address
= resolveSignalServiceAddress(c
.getAddress());
2005 var contact
= account
.getContactStore().getContact(address
);
2006 if (contact
== null) {
2007 contact
= new ContactInfo(address
);
2009 if (c
.getName().isPresent()) {
2010 contact
.name
= c
.getName().get();
2012 if (c
.getColor().isPresent()) {
2013 contact
.color
= c
.getColor().get();
2015 if (c
.getProfileKey().isPresent()) {
2016 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
2018 if (c
.getVerified().isPresent()) {
2019 final var verifiedMessage
= c
.getVerified().get();
2020 account
.getIdentityKeyStore()
2021 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2022 verifiedMessage
.getIdentityKey(),
2023 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2025 if (c
.getExpirationTimer().isPresent()) {
2026 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
2028 contact
.blocked
= c
.isBlocked();
2029 contact
.inboxPosition
= c
.getInboxPosition().orNull();
2030 contact
.archived
= c
.isArchived();
2031 account
.getContactStore().updateContact(contact
);
2033 if (c
.getAvatar().isPresent()) {
2034 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2038 } catch (Exception e
) {
2039 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2043 if (tmpFile
!= null) {
2045 Files
.delete(tmpFile
.toPath());
2046 } catch (IOException e
) {
2047 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2054 if (syncMessage
.getVerified().isPresent()) {
2055 final var verifiedMessage
= syncMessage
.getVerified().get();
2056 account
.getIdentityKeyStore()
2057 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2058 verifiedMessage
.getIdentityKey(),
2059 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2061 if (syncMessage
.getStickerPackOperations().isPresent()) {
2062 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2063 for (var m
: stickerPackOperationMessages
) {
2064 if (!m
.getPackId().isPresent()) {
2067 var sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2068 if (sticker
== null) {
2069 if (!m
.getPackKey().isPresent()) {
2072 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2074 sticker
.setInstalled(!m
.getType().isPresent()
2075 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2076 account
.getStickerStore().updateSticker(sticker
);
2079 if (syncMessage
.getFetchType().isPresent()) {
2080 switch (syncMessage
.getFetchType().get()) {
2082 getRecipientProfile(getSelfAddress(), true);
2083 case STORAGE_MANIFEST
:
2087 if (syncMessage
.getKeys().isPresent()) {
2088 final var keysMessage
= syncMessage
.getKeys().get();
2089 if (keysMessage
.getStorageService().isPresent()) {
2090 final var storageKey
= keysMessage
.getStorageService().get();
2091 account
.setStorageKey(storageKey
);
2094 if (syncMessage
.getConfiguration().isPresent()) {
2102 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2104 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2105 } catch (IOException e
) {
2106 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2110 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2112 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2113 } catch (IOException e
) {
2114 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2118 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2120 avatarStore
.storeGroupAvatar(groupId
,
2121 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2122 } catch (IOException e
) {
2123 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2127 private void downloadProfileAvatar(
2128 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2131 avatarStore
.storeProfileAvatar(address
,
2132 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2133 } catch (Throwable e
) {
2134 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2138 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2139 return attachmentStore
.getAttachmentFile(attachmentId
);
2142 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2143 if (!attachment
.isPointer()) {
2144 logger
.warn("Invalid state, can't store an attachment stream.");
2147 var pointer
= attachment
.asPointer();
2148 if (pointer
.getPreview().isPresent()) {
2149 final var preview
= pointer
.getPreview().get();
2151 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2152 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2153 } catch (IOException e
) {
2154 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2159 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2160 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2161 } catch (IOException e
) {
2162 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2166 private void retrieveGroupV2Avatar(
2167 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2168 ) throws IOException
{
2169 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2171 var tmpFile
= IOUtils
.createTempFile();
2172 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2174 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2175 var encryptedData
= IOUtils
.readFully(input
);
2177 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2178 outputStream
.write(decryptedData
);
2181 Files
.delete(tmpFile
.toPath());
2182 } catch (IOException e
) {
2183 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2190 private void retrieveProfileAvatar(
2191 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2192 ) throws IOException
{
2193 var tmpFile
= IOUtils
.createTempFile();
2194 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2197 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2198 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2199 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2202 Files
.delete(tmpFile
.toPath());
2203 } catch (IOException e
) {
2204 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2211 private void retrieveAttachment(
2212 final SignalServiceAttachment attachment
, final OutputStream outputStream
2213 ) throws IOException
{
2214 if (attachment
.isPointer()) {
2215 var pointer
= attachment
.asPointer();
2216 retrieveAttachmentPointer(pointer
, outputStream
);
2218 var stream
= attachment
.asStream();
2219 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2223 private void retrieveAttachmentPointer(
2224 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2225 ) throws IOException
{
2226 var tmpFile
= IOUtils
.createTempFile();
2227 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2228 IOUtils
.copyStream(input
, outputStream
);
2229 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2230 throw new IOException(e
);
2233 Files
.delete(tmpFile
.toPath());
2234 } catch (IOException e
) {
2235 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2242 private InputStream
retrieveAttachmentAsStream(
2243 SignalServiceAttachmentPointer pointer
, File tmpFile
2244 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2245 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2248 void sendGroups() throws IOException
, UntrustedIdentityException
{
2249 var groupsFile
= IOUtils
.createTempFile();
2252 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2253 var out
= new DeviceGroupsOutputStream(fos
);
2254 for (var record : getGroups()) {
2255 if (record instanceof GroupInfoV1
) {
2256 var groupInfo
= (GroupInfoV1
) record;
2257 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2258 Optional
.fromNullable(groupInfo
.name
),
2259 new ArrayList
<>(groupInfo
.getMembers()),
2260 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2261 groupInfo
.isMember(account
.getSelfAddress()),
2262 Optional
.of(groupInfo
.messageExpirationTime
),
2263 Optional
.fromNullable(groupInfo
.color
),
2265 Optional
.fromNullable(groupInfo
.inboxPosition
),
2266 groupInfo
.archived
));
2271 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2272 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2273 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2274 .withStream(groupsFileStream
)
2275 .withContentType("application/octet-stream")
2276 .withLength(groupsFile
.length())
2279 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2284 Files
.delete(groupsFile
.toPath());
2285 } catch (IOException e
) {
2286 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2291 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2292 var contactsFile
= IOUtils
.createTempFile();
2295 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2296 var out
= new DeviceContactsOutputStream(fos
);
2297 for (var record : account
.getContactStore().getContacts()) {
2298 VerifiedMessage verifiedMessage
= null;
2299 var currentIdentity
= account
.getIdentityKeyStore()
2300 .getIdentity(resolveRecipientTrusted(record.getAddress()));
2301 if (currentIdentity
!= null) {
2302 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2303 currentIdentity
.getIdentityKey(),
2304 currentIdentity
.getTrustLevel().toVerifiedState(),
2305 currentIdentity
.getDateAdded().getTime());
2308 var profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2309 out
.write(new DeviceContact(record.getAddress(),
2310 Optional
.fromNullable(record.name
),
2311 createContactAvatarAttachment(record.getAddress()),
2312 Optional
.fromNullable(record.color
),
2313 Optional
.fromNullable(verifiedMessage
),
2314 Optional
.fromNullable(profileKey
),
2316 Optional
.of(record.messageExpirationTime
),
2317 Optional
.fromNullable(record.inboxPosition
),
2321 if (account
.getProfileKey() != null) {
2322 // Send our own profile key as well
2323 out
.write(new DeviceContact(account
.getSelfAddress(),
2328 Optional
.of(account
.getProfileKey()),
2336 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2337 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2338 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2339 .withStream(contactsFileStream
)
2340 .withContentType("application/octet-stream")
2341 .withLength(contactsFile
.length())
2344 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2349 Files
.delete(contactsFile
.toPath());
2350 } catch (IOException e
) {
2351 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2356 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2357 var addresses
= new ArrayList
<SignalServiceAddress
>();
2358 for (var record : account
.getContactStore().getContacts()) {
2359 if (record.blocked
) {
2360 addresses
.add(record.getAddress());
2363 var groupIds
= new ArrayList
<byte[]>();
2364 for (var record : getGroups()) {
2365 if (record.isBlocked()) {
2366 groupIds
.add(record.getGroupId().serialize());
2369 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2372 private void sendVerifiedMessage(
2373 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2374 ) throws IOException
, UntrustedIdentityException
{
2375 var verifiedMessage
= new VerifiedMessage(destination
,
2377 trustLevel
.toVerifiedState(),
2378 System
.currentTimeMillis());
2379 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2382 public List
<ContactInfo
> getContacts() {
2383 return account
.getContactStore().getContacts();
2386 public String
getContactOrProfileName(String number
) {
2387 final var address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2389 final var contact
= account
.getContactStore().getContact(address
);
2390 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2391 return contact
.name
;
2394 final var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2395 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2396 return profileEntry
.getProfile().getDisplayName();
2401 public GroupInfo
getGroup(GroupId groupId
) {
2402 final var group
= account
.getGroupStore().getGroup(groupId
);
2403 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2404 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2405 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2406 account
.getGroupStore().updateGroup(group
);
2411 public List
<IdentityInfo
> getIdentities() {
2412 return account
.getIdentityKeyStore().getIdentities();
2415 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2416 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2417 return identity
== null ? List
.of() : List
.of(identity
);
2421 * Trust this the identity with this fingerprint
2423 * @param name username of the identity
2424 * @param fingerprint Fingerprint
2426 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2427 var recipientId
= canonicalizeAndResolveRecipient(name
);
2428 return trustIdentity(recipientId
,
2429 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2430 TrustLevel
.TRUSTED_VERIFIED
);
2434 * Trust this the identity with this safety number
2436 * @param name username of the identity
2437 * @param safetyNumber Safety number
2439 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2440 var recipientId
= canonicalizeAndResolveRecipient(name
);
2441 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2442 return trustIdentity(recipientId
,
2443 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2444 TrustLevel
.TRUSTED_VERIFIED
);
2448 * Trust all keys of this identity without verification
2450 * @param name username of the identity
2452 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2453 var recipientId
= canonicalizeAndResolveRecipient(name
);
2454 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2457 private boolean trustIdentity(
2458 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2460 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2461 if (identity
== null) {
2465 if (!verifier
.apply(identity
.getIdentityKey())) {
2469 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2471 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2472 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2473 } catch (IOException
| UntrustedIdentityException e
) {
2474 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2480 public String
computeSafetyNumber(
2481 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2483 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2484 account
.getSelfAddress(),
2485 getIdentityKeyPair().getPublicKey(),
2491 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2492 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2494 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2495 return resolveSignalServiceAddress(canonicalizedNumber
);
2499 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2500 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2502 return resolveSignalServiceAddress(address
);
2506 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2507 if (address
.matches(account
.getSelfAddress())) {
2508 return account
.getSelfAddress();
2511 return account
.getRecipientStore().resolveServiceAddress(address
);
2514 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2515 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2518 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2519 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2521 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2523 return resolveRecipient(canonicalizedNumber
);
2526 private RecipientId
resolveRecipient(final String identifier
) {
2527 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2529 return resolveRecipient(address
);
2532 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2533 return account
.getRecipientStore().resolveRecipientUntrusted(address
);
2536 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2537 return account
.getRecipientStore().resolveRecipient(address
);
2541 public void close() throws IOException
{
2545 void close(boolean closeAccount
) throws IOException
{
2546 executor
.shutdown();
2548 if (messagePipe
!= null) {
2549 messagePipe
.shutdown();
2553 if (unidentifiedMessagePipe
!= null) {
2554 unidentifiedMessagePipe
.shutdown();
2555 unidentifiedMessagePipe
= null;
2558 if (closeAccount
&& account
!= null) {
2564 public interface ReceiveMessageHandler
{
2566 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);