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
.Collection
;
150 import java
.util
.Date
;
151 import java
.util
.HashSet
;
152 import java
.util
.List
;
153 import java
.util
.Map
;
154 import java
.util
.Set
;
155 import java
.util
.UUID
;
156 import java
.util
.concurrent
.ExecutorService
;
157 import java
.util
.concurrent
.Executors
;
158 import java
.util
.concurrent
.TimeUnit
;
159 import java
.util
.concurrent
.TimeoutException
;
160 import java
.util
.function
.Function
;
161 import java
.util
.stream
.Collectors
;
163 import static org
.asamk
.signal
.manager
.config
.ServiceConfig
.capabilities
;
165 public class Manager
implements Closeable
{
167 private final static Logger logger
= LoggerFactory
.getLogger(Manager
.class);
169 private final CertificateValidator certificateValidator
;
171 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
172 private final String userAgent
;
174 private SignalAccount account
;
175 private final SignalServiceAccountManager accountManager
;
176 private final GroupsV2Api groupsV2Api
;
177 private final GroupsV2Operations groupsV2Operations
;
178 private final SignalServiceMessageReceiver messageReceiver
;
179 private final ClientZkProfileOperations clientZkProfileOperations
;
181 private final ExecutorService executor
= Executors
.newCachedThreadPool();
183 private SignalServiceMessagePipe messagePipe
= null;
184 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
186 private final UnidentifiedAccessHelper unidentifiedAccessHelper
;
187 private final ProfileHelper profileHelper
;
188 private final GroupHelper groupHelper
;
189 private final PinHelper pinHelper
;
190 private final AvatarStore avatarStore
;
191 private final AttachmentStore attachmentStore
;
194 SignalAccount account
,
195 PathConfig pathConfig
,
196 ServiceEnvironmentConfig serviceEnvironmentConfig
,
199 this.account
= account
;
200 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
201 this.certificateValidator
= new CertificateValidator(serviceEnvironmentConfig
.getUnidentifiedSenderTrustRoot());
202 this.userAgent
= userAgent
;
203 this.groupsV2Operations
= capabilities
.isGv2() ?
new GroupsV2Operations(ClientZkOperations
.create(
204 serviceEnvironmentConfig
.getSignalServiceConfiguration())) : null;
205 final SleepTimer timer
= new UptimeSleepTimer();
206 this.accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
207 new DynamicCredentialsProvider(account
.getUuid(),
208 account
.getUsername(),
209 account
.getPassword(),
210 account
.getDeviceId()),
213 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
215 this.groupsV2Api
= accountManager
.getGroupsV2Api();
216 final var keyBackupService
= accountManager
.getKeyBackupService(ServiceConfig
.getIasKeyStore(),
217 serviceEnvironmentConfig
.getKeyBackupConfig().getEnclaveName(),
218 serviceEnvironmentConfig
.getKeyBackupConfig().getServiceId(),
219 serviceEnvironmentConfig
.getKeyBackupConfig().getMrenclave(),
222 this.pinHelper
= new PinHelper(keyBackupService
);
223 this.clientZkProfileOperations
= capabilities
.isGv2()
224 ? ClientZkOperations
.create(serviceEnvironmentConfig
.getSignalServiceConfiguration())
225 .getProfileOperations()
227 this.messageReceiver
= new SignalServiceMessageReceiver(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
229 account
.getUsername(),
230 account
.getPassword(),
231 account
.getDeviceId(),
235 clientZkProfileOperations
,
236 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
238 this.unidentifiedAccessHelper
= new UnidentifiedAccessHelper(account
::getProfileKey
,
239 account
.getProfileStore()::getProfileKey
,
240 this::getRecipientProfile
,
241 this::getSenderCertificate
);
242 this.profileHelper
= new ProfileHelper(account
.getProfileStore()::getProfileKey
,
243 unidentifiedAccessHelper
::getAccessFor
,
244 unidentified
-> unidentified ?
getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
245 () -> messageReceiver
);
246 this.groupHelper
= new GroupHelper(this::getRecipientProfileKeyCredential
,
247 this::getRecipientProfile
,
248 account
::getSelfAddress
,
251 this::getGroupAuthForToday
);
252 this.avatarStore
= new AvatarStore(pathConfig
.getAvatarsPath());
253 this.attachmentStore
= new AttachmentStore(pathConfig
.getAttachmentsPath());
256 public String
getUsername() {
257 return account
.getUsername();
260 public SignalServiceAddress
getSelfAddress() {
261 return account
.getSelfAddress();
264 private IdentityKeyPair
getIdentityKeyPair() {
265 return account
.getIdentityKeyPair();
268 public int getDeviceId() {
269 return account
.getDeviceId();
272 public static Manager
init(
273 String username
, File settingsPath
, ServiceEnvironment serviceEnvironment
, String userAgent
274 ) throws IOException
, NotRegisteredException
{
275 var pathConfig
= PathConfig
.createDefault(settingsPath
);
277 if (!SignalAccount
.userExists(pathConfig
.getDataPath(), username
)) {
278 throw new NotRegisteredException();
281 var account
= SignalAccount
.load(pathConfig
.getDataPath(), username
);
283 if (!account
.isRegistered()) {
284 throw new NotRegisteredException();
287 final var serviceEnvironmentConfig
= ServiceConfig
.getServiceEnvironmentConfig(serviceEnvironment
, userAgent
);
289 return new Manager(account
, pathConfig
, serviceEnvironmentConfig
, userAgent
);
292 public static List
<String
> getAllLocalUsernames(File settingsPath
) {
293 var pathConfig
= PathConfig
.createDefault(settingsPath
);
294 final var dataPath
= pathConfig
.getDataPath();
295 final var files
= dataPath
.listFiles();
301 return Arrays
.stream(files
)
302 .filter(File
::isFile
)
304 .filter(file
-> PhoneNumberFormatter
.isValidNumber(file
, null))
305 .collect(Collectors
.toList());
308 public void checkAccountState() throws IOException
{
309 if (accountManager
.getPreKeysCount() < ServiceConfig
.PREKEY_MINIMUM_COUNT
) {
313 if (account
.getUuid() == null) {
314 account
.setUuid(accountManager
.getOwnUuid());
317 updateAccountAttributes();
321 * This is used for checking a set of phone numbers for registration on Signal
323 * @param numbers The set of phone number in question
324 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
325 * @throws IOException if its unable to get the contacts to check if they're registered
327 public Map
<String
, Boolean
> areUsersRegistered(Set
<String
> numbers
) throws IOException
{
328 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
329 var contactDetails
= getRegisteredUsers(numbers
);
331 var registeredUsers
= contactDetails
.keySet();
333 return numbers
.stream().collect(Collectors
.toMap(x
-> x
, registeredUsers
::contains
));
336 public void updateAccountAttributes() throws IOException
{
337 accountManager
.setAccountAttributes(null,
338 account
.getLocalRegistrationId(),
340 // set legacy pin only if no KBS master key is set
341 account
.getPinMasterKey() == null ? account
.getRegistrationLockPin() : null,
342 account
.getPinMasterKey() == null ?
null : account
.getPinMasterKey().deriveRegistrationLock(),
343 account
.getSelfUnidentifiedAccessKey(),
344 account
.isUnrestrictedUnidentifiedAccess(),
346 account
.isDiscoverableByPhoneNumber());
350 * @param name if null, the previous name will be kept
351 * @param about if null, the previous about text will be kept
352 * @param aboutEmoji if null, the previous about emoji will be kept
353 * @param avatar if avatar is null the image from the local avatar store is used (if present),
354 * if it's Optional.absent(), the avatar will be removed
356 public void setProfile(String name
, String about
, String aboutEmoji
, Optional
<File
> avatar
) throws IOException
{
357 var profileEntry
= account
.getProfileStore().getProfileEntry(getSelfAddress());
358 var profile
= profileEntry
== null ?
null : profileEntry
.getProfile();
359 var newProfile
= new SignalProfile(profile
== null ?
null : profile
.getIdentityKey(),
360 name
!= null ? name
: profile
== null || profile
.getName() == null ?
"" : profile
.getName(),
361 about
!= null ? about
: profile
== null || profile
.getAbout() == null ?
"" : profile
.getAbout(),
364 : profile
== null || profile
.getAboutEmoji() == null ?
"" : profile
.getAboutEmoji(),
365 profile
== null ?
null : profile
.getUnidentifiedAccess(),
366 account
.isUnrestrictedUnidentifiedAccess(),
367 profile
== null ?
null : profile
.getCapabilities());
369 try (final var streamDetails
= avatar
== null
370 ? avatarStore
.retrieveProfileAvatar(getSelfAddress())
371 : avatar
.isPresent() ? Utils
.createStreamDetailsFromFile(avatar
.get()) : null) {
372 accountManager
.setVersionedProfile(account
.getUuid(),
373 account
.getProfileKey(),
374 newProfile
.getName(),
375 newProfile
.getAbout(),
376 newProfile
.getAboutEmoji(),
380 if (avatar
!= null) {
381 if (avatar
.isPresent()) {
382 avatarStore
.storeProfileAvatar(getSelfAddress(),
383 outputStream
-> IOUtils
.copyFileToStream(avatar
.get(), outputStream
));
385 avatarStore
.deleteProfileAvatar(getSelfAddress());
388 account
.getProfileStore()
389 .updateProfile(getSelfAddress(),
390 account
.getProfileKey(),
391 System
.currentTimeMillis(),
393 profileEntry
== null ?
null : profileEntry
.getProfileKeyCredential());
396 sendSyncMessage(SignalServiceSyncMessage
.forFetchLatest(SignalServiceSyncMessage
.FetchType
.LOCAL_PROFILE
));
397 } catch (UntrustedIdentityException ignored
) {
401 public void unregister() throws IOException
{
402 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
403 // If this is the master device, other users can't send messages to this number anymore.
404 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
405 accountManager
.setGcmId(Optional
.absent());
406 accountManager
.deleteAccount();
408 account
.setRegistered(false);
412 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
413 var devices
= accountManager
.getDevices();
414 account
.setMultiDevice(devices
.size() > 1);
419 public void removeLinkedDevices(int deviceId
) throws IOException
{
420 accountManager
.removeDevice(deviceId
);
421 var devices
= accountManager
.getDevices();
422 account
.setMultiDevice(devices
.size() > 1);
426 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
427 var info
= DeviceLinkInfo
.parseDeviceLinkUri(linkUri
);
429 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
432 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
433 var identityKeyPair
= getIdentityKeyPair();
434 var verificationCode
= accountManager
.getNewDeviceVerificationCode();
436 accountManager
.addDevice(deviceIdentifier
,
439 Optional
.of(account
.getProfileKey().serialize()),
441 account
.setMultiDevice(true);
445 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
, UnauthenticatedResponseException
{
446 if (!account
.isMasterDevice()) {
447 throw new RuntimeException("Only master device can set a PIN");
449 if (pin
.isPresent()) {
450 final var masterKey
= account
.getPinMasterKey() != null
451 ? account
.getPinMasterKey()
452 : KeyUtils
.createMasterKey();
454 pinHelper
.setRegistrationLockPin(pin
.get(), masterKey
);
456 account
.setRegistrationLockPin(pin
.get());
457 account
.setPinMasterKey(masterKey
);
459 // Remove legacy registration lock
460 accountManager
.removeRegistrationLockV1();
463 pinHelper
.removeRegistrationLockPin();
465 account
.setRegistrationLockPin(null);
466 account
.setPinMasterKey(null);
471 void refreshPreKeys() throws IOException
{
472 var oneTimePreKeys
= generatePreKeys();
473 final var identityKeyPair
= getIdentityKeyPair();
474 var signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
476 accountManager
.setPreKeys(identityKeyPair
.getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
479 private List
<PreKeyRecord
> generatePreKeys() {
480 final var offset
= account
.getPreKeyIdOffset();
482 var records
= KeyUtils
.generatePreKeyRecords(offset
, ServiceConfig
.PREKEY_BATCH_SIZE
);
483 account
.addPreKeys(records
);
488 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
489 final var signedPreKeyId
= account
.getNextSignedPreKeyId();
491 var record = KeyUtils
.generateSignedPreKeyRecord(identityKeyPair
, signedPreKeyId
);
492 account
.addSignedPreKey(record);
497 private SignalServiceMessagePipe
getOrCreateMessagePipe() {
498 if (messagePipe
== null) {
499 messagePipe
= messageReceiver
.createMessagePipe();
504 private SignalServiceMessagePipe
getOrCreateUnidentifiedMessagePipe() {
505 if (unidentifiedMessagePipe
== null) {
506 unidentifiedMessagePipe
= messageReceiver
.createUnidentifiedMessagePipe();
508 return unidentifiedMessagePipe
;
511 private SignalServiceMessageSender
createMessageSender() {
512 return new SignalServiceMessageSender(serviceEnvironmentConfig
.getSignalServiceConfiguration(),
514 account
.getUsername(),
515 account
.getPassword(),
516 account
.getDeviceId(),
517 account
.getSignalProtocolStore(),
519 account
.isMultiDevice(),
520 Optional
.fromNullable(messagePipe
),
521 Optional
.fromNullable(unidentifiedMessagePipe
),
523 clientZkProfileOperations
,
525 ServiceConfig
.MAX_ENVELOPE_SIZE
,
526 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
529 public SignalProfile
getRecipientProfile(
530 SignalServiceAddress address
532 return getRecipientProfile(address
, false);
535 private SignalProfile
getRecipientProfile(
536 SignalServiceAddress address
, boolean force
538 var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
539 if (profileEntry
== null) {
542 var now
= new Date().getTime();
543 // Profiles are cached for 24h before retrieving them again
544 if (!profileEntry
.isRequestPending() && (
546 || profileEntry
.getProfile() == null
547 || now
- profileEntry
.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
549 profileEntry
.setRequestPending(true);
550 final SignalServiceProfile encryptedProfile
;
552 encryptedProfile
= profileHelper
.retrieveProfileSync(address
, SignalServiceProfile
.RequestType
.PROFILE
)
554 } catch (IOException e
) {
555 logger
.warn("Failed to retrieve profile, ignoring: {}", e
.getMessage());
558 profileEntry
.setRequestPending(false);
561 final var profileKey
= profileEntry
.getProfileKey();
562 final var profile
= decryptProfileAndDownloadAvatar(address
, profileKey
, encryptedProfile
);
563 account
.getProfileStore()
564 .updateProfile(address
, profileKey
, now
, profile
, profileEntry
.getProfileKeyCredential());
567 return profileEntry
.getProfile();
570 private ProfileKeyCredential
getRecipientProfileKeyCredential(SignalServiceAddress address
) {
571 var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
572 if (profileEntry
== null) {
575 if (profileEntry
.getProfileKeyCredential() == null) {
576 ProfileAndCredential profileAndCredential
;
578 profileAndCredential
= profileHelper
.retrieveProfileSync(address
,
579 SignalServiceProfile
.RequestType
.PROFILE_AND_CREDENTIAL
);
580 } catch (IOException e
) {
581 logger
.warn("Failed to retrieve profile key credential, ignoring: {}", e
.getMessage());
585 var now
= new Date().getTime();
586 final var profileKeyCredential
= profileAndCredential
.getProfileKeyCredential().orNull();
587 final var profile
= decryptProfileAndDownloadAvatar(address
,
588 profileEntry
.getProfileKey(),
589 profileAndCredential
.getProfile());
590 account
.getProfileStore()
591 .updateProfile(address
, profileEntry
.getProfileKey(), now
, profile
, profileKeyCredential
);
592 return profileKeyCredential
;
594 return profileEntry
.getProfileKeyCredential();
597 private SignalProfile
decryptProfileAndDownloadAvatar(
598 final SignalServiceAddress address
, final ProfileKey profileKey
, final SignalServiceProfile encryptedProfile
600 if (encryptedProfile
.getAvatar() != null) {
601 downloadProfileAvatar(address
, encryptedProfile
.getAvatar(), profileKey
);
604 return ProfileUtils
.decryptProfile(profileKey
, encryptedProfile
);
607 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(GroupId groupId
) throws IOException
{
608 final var streamDetails
= avatarStore
.retrieveGroupAvatar(groupId
);
609 if (streamDetails
== null) {
610 return Optional
.absent();
613 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
616 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(SignalServiceAddress address
) throws IOException
{
617 final var streamDetails
= avatarStore
.retrieveContactAvatar(address
);
618 if (streamDetails
== null) {
619 return Optional
.absent();
622 return Optional
.of(AttachmentUtils
.createAttachment(streamDetails
, Optional
.absent()));
625 private GroupInfo
getGroupForSending(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
626 var g
= getGroup(groupId
);
628 throw new GroupNotFoundException(groupId
);
630 if (!g
.isMember(account
.getSelfAddress())) {
631 throw new NotAGroupMemberException(groupId
, g
.getTitle());
636 private GroupInfo
getGroupForUpdating(GroupId groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
637 var g
= getGroup(groupId
);
639 throw new GroupNotFoundException(groupId
);
641 if (!g
.isMember(account
.getSelfAddress()) && !g
.isPendingMember(account
.getSelfAddress())) {
642 throw new NotAGroupMemberException(groupId
, g
.getTitle());
647 public List
<GroupInfo
> getGroups() {
648 return account
.getGroupStore().getGroups();
651 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
652 String messageText
, List
<String
> attachments
, GroupId groupId
653 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
654 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
655 if (attachments
!= null) {
656 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
659 return sendGroupMessage(messageBuilder
, groupId
);
662 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessageReaction(
663 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, GroupId groupId
664 ) throws IOException
, InvalidNumberException
, NotAGroupMemberException
, GroupNotFoundException
{
665 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
667 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
668 targetSentTimestamp
);
669 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
671 return sendGroupMessage(messageBuilder
, groupId
);
674 public Pair
<Long
, List
<SendMessageResult
>> sendGroupMessage(
675 SignalServiceDataMessage
.Builder messageBuilder
, GroupId groupId
676 ) throws IOException
, GroupNotFoundException
, NotAGroupMemberException
{
677 final var g
= getGroupForSending(groupId
);
679 GroupUtils
.setGroupContext(messageBuilder
, g
);
680 messageBuilder
.withExpiration(g
.getMessageExpirationTime());
682 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
685 public Pair
<Long
, List
<SendMessageResult
>> sendQuitGroupMessage(GroupId groupId
) throws GroupNotFoundException
, IOException
, NotAGroupMemberException
{
686 SignalServiceDataMessage
.Builder messageBuilder
;
688 final var g
= getGroupForUpdating(groupId
);
689 if (g
instanceof GroupInfoV1
) {
690 var groupInfoV1
= (GroupInfoV1
) g
;
691 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
).withId(groupId
.serialize()).build();
692 messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
);
693 groupInfoV1
.removeMember(account
.getSelfAddress());
694 account
.getGroupStore().updateGroup(groupInfoV1
);
696 final var groupInfoV2
= (GroupInfoV2
) g
;
697 final var groupGroupChangePair
= groupHelper
.leaveGroup(groupInfoV2
);
698 groupInfoV2
.setGroup(groupGroupChangePair
.first());
699 messageBuilder
= getGroupUpdateMessageBuilder(groupInfoV2
, groupGroupChangePair
.second().toByteArray());
700 account
.getGroupStore().updateGroup(groupInfoV2
);
703 return sendMessage(messageBuilder
, g
.getMembersWithout(account
.getSelfAddress()));
706 public Pair
<GroupId
, List
<SendMessageResult
>> updateGroup(
707 GroupId groupId
, String name
, List
<String
> members
, File avatarFile
708 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, InvalidNumberException
, NotAGroupMemberException
{
709 return sendUpdateGroupMessage(groupId
,
711 members
== null ?
null : getSignalServiceAddresses(members
),
715 private Pair
<GroupId
, List
<SendMessageResult
>> sendUpdateGroupMessage(
716 GroupId groupId
, String name
, Collection
<SignalServiceAddress
> members
, File avatarFile
717 ) throws IOException
, GroupNotFoundException
, AttachmentInvalidException
, NotAGroupMemberException
{
719 SignalServiceDataMessage
.Builder messageBuilder
;
720 if (groupId
== null) {
722 var gv2
= groupHelper
.createGroupV2(name
== null ?
"" : name
,
723 members
== null ? List
.of() : members
,
726 var gv1
= new GroupInfoV1(GroupIdV1
.createRandom());
727 gv1
.addMembers(List
.of(account
.getSelfAddress()));
728 updateGroupV1(gv1
, name
, members
, avatarFile
);
729 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
732 if (avatarFile
!= null) {
733 avatarStore
.storeGroupAvatar(gv2
.getGroupId(),
734 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
736 messageBuilder
= getGroupUpdateMessageBuilder(gv2
, null);
740 var group
= getGroupForUpdating(groupId
);
741 if (group
instanceof GroupInfoV2
) {
742 final var groupInfoV2
= (GroupInfoV2
) group
;
744 Pair
<Long
, List
<SendMessageResult
>> result
= null;
745 if (groupInfoV2
.isPendingMember(getSelfAddress())) {
746 var groupGroupChangePair
= groupHelper
.acceptInvite(groupInfoV2
);
747 result
= sendUpdateGroupMessage(groupInfoV2
,
748 groupGroupChangePair
.first(),
749 groupGroupChangePair
.second());
752 if (members
!= null) {
753 final var newMembers
= new HashSet
<>(members
);
754 newMembers
.removeAll(group
.getMembers()
756 .map(this::resolveSignalServiceAddress
)
757 .collect(Collectors
.toSet()));
758 if (newMembers
.size() > 0) {
759 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, newMembers
);
760 result
= sendUpdateGroupMessage(groupInfoV2
,
761 groupGroupChangePair
.first(),
762 groupGroupChangePair
.second());
765 if (result
== null || name
!= null || avatarFile
!= null) {
766 var groupGroupChangePair
= groupHelper
.updateGroupV2(groupInfoV2
, name
, avatarFile
);
767 if (avatarFile
!= null) {
768 avatarStore
.storeGroupAvatar(groupInfoV2
.getGroupId(),
769 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
771 result
= sendUpdateGroupMessage(groupInfoV2
,
772 groupGroupChangePair
.first(),
773 groupGroupChangePair
.second());
776 return new Pair
<>(group
.getGroupId(), result
.second());
778 var gv1
= (GroupInfoV1
) group
;
779 updateGroupV1(gv1
, name
, members
, avatarFile
);
780 messageBuilder
= getGroupUpdateMessageBuilder(gv1
);
785 account
.getGroupStore().updateGroup(g
);
787 final var result
= sendMessage(messageBuilder
, g
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
788 return new Pair
<>(g
.getGroupId(), result
.second());
791 private void updateGroupV1(
794 final Collection
<SignalServiceAddress
> members
,
795 final File avatarFile
796 ) throws IOException
{
801 if (members
!= null) {
802 final var newE164Members
= new HashSet
<String
>();
803 for (var member
: members
) {
804 if (g
.isMember(member
) || !member
.getNumber().isPresent()) {
807 newE164Members
.add(member
.getNumber().get());
810 final var registeredUsers
= getRegisteredUsers(newE164Members
);
811 if (registeredUsers
.size() != newE164Members
.size()) {
812 // Some of the new members are not registered on Signal
813 newE164Members
.removeAll(registeredUsers
.keySet());
814 throw new IOException("Failed to add members "
815 + String
.join(", ", newE164Members
)
816 + " to group: Not registered on Signal");
819 g
.addMembers(members
);
822 if (avatarFile
!= null) {
823 avatarStore
.storeGroupAvatar(g
.getGroupId(),
824 outputStream
-> IOUtils
.copyFileToStream(avatarFile
, outputStream
));
828 public Pair
<GroupId
, List
<SendMessageResult
>> joinGroup(
829 GroupInviteLinkUrl inviteLinkUrl
830 ) throws IOException
, GroupLinkNotActiveException
{
831 return sendJoinGroupMessage(inviteLinkUrl
);
834 private Pair
<GroupId
, List
<SendMessageResult
>> sendJoinGroupMessage(
835 GroupInviteLinkUrl inviteLinkUrl
836 ) throws IOException
, GroupLinkNotActiveException
{
837 final var groupJoinInfo
= groupHelper
.getDecryptedGroupJoinInfo(inviteLinkUrl
.getGroupMasterKey(),
838 inviteLinkUrl
.getPassword());
839 final var groupChange
= groupHelper
.joinGroup(inviteLinkUrl
.getGroupMasterKey(),
840 inviteLinkUrl
.getPassword(),
842 final var group
= getOrMigrateGroup(inviteLinkUrl
.getGroupMasterKey(),
843 groupJoinInfo
.getRevision() + 1,
844 groupChange
.toByteArray());
846 if (group
.getGroup() == null) {
847 // Only requested member, can't send update to group members
848 return new Pair
<>(group
.getGroupId(), List
.of());
851 final var result
= sendUpdateGroupMessage(group
, group
.getGroup(), groupChange
);
853 return new Pair
<>(group
.getGroupId(), result
.second());
856 private static int currentTimeDays() {
857 return (int) TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis());
860 private GroupsV2AuthorizationString
getGroupAuthForToday(
861 final GroupSecretParams groupSecretParams
862 ) throws IOException
{
863 final var today
= currentTimeDays();
864 // Returns credentials for the next 7 days
865 final var credentials
= groupsV2Api
.getCredentials(today
);
866 // TODO cache credentials until they expire
867 var authCredentialResponse
= credentials
.get(today
);
869 return groupsV2Api
.getGroupsV2AuthorizationString(account
.getUuid(),
872 authCredentialResponse
);
873 } catch (VerificationFailedException e
) {
874 throw new IOException(e
);
878 private Pair
<Long
, List
<SendMessageResult
>> sendUpdateGroupMessage(
879 GroupInfoV2 group
, DecryptedGroup newDecryptedGroup
, GroupChange groupChange
880 ) throws IOException
{
881 group
.setGroup(newDecryptedGroup
);
882 final var messageBuilder
= getGroupUpdateMessageBuilder(group
, groupChange
.toByteArray());
883 account
.getGroupStore().updateGroup(group
);
884 return sendMessage(messageBuilder
, group
.getMembersIncludingPendingWithout(account
.getSelfAddress()));
887 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoMessage(
888 GroupIdV1 groupId
, SignalServiceAddress recipient
889 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
, AttachmentInvalidException
{
891 var group
= getGroupForSending(groupId
);
892 if (!(group
instanceof GroupInfoV1
)) {
893 throw new RuntimeException("Received an invalid group request for a v2 group!");
895 g
= (GroupInfoV1
) group
;
897 if (!g
.isMember(recipient
)) {
898 throw new NotAGroupMemberException(groupId
, g
.name
);
901 var messageBuilder
= getGroupUpdateMessageBuilder(g
);
903 // Send group message only to the recipient who requested it
904 return sendMessage(messageBuilder
, List
.of(recipient
));
907 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV1 g
) throws AttachmentInvalidException
{
908 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
909 .withId(g
.getGroupId().serialize())
911 .withMembers(new ArrayList
<>(g
.getMembers()));
914 final var attachment
= createGroupAvatarAttachment(g
.getGroupId());
915 if (attachment
.isPresent()) {
916 group
.withAvatar(attachment
.get());
918 } catch (IOException e
) {
919 throw new AttachmentInvalidException(g
.getGroupId().toBase64(), e
);
922 return SignalServiceDataMessage
.newBuilder()
923 .asGroupMessage(group
.build())
924 .withExpiration(g
.getMessageExpirationTime());
927 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfoV2 g
, byte[] signedGroupChange
) {
928 var group
= SignalServiceGroupV2
.newBuilder(g
.getMasterKey())
929 .withRevision(g
.getGroup().getRevision())
930 .withSignedGroupChange(signedGroupChange
);
931 return SignalServiceDataMessage
.newBuilder()
932 .asGroupMessage(group
.build())
933 .withExpiration(g
.getMessageExpirationTime());
936 Pair
<Long
, List
<SendMessageResult
>> sendGroupInfoRequest(
937 GroupIdV1 groupId
, SignalServiceAddress recipient
938 ) throws IOException
{
939 var group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
).withId(groupId
.serialize());
941 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asGroupMessage(group
.build());
943 // Send group info request message to the recipient who sent us a message with this groupId
944 return sendMessage(messageBuilder
, List
.of(recipient
));
948 SignalServiceAddress remoteAddress
, long messageId
949 ) throws IOException
, UntrustedIdentityException
{
950 var receiptMessage
= new SignalServiceReceiptMessage(SignalServiceReceiptMessage
.Type
.DELIVERY
,
952 System
.currentTimeMillis());
954 createMessageSender().sendReceipt(remoteAddress
,
955 unidentifiedAccessHelper
.getAccessFor(remoteAddress
),
959 public Pair
<Long
, List
<SendMessageResult
>> sendMessage(
960 String messageText
, List
<String
> attachments
, List
<String
> recipients
961 ) throws IOException
, AttachmentInvalidException
, InvalidNumberException
{
962 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
963 if (attachments
!= null) {
964 var attachmentStreams
= AttachmentUtils
.getSignalServiceAttachments(attachments
);
966 // Upload attachments here, so we only upload once even for multiple recipients
967 var messageSender
= createMessageSender();
968 var attachmentPointers
= new ArrayList
<SignalServiceAttachment
>(attachmentStreams
.size());
969 for (var attachment
: attachmentStreams
) {
970 if (attachment
.isStream()) {
971 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
972 } else if (attachment
.isPointer()) {
973 attachmentPointers
.add(attachment
.asPointer());
977 messageBuilder
.withAttachments(attachmentPointers
);
979 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
982 public Pair
<Long
, SendMessageResult
> sendSelfMessage(
983 String messageText
, List
<String
> attachments
984 ) throws IOException
, AttachmentInvalidException
{
985 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
986 if (attachments
!= null) {
987 messageBuilder
.withAttachments(AttachmentUtils
.getSignalServiceAttachments(attachments
));
989 return sendSelfMessage(messageBuilder
);
992 public Pair
<Long
, List
<SendMessageResult
>> sendRemoteDeleteMessage(
993 long targetSentTimestamp
, List
<String
> recipients
994 ) throws IOException
, InvalidNumberException
{
995 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
996 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
997 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1000 public Pair
<Long
, List
<SendMessageResult
>> sendGroupRemoteDeleteMessage(
1001 long targetSentTimestamp
, GroupId groupId
1002 ) throws IOException
, NotAGroupMemberException
, GroupNotFoundException
{
1003 var delete
= new SignalServiceDataMessage
.RemoteDelete(targetSentTimestamp
);
1004 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withRemoteDelete(delete
);
1005 return sendGroupMessage(messageBuilder
, groupId
);
1008 public Pair
<Long
, List
<SendMessageResult
>> sendMessageReaction(
1009 String emoji
, boolean remove
, String targetAuthor
, long targetSentTimestamp
, List
<String
> recipients
1010 ) throws IOException
, InvalidNumberException
{
1011 var reaction
= new SignalServiceDataMessage
.Reaction(emoji
,
1013 canonicalizeAndResolveSignalServiceAddress(targetAuthor
),
1014 targetSentTimestamp
);
1015 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().withReaction(reaction
);
1016 return sendMessage(messageBuilder
, getSignalServiceAddresses(recipients
));
1019 public Pair
<Long
, List
<SendMessageResult
>> sendEndSessionMessage(List
<String
> recipients
) throws IOException
, InvalidNumberException
{
1020 var messageBuilder
= SignalServiceDataMessage
.newBuilder().asEndSessionMessage();
1022 final var signalServiceAddresses
= getSignalServiceAddresses(recipients
);
1024 return sendMessage(messageBuilder
, signalServiceAddresses
);
1025 } catch (Exception e
) {
1026 for (var address
: signalServiceAddresses
) {
1027 handleEndSession(address
);
1034 public String
getContactName(String number
) throws InvalidNumberException
{
1035 var contact
= account
.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number
));
1036 if (contact
== null) {
1039 return contact
.name
;
1043 public void setContactName(String number
, String name
) throws InvalidNumberException
{
1044 final var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1045 var contact
= account
.getContactStore().getContact(address
);
1046 if (contact
== null) {
1047 contact
= new ContactInfo(address
);
1049 contact
.name
= name
;
1050 account
.getContactStore().updateContact(contact
);
1054 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
1055 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number
), blocked
);
1058 private void setContactBlocked(SignalServiceAddress address
, boolean blocked
) {
1059 var contact
= account
.getContactStore().getContact(address
);
1060 if (contact
== null) {
1061 contact
= new ContactInfo(address
);
1063 contact
.blocked
= blocked
;
1064 account
.getContactStore().updateContact(contact
);
1068 public void setGroupBlocked(final GroupId groupId
, final boolean blocked
) throws GroupNotFoundException
{
1069 var group
= getGroup(groupId
);
1070 if (group
== null) {
1071 throw new GroupNotFoundException(groupId
);
1074 group
.setBlocked(blocked
);
1075 account
.getGroupStore().updateGroup(group
);
1080 * Change the expiration timer for a contact
1082 public void setExpirationTimer(SignalServiceAddress address
, int messageExpirationTimer
) throws IOException
{
1083 var contact
= account
.getContactStore().getContact(address
);
1084 contact
.messageExpirationTime
= messageExpirationTimer
;
1085 account
.getContactStore().updateContact(contact
);
1086 sendExpirationTimerUpdate(address
);
1090 private void sendExpirationTimerUpdate(SignalServiceAddress address
) throws IOException
{
1091 final var messageBuilder
= SignalServiceDataMessage
.newBuilder().asExpirationUpdate();
1092 sendMessage(messageBuilder
, List
.of(address
));
1096 * Change the expiration timer for a contact
1098 public void setExpirationTimer(
1099 String number
, int messageExpirationTimer
1100 ) throws IOException
, InvalidNumberException
{
1101 var address
= canonicalizeAndResolveSignalServiceAddress(number
);
1102 setExpirationTimer(address
, messageExpirationTimer
);
1106 * Change the expiration timer for a group
1108 public void setExpirationTimer(GroupId groupId
, int messageExpirationTimer
) {
1109 var g
= getGroup(groupId
);
1110 if (g
instanceof GroupInfoV1
) {
1111 var groupInfoV1
= (GroupInfoV1
) g
;
1112 groupInfoV1
.messageExpirationTime
= messageExpirationTimer
;
1113 account
.getGroupStore().updateGroup(groupInfoV1
);
1115 throw new RuntimeException("TODO Not implemented!");
1120 * Upload the sticker pack from path.
1122 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1123 * @return if successful, returns the URL to install the sticker pack in the signal app
1125 public String
uploadStickerPack(File path
) throws IOException
, StickerPackInvalidException
{
1126 var manifest
= StickerUtils
.getSignalServiceStickerManifestUpload(path
);
1128 var messageSender
= createMessageSender();
1130 var packKey
= KeyUtils
.createStickerUploadKey();
1131 var packId
= messageSender
.uploadStickerManifest(manifest
, packKey
);
1133 var sticker
= new Sticker(Hex
.fromStringCondensed(packId
), packKey
);
1134 account
.getStickerStore().updateSticker(sticker
);
1138 return new URI("https",
1141 "pack_id=" + URLEncoder
.encode(packId
, StandardCharsets
.UTF_8
) + "&pack_key=" + URLEncoder
.encode(
1142 Hex
.toStringCondensed(packKey
),
1143 StandardCharsets
.UTF_8
)).toString();
1144 } catch (URISyntaxException e
) {
1145 throw new AssertionError(e
);
1149 void requestSyncGroups() throws IOException
{
1150 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1151 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
)
1153 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1155 sendSyncMessage(message
);
1156 } catch (UntrustedIdentityException e
) {
1157 throw new AssertionError(e
);
1161 void requestSyncContacts() throws IOException
{
1162 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1163 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
)
1165 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1167 sendSyncMessage(message
);
1168 } catch (UntrustedIdentityException e
) {
1169 throw new AssertionError(e
);
1173 void requestSyncBlocked() throws IOException
{
1174 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1175 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
)
1177 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1179 sendSyncMessage(message
);
1180 } catch (UntrustedIdentityException e
) {
1181 throw new AssertionError(e
);
1185 void requestSyncConfiguration() throws IOException
{
1186 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1187 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
)
1189 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1191 sendSyncMessage(message
);
1192 } catch (UntrustedIdentityException e
) {
1193 throw new AssertionError(e
);
1197 void requestSyncKeys() throws IOException
{
1198 var r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder()
1199 .setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.KEYS
)
1201 var message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
1203 sendSyncMessage(message
);
1204 } catch (UntrustedIdentityException e
) {
1205 throw new AssertionError(e
);
1209 private byte[] getSenderCertificate() {
1210 // TODO support UUID capable sender certificates
1211 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1214 certificate
= accountManager
.getSenderCertificate();
1215 } catch (IOException e
) {
1216 logger
.warn("Failed to get sender certificate, ignoring: {}", e
.getMessage());
1219 // TODO cache for a day
1223 private void sendSyncMessage(SignalServiceSyncMessage message
) throws IOException
, UntrustedIdentityException
{
1224 var messageSender
= createMessageSender();
1225 messageSender
.sendMessage(message
, unidentifiedAccessHelper
.getAccessForSync());
1228 private Collection
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> numbers
) throws InvalidNumberException
{
1229 final var signalServiceAddresses
= new HashSet
<SignalServiceAddress
>(numbers
.size());
1230 final var addressesMissingUuid
= new HashSet
<SignalServiceAddress
>();
1232 for (var number
: numbers
) {
1233 final var resolvedAddress
= canonicalizeAndResolveSignalServiceAddress(number
);
1234 if (resolvedAddress
.getUuid().isPresent()) {
1235 signalServiceAddresses
.add(resolvedAddress
);
1237 addressesMissingUuid
.add(resolvedAddress
);
1241 final var numbersMissingUuid
= addressesMissingUuid
.stream()
1242 .map(a
-> a
.getNumber().get())
1243 .collect(Collectors
.toSet());
1244 Map
<String
, UUID
> registeredUsers
;
1246 registeredUsers
= getRegisteredUsers(numbersMissingUuid
);
1247 } catch (IOException e
) {
1248 logger
.warn("Failed to resolve uuids from server, ignoring: {}", e
.getMessage());
1249 registeredUsers
= Map
.of();
1252 for (var address
: addressesMissingUuid
) {
1253 final var number
= address
.getNumber().get();
1254 if (registeredUsers
.containsKey(number
)) {
1255 final var newAddress
= resolveSignalServiceAddress(new SignalServiceAddress(registeredUsers
.get(number
),
1257 signalServiceAddresses
.add(newAddress
);
1259 signalServiceAddresses
.add(address
);
1263 return signalServiceAddresses
;
1266 private Map
<String
, UUID
> getRegisteredUsers(final Set
<String
> numbersMissingUuid
) throws IOException
{
1268 return accountManager
.getRegisteredUsers(ServiceConfig
.getIasKeyStore(),
1270 serviceEnvironmentConfig
.getCdsMrenclave());
1271 } catch (Quote
.InvalidQuoteFormatException
| UnauthenticatedQuoteException
| SignatureException
| UnauthenticatedResponseException
| InvalidKeyException e
) {
1272 throw new IOException(e
);
1276 private Pair
<Long
, List
<SendMessageResult
>> sendMessage(
1277 SignalServiceDataMessage
.Builder messageBuilder
, Collection
<SignalServiceAddress
> recipients
1278 ) throws IOException
{
1279 recipients
= recipients
.stream().map(this::resolveSignalServiceAddress
).collect(Collectors
.toSet());
1280 final var timestamp
= System
.currentTimeMillis();
1281 messageBuilder
.withTimestamp(timestamp
);
1282 getOrCreateMessagePipe();
1283 getOrCreateUnidentifiedMessagePipe();
1284 SignalServiceDataMessage message
= null;
1286 message
= messageBuilder
.build();
1287 if (message
.getGroupContext().isPresent()) {
1289 var messageSender
= createMessageSender();
1290 final var isRecipientUpdate
= false;
1291 var result
= messageSender
.sendMessage(new ArrayList
<>(recipients
),
1292 unidentifiedAccessHelper
.getAccessFor(recipients
),
1295 return new Pair
<>(timestamp
, result
);
1296 } catch (UntrustedIdentityException e
) {
1297 return new Pair
<>(timestamp
, List
.of());
1300 // Send to all individually, so sync messages are sent correctly
1301 messageBuilder
.withProfileKey(account
.getProfileKey().serialize());
1302 var results
= new ArrayList
<SendMessageResult
>(recipients
.size());
1303 for (var address
: recipients
) {
1304 final var contact
= account
.getContactStore().getContact(address
);
1305 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1306 messageBuilder
.withExpiration(expirationTime
);
1307 message
= messageBuilder
.build();
1308 results
.add(sendMessage(address
, message
));
1310 return new Pair
<>(timestamp
, results
);
1313 if (message
!= null && message
.isEndSession()) {
1314 for (var recipient
: recipients
) {
1315 handleEndSession(recipient
);
1322 private Pair
<Long
, SendMessageResult
> sendSelfMessage(
1323 SignalServiceDataMessage
.Builder messageBuilder
1324 ) throws IOException
{
1325 final var timestamp
= System
.currentTimeMillis();
1326 messageBuilder
.withTimestamp(timestamp
);
1327 getOrCreateMessagePipe();
1328 getOrCreateUnidentifiedMessagePipe();
1330 final var address
= getSelfAddress();
1332 final var contact
= account
.getContactStore().getContact(address
);
1333 final var expirationTime
= contact
!= null ? contact
.messageExpirationTime
: 0;
1334 messageBuilder
.withExpiration(expirationTime
);
1336 var message
= messageBuilder
.build();
1337 final var result
= sendSelfMessage(message
);
1338 return new Pair
<>(timestamp
, result
);
1344 private SendMessageResult
sendSelfMessage(SignalServiceDataMessage message
) throws IOException
{
1345 var messageSender
= createMessageSender();
1347 var recipient
= account
.getSelfAddress();
1349 final var unidentifiedAccess
= unidentifiedAccessHelper
.getAccessFor(recipient
);
1350 var transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
1351 message
.getTimestamp(),
1353 message
.getExpiresInSeconds(),
1354 Map
.of(recipient
, unidentifiedAccess
.isPresent()),
1356 var syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
1359 var startTime
= System
.currentTimeMillis();
1360 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
1361 return SendMessageResult
.success(recipient
,
1362 unidentifiedAccess
.isPresent(),
1364 System
.currentTimeMillis() - startTime
);
1365 } catch (UntrustedIdentityException e
) {
1366 return SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey());
1370 private SendMessageResult
sendMessage(
1371 SignalServiceAddress address
, SignalServiceDataMessage message
1372 ) throws IOException
{
1373 var messageSender
= createMessageSender();
1376 return messageSender
.sendMessage(address
, unidentifiedAccessHelper
.getAccessFor(address
), message
);
1377 } catch (UntrustedIdentityException e
) {
1378 return SendMessageResult
.identityFailure(address
, e
.getIdentityKey());
1382 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, SelfSendException
, UnsupportedDataMessageException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
1383 var cipher
= new SignalServiceCipher(account
.getSelfAddress(),
1384 account
.getSignalProtocolStore(),
1385 certificateValidator
);
1387 return cipher
.decrypt(envelope
);
1388 } catch (ProtocolUntrustedIdentityException e
) {
1389 if (e
.getCause() instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1390 throw (org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
.getCause();
1392 throw new AssertionError(e
);
1396 private void handleEndSession(SignalServiceAddress source
) {
1397 account
.getSessionStore().deleteAllSessions(source
.getIdentifier());
1400 private List
<HandleAction
> handleSignalServiceDataMessage(
1401 SignalServiceDataMessage message
,
1403 SignalServiceAddress source
,
1404 SignalServiceAddress destination
,
1405 boolean ignoreAttachments
1407 var actions
= new ArrayList
<HandleAction
>();
1408 if (message
.getGroupContext().isPresent()) {
1409 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1410 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1411 var groupId
= GroupId
.v1(groupInfo
.getGroupId());
1412 var group
= getGroup(groupId
);
1413 if (group
== null || group
instanceof GroupInfoV1
) {
1414 var groupV1
= (GroupInfoV1
) group
;
1415 switch (groupInfo
.getType()) {
1417 if (groupV1
== null) {
1418 groupV1
= new GroupInfoV1(groupId
);
1421 if (groupInfo
.getAvatar().isPresent()) {
1422 var avatar
= groupInfo
.getAvatar().get();
1423 downloadGroupAvatar(avatar
, groupV1
.getGroupId());
1426 if (groupInfo
.getName().isPresent()) {
1427 groupV1
.name
= groupInfo
.getName().get();
1430 if (groupInfo
.getMembers().isPresent()) {
1431 groupV1
.addMembers(groupInfo
.getMembers()
1434 .map(this::resolveSignalServiceAddress
)
1435 .collect(Collectors
.toSet()));
1438 account
.getGroupStore().updateGroup(groupV1
);
1442 if (groupV1
== null && !isSync
) {
1443 actions
.add(new SendGroupInfoRequestAction(source
, groupId
));
1447 if (groupV1
!= null) {
1448 groupV1
.removeMember(source
);
1449 account
.getGroupStore().updateGroup(groupV1
);
1454 if (groupV1
!= null && !isSync
) {
1455 actions
.add(new SendGroupInfoAction(source
, groupV1
.getGroupId()));
1460 // Received a group v1 message for a v2 group
1463 if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1464 final var groupContext
= message
.getGroupContext().get().getGroupV2().get();
1465 final var groupMasterKey
= groupContext
.getMasterKey();
1467 getOrMigrateGroup(groupMasterKey
,
1468 groupContext
.getRevision(),
1469 groupContext
.hasSignedGroupChange() ? groupContext
.getSignedGroupChange() : null);
1473 final var conversationPartnerAddress
= isSync ? destination
: source
;
1474 if (conversationPartnerAddress
!= null && message
.isEndSession()) {
1475 handleEndSession(conversationPartnerAddress
);
1477 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1478 if (message
.getGroupContext().isPresent()) {
1479 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1480 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1481 var group
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(groupInfo
.getGroupId()));
1482 if (group
!= null) {
1483 if (group
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1484 group
.messageExpirationTime
= message
.getExpiresInSeconds();
1485 account
.getGroupStore().updateGroup(group
);
1488 } else if (message
.getGroupContext().get().getGroupV2().isPresent()) {
1489 // disappearing message timer already stored in the DecryptedGroup
1491 } else if (conversationPartnerAddress
!= null) {
1492 var contact
= account
.getContactStore().getContact(conversationPartnerAddress
);
1493 if (contact
== null) {
1494 contact
= new ContactInfo(conversationPartnerAddress
);
1496 if (contact
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1497 contact
.messageExpirationTime
= message
.getExpiresInSeconds();
1498 account
.getContactStore().updateContact(contact
);
1502 if (!ignoreAttachments
) {
1503 if (message
.getAttachments().isPresent()) {
1504 for (var attachment
: message
.getAttachments().get()) {
1505 downloadAttachment(attachment
);
1508 if (message
.getSharedContacts().isPresent()) {
1509 for (var contact
: message
.getSharedContacts().get()) {
1510 if (contact
.getAvatar().isPresent()) {
1511 downloadAttachment(contact
.getAvatar().get().getAttachment());
1516 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1517 final ProfileKey profileKey
;
1519 profileKey
= new ProfileKey(message
.getProfileKey().get());
1520 } catch (InvalidInputException e
) {
1521 throw new AssertionError(e
);
1523 if (source
.matches(account
.getSelfAddress())) {
1524 this.account
.setProfileKey(profileKey
);
1526 this.account
.getProfileStore().storeProfileKey(source
, profileKey
);
1528 if (message
.getPreviews().isPresent()) {
1529 final var previews
= message
.getPreviews().get();
1530 for (var preview
: previews
) {
1531 if (preview
.getImage().isPresent()) {
1532 downloadAttachment(preview
.getImage().get());
1536 if (message
.getQuote().isPresent()) {
1537 final var quote
= message
.getQuote().get();
1539 for (var quotedAttachment
: quote
.getAttachments()) {
1540 final var thumbnail
= quotedAttachment
.getThumbnail();
1541 if (thumbnail
!= null) {
1542 downloadAttachment(thumbnail
);
1546 if (message
.getSticker().isPresent()) {
1547 final var messageSticker
= message
.getSticker().get();
1548 var sticker
= account
.getStickerStore().getSticker(messageSticker
.getPackId());
1549 if (sticker
== null) {
1550 sticker
= new Sticker(messageSticker
.getPackId(), messageSticker
.getPackKey());
1551 account
.getStickerStore().updateSticker(sticker
);
1557 private GroupInfoV2
getOrMigrateGroup(
1558 final GroupMasterKey groupMasterKey
, final int revision
, final byte[] signedGroupChange
1560 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
1562 var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
1563 var groupInfo
= getGroup(groupId
);
1564 final GroupInfoV2 groupInfoV2
;
1565 if (groupInfo
instanceof GroupInfoV1
) {
1566 // Received a v2 group message for a v1 group, we need to locally migrate the group
1567 account
.getGroupStore().deleteGroup(groupInfo
.getGroupId());
1568 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1569 logger
.info("Locally migrated group {} to group v2, id: {}",
1570 groupInfo
.getGroupId().toBase64(),
1571 groupInfoV2
.getGroupId().toBase64());
1572 } else if (groupInfo
instanceof GroupInfoV2
) {
1573 groupInfoV2
= (GroupInfoV2
) groupInfo
;
1575 groupInfoV2
= new GroupInfoV2(groupId
, groupMasterKey
);
1578 if (groupInfoV2
.getGroup() == null || groupInfoV2
.getGroup().getRevision() < revision
) {
1579 DecryptedGroup group
= null;
1580 if (signedGroupChange
!= null
1581 && groupInfoV2
.getGroup() != null
1582 && groupInfoV2
.getGroup().getRevision() + 1 == revision
) {
1583 group
= groupHelper
.getUpdatedDecryptedGroup(groupInfoV2
.getGroup(), signedGroupChange
, groupMasterKey
);
1585 if (group
== null) {
1586 group
= groupHelper
.getDecryptedGroup(groupSecretParams
);
1588 if (group
!= null) {
1589 storeProfileKeysFromMembers(group
);
1590 final var avatar
= group
.getAvatar();
1591 if (avatar
!= null && !avatar
.isEmpty()) {
1592 downloadGroupAvatar(groupId
, groupSecretParams
, avatar
);
1595 groupInfoV2
.setGroup(group
);
1596 account
.getGroupStore().updateGroup(groupInfoV2
);
1602 private void storeProfileKeysFromMembers(final DecryptedGroup group
) {
1603 for (var member
: group
.getMembersList()) {
1604 final var address
= resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil
.parseOrThrow(member
.getUuid()
1605 .toByteArray()), null));
1607 account
.getProfileStore()
1608 .storeProfileKey(address
, new ProfileKey(member
.getProfileKey().toByteArray()));
1609 } catch (InvalidInputException ignored
) {
1614 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1615 for (var cachedMessage
: account
.getMessageCache().getCachedMessages()) {
1616 retryFailedReceivedMessage(handler
, ignoreAttachments
, cachedMessage
);
1620 private void retryFailedReceivedMessage(
1621 final ReceiveMessageHandler handler
, final boolean ignoreAttachments
, final CachedMessage cachedMessage
1623 var envelope
= cachedMessage
.loadEnvelope();
1624 if (envelope
== null) {
1627 SignalServiceContent content
= null;
1628 if (!envelope
.isReceipt()) {
1630 content
= decryptMessage(envelope
);
1631 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
1632 if (!envelope
.hasSource()) {
1633 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) e
)
1636 account
.getMessageCache().replaceSender(cachedMessage
, recipientId
);
1637 } catch (IOException ioException
) {
1638 logger
.warn("Failed to move cached message to recipient folder: {}", ioException
.getMessage());
1642 } catch (Exception er
) {
1643 // All other errors are not recoverable, so delete the cached message
1644 cachedMessage
.delete();
1647 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1648 for (var action
: actions
) {
1650 action
.execute(this);
1651 } catch (Throwable e
) {
1652 logger
.warn("Message action failed.", e
);
1657 handler
.handleMessage(envelope
, content
, null);
1658 cachedMessage
.delete();
1661 public void receiveMessages(
1664 boolean returnOnTimeout
,
1665 boolean ignoreAttachments
,
1666 ReceiveMessageHandler handler
1667 ) throws IOException
{
1668 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1670 Set
<HandleAction
> queuedActions
= null;
1672 final var messagePipe
= getOrCreateMessagePipe();
1674 var hasCaughtUpWithOldMessages
= false;
1677 SignalServiceEnvelope envelope
;
1678 SignalServiceContent content
= null;
1679 Exception exception
= null;
1680 final CachedMessage
[] cachedMessage
= {null};
1682 var result
= messagePipe
.readOrEmpty(timeout
, unit
, envelope1
-> {
1683 final var recipientId
= envelope1
.hasSource()
1684 ?
resolveRecipient(envelope1
.getSourceIdentifier())
1686 // store message on disk, before acknowledging receipt to the server
1687 cachedMessage
[0] = account
.getMessageCache().cacheMessage(envelope1
, recipientId
);
1689 if (result
.isPresent()) {
1690 envelope
= result
.get();
1692 // Received indicator that server queue is empty
1693 hasCaughtUpWithOldMessages
= true;
1695 if (queuedActions
!= null) {
1696 for (var action
: queuedActions
) {
1698 action
.execute(this);
1699 } catch (Throwable e
) {
1700 logger
.warn("Message action failed.", e
);
1704 queuedActions
.clear();
1705 queuedActions
= null;
1708 // Continue to wait another timeout for new messages
1711 } catch (TimeoutException e
) {
1712 if (returnOnTimeout
) return;
1716 if (envelope
.hasSource()) {
1717 // Store uuid if we don't have it already
1718 resolveRecipientTrusted(envelope
.getSourceAddress());
1720 if (!envelope
.isReceipt()) {
1722 content
= decryptMessage(envelope
);
1723 } catch (Exception e
) {
1726 var actions
= handleMessage(envelope
, content
, ignoreAttachments
);
1727 if (hasCaughtUpWithOldMessages
) {
1728 for (var action
: actions
) {
1730 action
.execute(this);
1731 } catch (Throwable e
) {
1732 logger
.warn("Message action failed.", e
);
1736 if (queuedActions
== null) {
1737 queuedActions
= new HashSet
<>();
1739 queuedActions
.addAll(actions
);
1743 if (isMessageBlocked(envelope
, content
)) {
1744 logger
.info("Ignoring a message from blocked user/group: {}", envelope
.getTimestamp());
1745 } else if (isNotAGroupMember(envelope
, content
)) {
1746 logger
.info("Ignoring a message from a non group member: {}", envelope
.getTimestamp());
1748 handler
.handleMessage(envelope
, content
, exception
);
1750 if (cachedMessage
[0] != null) {
1751 if (exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
) {
1752 if (!envelope
.hasSource()) {
1753 final var recipientId
= resolveRecipient(((org
.whispersystems
.libsignal
.UntrustedIdentityException
) exception
)
1756 cachedMessage
[0] = account
.getMessageCache().replaceSender(cachedMessage
[0], recipientId
);
1757 } catch (IOException ioException
) {
1758 logger
.warn("Failed to move cached message to recipient folder: {}",
1759 ioException
.getMessage());
1763 cachedMessage
[0].delete();
1769 private boolean isMessageBlocked(
1770 SignalServiceEnvelope envelope
, SignalServiceContent content
1772 SignalServiceAddress source
;
1773 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1774 source
= envelope
.getSourceAddress();
1775 } else if (content
!= null) {
1776 source
= content
.getSender();
1780 var sourceContact
= account
.getContactStore().getContact(source
);
1781 if (sourceContact
!= null && sourceContact
.blocked
) {
1785 if (content
!= null && content
.getDataMessage().isPresent()) {
1786 var message
= content
.getDataMessage().get();
1787 if (message
.getGroupContext().isPresent()) {
1788 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1789 var group
= getGroup(groupId
);
1790 if (group
!= null && group
.isBlocked()) {
1798 private boolean isNotAGroupMember(
1799 SignalServiceEnvelope envelope
, SignalServiceContent content
1801 SignalServiceAddress source
;
1802 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1803 source
= envelope
.getSourceAddress();
1804 } else if (content
!= null) {
1805 source
= content
.getSender();
1810 if (content
!= null && content
.getDataMessage().isPresent()) {
1811 var message
= content
.getDataMessage().get();
1812 if (message
.getGroupContext().isPresent()) {
1813 if (message
.getGroupContext().get().getGroupV1().isPresent()) {
1814 var groupInfo
= message
.getGroupContext().get().getGroupV1().get();
1815 if (groupInfo
.getType() == SignalServiceGroup
.Type
.QUIT
) {
1819 var groupId
= GroupUtils
.getGroupId(message
.getGroupContext().get());
1820 var group
= getGroup(groupId
);
1821 if (group
!= null && !group
.isMember(source
)) {
1829 private List
<HandleAction
> handleMessage(
1830 SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
1832 var actions
= new ArrayList
<HandleAction
>();
1833 if (content
!= null) {
1834 final SignalServiceAddress sender
;
1835 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1836 sender
= envelope
.getSourceAddress();
1838 sender
= content
.getSender();
1840 // Store uuid if we don't have it already
1841 resolveSignalServiceAddress(sender
);
1843 if (content
.getDataMessage().isPresent()) {
1844 var message
= content
.getDataMessage().get();
1846 if (content
.isNeedsReceipt()) {
1847 actions
.add(new SendReceiptAction(sender
, message
.getTimestamp()));
1850 actions
.addAll(handleSignalServiceDataMessage(message
,
1853 account
.getSelfAddress(),
1854 ignoreAttachments
));
1856 if (content
.getSyncMessage().isPresent()) {
1857 account
.setMultiDevice(true);
1858 var syncMessage
= content
.getSyncMessage().get();
1859 if (syncMessage
.getSent().isPresent()) {
1860 var message
= syncMessage
.getSent().get();
1861 final var destination
= message
.getDestination().orNull();
1862 actions
.addAll(handleSignalServiceDataMessage(message
.getMessage(),
1866 ignoreAttachments
));
1868 if (syncMessage
.getRequest().isPresent()) {
1869 var rm
= syncMessage
.getRequest().get();
1870 if (rm
.isContactsRequest()) {
1871 actions
.add(SendSyncContactsAction
.create());
1873 if (rm
.isGroupsRequest()) {
1874 actions
.add(SendSyncGroupsAction
.create());
1876 if (rm
.isBlockedListRequest()) {
1877 actions
.add(SendSyncBlockedListAction
.create());
1879 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1881 if (syncMessage
.getGroups().isPresent()) {
1882 File tmpFile
= null;
1884 tmpFile
= IOUtils
.createTempFile();
1885 final var groupsMessage
= syncMessage
.getGroups().get();
1886 try (var attachmentAsStream
= retrieveAttachmentAsStream(groupsMessage
.asPointer(), tmpFile
)) {
1887 var s
= new DeviceGroupsInputStream(attachmentAsStream
);
1889 while ((g
= s
.read()) != null) {
1890 var syncGroup
= account
.getGroupStore().getOrCreateGroupV1(GroupId
.v1(g
.getId()));
1891 if (syncGroup
!= null) {
1892 if (g
.getName().isPresent()) {
1893 syncGroup
.name
= g
.getName().get();
1895 syncGroup
.addMembers(g
.getMembers()
1897 .map(this::resolveSignalServiceAddress
)
1898 .collect(Collectors
.toSet()));
1899 if (!g
.isActive()) {
1900 syncGroup
.removeMember(account
.getSelfAddress());
1902 // Add ourself to the member set as it's marked as active
1903 syncGroup
.addMembers(List
.of(account
.getSelfAddress()));
1905 syncGroup
.blocked
= g
.isBlocked();
1906 if (g
.getColor().isPresent()) {
1907 syncGroup
.color
= g
.getColor().get();
1910 if (g
.getAvatar().isPresent()) {
1911 downloadGroupAvatar(g
.getAvatar().get(), syncGroup
.getGroupId());
1913 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1914 syncGroup
.archived
= g
.isArchived();
1915 account
.getGroupStore().updateGroup(syncGroup
);
1919 } catch (Exception e
) {
1920 logger
.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1924 if (tmpFile
!= null) {
1926 Files
.delete(tmpFile
.toPath());
1927 } catch (IOException e
) {
1928 logger
.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1935 if (syncMessage
.getBlockedList().isPresent()) {
1936 final var blockedListMessage
= syncMessage
.getBlockedList().get();
1937 for (var address
: blockedListMessage
.getAddresses()) {
1938 setContactBlocked(resolveSignalServiceAddress(address
), true);
1940 for (var groupId
: blockedListMessage
.getGroupIds()
1942 .map(GroupId
::unknownVersion
)
1943 .collect(Collectors
.toSet())) {
1945 setGroupBlocked(groupId
, true);
1946 } catch (GroupNotFoundException e
) {
1947 logger
.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1948 groupId
.toBase64());
1952 if (syncMessage
.getContacts().isPresent()) {
1953 File tmpFile
= null;
1955 tmpFile
= IOUtils
.createTempFile();
1956 final var contactsMessage
= syncMessage
.getContacts().get();
1957 try (var attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream()
1958 .asPointer(), tmpFile
)) {
1959 var s
= new DeviceContactsInputStream(attachmentAsStream
);
1960 if (contactsMessage
.isComplete()) {
1961 account
.getContactStore().clear();
1964 while ((c
= s
.read()) != null) {
1965 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1966 account
.setProfileKey(c
.getProfileKey().get());
1968 final var address
= resolveSignalServiceAddress(c
.getAddress());
1969 var contact
= account
.getContactStore().getContact(address
);
1970 if (contact
== null) {
1971 contact
= new ContactInfo(address
);
1973 if (c
.getName().isPresent()) {
1974 contact
.name
= c
.getName().get();
1976 if (c
.getColor().isPresent()) {
1977 contact
.color
= c
.getColor().get();
1979 if (c
.getProfileKey().isPresent()) {
1980 account
.getProfileStore().storeProfileKey(address
, c
.getProfileKey().get());
1982 if (c
.getVerified().isPresent()) {
1983 final var verifiedMessage
= c
.getVerified().get();
1984 account
.getIdentityKeyStore()
1985 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
1986 verifiedMessage
.getIdentityKey(),
1987 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1989 if (c
.getExpirationTimer().isPresent()) {
1990 contact
.messageExpirationTime
= c
.getExpirationTimer().get();
1992 contact
.blocked
= c
.isBlocked();
1993 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1994 contact
.archived
= c
.isArchived();
1995 account
.getContactStore().updateContact(contact
);
1997 if (c
.getAvatar().isPresent()) {
1998 downloadContactAvatar(c
.getAvatar().get(), contact
.getAddress());
2002 } catch (Exception e
) {
2003 logger
.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2007 if (tmpFile
!= null) {
2009 Files
.delete(tmpFile
.toPath());
2010 } catch (IOException e
) {
2011 logger
.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2018 if (syncMessage
.getVerified().isPresent()) {
2019 final var verifiedMessage
= syncMessage
.getVerified().get();
2020 account
.getIdentityKeyStore()
2021 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage
.getDestination()),
2022 verifiedMessage
.getIdentityKey(),
2023 TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
2025 if (syncMessage
.getStickerPackOperations().isPresent()) {
2026 final var stickerPackOperationMessages
= syncMessage
.getStickerPackOperations().get();
2027 for (var m
: stickerPackOperationMessages
) {
2028 if (!m
.getPackId().isPresent()) {
2031 var sticker
= account
.getStickerStore().getSticker(m
.getPackId().get());
2032 if (sticker
== null) {
2033 if (!m
.getPackKey().isPresent()) {
2036 sticker
= new Sticker(m
.getPackId().get(), m
.getPackKey().get());
2038 sticker
.setInstalled(!m
.getType().isPresent()
2039 || m
.getType().get() == StickerPackOperationMessage
.Type
.INSTALL
);
2040 account
.getStickerStore().updateSticker(sticker
);
2043 if (syncMessage
.getFetchType().isPresent()) {
2044 switch (syncMessage
.getFetchType().get()) {
2046 getRecipientProfile(getSelfAddress(), true);
2047 case STORAGE_MANIFEST
:
2051 if (syncMessage
.getKeys().isPresent()) {
2052 final var keysMessage
= syncMessage
.getKeys().get();
2053 if (keysMessage
.getStorageService().isPresent()) {
2054 final var storageKey
= keysMessage
.getStorageService().get();
2055 account
.setStorageKey(storageKey
);
2058 if (syncMessage
.getConfiguration().isPresent()) {
2066 private void downloadContactAvatar(SignalServiceAttachment avatar
, SignalServiceAddress address
) {
2068 avatarStore
.storeContactAvatar(address
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2069 } catch (IOException e
) {
2070 logger
.warn("Failed to download avatar for contact {}, ignoring: {}", address
, e
.getMessage());
2074 private void downloadGroupAvatar(SignalServiceAttachment avatar
, GroupId groupId
) {
2076 avatarStore
.storeGroupAvatar(groupId
, outputStream
-> retrieveAttachment(avatar
, outputStream
));
2077 } catch (IOException e
) {
2078 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2082 private void downloadGroupAvatar(GroupId groupId
, GroupSecretParams groupSecretParams
, String cdnKey
) {
2084 avatarStore
.storeGroupAvatar(groupId
,
2085 outputStream
-> retrieveGroupV2Avatar(groupSecretParams
, cdnKey
, outputStream
));
2086 } catch (IOException e
) {
2087 logger
.warn("Failed to download avatar for group {}, ignoring: {}", groupId
.toBase64(), e
.getMessage());
2091 private void downloadProfileAvatar(
2092 SignalServiceAddress address
, String avatarPath
, ProfileKey profileKey
2095 avatarStore
.storeProfileAvatar(address
,
2096 outputStream
-> retrieveProfileAvatar(avatarPath
, profileKey
, outputStream
));
2097 } catch (Throwable e
) {
2098 logger
.warn("Failed to download profile avatar, ignoring: {}", e
.getMessage());
2102 public File
getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId
) {
2103 return attachmentStore
.getAttachmentFile(attachmentId
);
2106 private void downloadAttachment(final SignalServiceAttachment attachment
) {
2107 if (!attachment
.isPointer()) {
2108 logger
.warn("Invalid state, can't store an attachment stream.");
2111 var pointer
= attachment
.asPointer();
2112 if (pointer
.getPreview().isPresent()) {
2113 final var preview
= pointer
.getPreview().get();
2115 attachmentStore
.storeAttachmentPreview(pointer
.getRemoteId(),
2116 outputStream
-> outputStream
.write(preview
, 0, preview
.length
));
2117 } catch (IOException e
) {
2118 logger
.warn("Failed to download attachment preview, ignoring: {}", e
.getMessage());
2123 attachmentStore
.storeAttachment(pointer
.getRemoteId(),
2124 outputStream
-> retrieveAttachmentPointer(pointer
, outputStream
));
2125 } catch (IOException e
) {
2126 logger
.warn("Failed to download attachment ({}), ignoring: {}", pointer
.getRemoteId(), e
.getMessage());
2130 private void retrieveGroupV2Avatar(
2131 GroupSecretParams groupSecretParams
, String cdnKey
, OutputStream outputStream
2132 ) throws IOException
{
2133 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
2135 var tmpFile
= IOUtils
.createTempFile();
2136 try (InputStream input
= messageReceiver
.retrieveGroupsV2ProfileAvatar(cdnKey
,
2138 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2139 var encryptedData
= IOUtils
.readFully(input
);
2141 var decryptedData
= groupOperations
.decryptAvatar(encryptedData
);
2142 outputStream
.write(decryptedData
);
2145 Files
.delete(tmpFile
.toPath());
2146 } catch (IOException e
) {
2147 logger
.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2154 private void retrieveProfileAvatar(
2155 String avatarPath
, ProfileKey profileKey
, OutputStream outputStream
2156 ) throws IOException
{
2157 var tmpFile
= IOUtils
.createTempFile();
2158 try (var input
= messageReceiver
.retrieveProfileAvatar(avatarPath
,
2161 ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
)) {
2162 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2163 IOUtils
.copyStream(input
, outputStream
, (int) ServiceConfig
.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE
);
2166 Files
.delete(tmpFile
.toPath());
2167 } catch (IOException e
) {
2168 logger
.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2175 private void retrieveAttachment(
2176 final SignalServiceAttachment attachment
, final OutputStream outputStream
2177 ) throws IOException
{
2178 if (attachment
.isPointer()) {
2179 var pointer
= attachment
.asPointer();
2180 retrieveAttachmentPointer(pointer
, outputStream
);
2182 var stream
= attachment
.asStream();
2183 IOUtils
.copyStream(stream
.getInputStream(), outputStream
);
2187 private void retrieveAttachmentPointer(
2188 SignalServiceAttachmentPointer pointer
, OutputStream outputStream
2189 ) throws IOException
{
2190 var tmpFile
= IOUtils
.createTempFile();
2191 try (var input
= retrieveAttachmentAsStream(pointer
, tmpFile
)) {
2192 IOUtils
.copyStream(input
, outputStream
);
2193 } catch (MissingConfigurationException
| InvalidMessageException e
) {
2194 throw new IOException(e
);
2197 Files
.delete(tmpFile
.toPath());
2198 } catch (IOException e
) {
2199 logger
.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2206 private InputStream
retrieveAttachmentAsStream(
2207 SignalServiceAttachmentPointer pointer
, File tmpFile
2208 ) throws IOException
, InvalidMessageException
, MissingConfigurationException
{
2209 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, ServiceConfig
.MAX_ATTACHMENT_SIZE
);
2212 void sendGroups() throws IOException
, UntrustedIdentityException
{
2213 var groupsFile
= IOUtils
.createTempFile();
2216 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
2217 var out
= new DeviceGroupsOutputStream(fos
);
2218 for (var record : getGroups()) {
2219 if (record instanceof GroupInfoV1
) {
2220 var groupInfo
= (GroupInfoV1
) record;
2221 out
.write(new DeviceGroup(groupInfo
.getGroupId().serialize(),
2222 Optional
.fromNullable(groupInfo
.name
),
2223 new ArrayList
<>(groupInfo
.getMembers()),
2224 createGroupAvatarAttachment(groupInfo
.getGroupId()),
2225 groupInfo
.isMember(account
.getSelfAddress()),
2226 Optional
.of(groupInfo
.messageExpirationTime
),
2227 Optional
.fromNullable(groupInfo
.color
),
2229 Optional
.fromNullable(groupInfo
.inboxPosition
),
2230 groupInfo
.archived
));
2235 if (groupsFile
.exists() && groupsFile
.length() > 0) {
2236 try (var groupsFileStream
= new FileInputStream(groupsFile
)) {
2237 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2238 .withStream(groupsFileStream
)
2239 .withContentType("application/octet-stream")
2240 .withLength(groupsFile
.length())
2243 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
2248 Files
.delete(groupsFile
.toPath());
2249 } catch (IOException e
) {
2250 logger
.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile
, e
.getMessage());
2255 public void sendContacts() throws IOException
, UntrustedIdentityException
{
2256 var contactsFile
= IOUtils
.createTempFile();
2259 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
2260 var out
= new DeviceContactsOutputStream(fos
);
2261 for (var record : account
.getContactStore().getContacts()) {
2262 VerifiedMessage verifiedMessage
= null;
2263 var currentIdentity
= account
.getIdentityKeyStore()
2264 .getIdentity(resolveRecipientTrusted(record.getAddress()));
2265 if (currentIdentity
!= null) {
2266 verifiedMessage
= new VerifiedMessage(record.getAddress(),
2267 currentIdentity
.getIdentityKey(),
2268 currentIdentity
.getTrustLevel().toVerifiedState(),
2269 currentIdentity
.getDateAdded().getTime());
2272 var profileKey
= account
.getProfileStore().getProfileKey(record.getAddress());
2273 out
.write(new DeviceContact(record.getAddress(),
2274 Optional
.fromNullable(record.name
),
2275 createContactAvatarAttachment(record.getAddress()),
2276 Optional
.fromNullable(record.color
),
2277 Optional
.fromNullable(verifiedMessage
),
2278 Optional
.fromNullable(profileKey
),
2280 Optional
.of(record.messageExpirationTime
),
2281 Optional
.fromNullable(record.inboxPosition
),
2285 if (account
.getProfileKey() != null) {
2286 // Send our own profile key as well
2287 out
.write(new DeviceContact(account
.getSelfAddress(),
2292 Optional
.of(account
.getProfileKey()),
2300 if (contactsFile
.exists() && contactsFile
.length() > 0) {
2301 try (var contactsFileStream
= new FileInputStream(contactsFile
)) {
2302 var attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
2303 .withStream(contactsFileStream
)
2304 .withContentType("application/octet-stream")
2305 .withLength(contactsFile
.length())
2308 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
2313 Files
.delete(contactsFile
.toPath());
2314 } catch (IOException e
) {
2315 logger
.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile
, e
.getMessage());
2320 void sendBlockedList() throws IOException
, UntrustedIdentityException
{
2321 var addresses
= new ArrayList
<SignalServiceAddress
>();
2322 for (var record : account
.getContactStore().getContacts()) {
2323 if (record.blocked
) {
2324 addresses
.add(record.getAddress());
2327 var groupIds
= new ArrayList
<byte[]>();
2328 for (var record : getGroups()) {
2329 if (record.isBlocked()) {
2330 groupIds
.add(record.getGroupId().serialize());
2333 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
2336 private void sendVerifiedMessage(
2337 SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
2338 ) throws IOException
, UntrustedIdentityException
{
2339 var verifiedMessage
= new VerifiedMessage(destination
,
2341 trustLevel
.toVerifiedState(),
2342 System
.currentTimeMillis());
2343 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
2346 public List
<ContactInfo
> getContacts() {
2347 return account
.getContactStore().getContacts();
2350 public String
getContactOrProfileName(String number
) {
2351 final var address
= Utils
.getSignalServiceAddressFromIdentifier(number
);
2353 final var contact
= account
.getContactStore().getContact(address
);
2354 if (contact
!= null && !Util
.isEmpty(contact
.name
)) {
2355 return contact
.name
;
2358 final var profileEntry
= account
.getProfileStore().getProfileEntry(address
);
2359 if (profileEntry
!= null && profileEntry
.getProfile() != null) {
2360 return profileEntry
.getProfile().getDisplayName();
2365 public GroupInfo
getGroup(GroupId groupId
) {
2366 final var group
= account
.getGroupStore().getGroup(groupId
);
2367 if (group
instanceof GroupInfoV2
&& ((GroupInfoV2
) group
).getGroup() == null) {
2368 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(((GroupInfoV2
) group
).getMasterKey());
2369 ((GroupInfoV2
) group
).setGroup(groupHelper
.getDecryptedGroup(groupSecretParams
));
2370 account
.getGroupStore().updateGroup(group
);
2375 public List
<IdentityInfo
> getIdentities() {
2376 return account
.getIdentityKeyStore().getIdentities();
2379 public List
<IdentityInfo
> getIdentities(String number
) throws InvalidNumberException
{
2380 final var identity
= account
.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number
));
2381 return identity
== null ? List
.of() : List
.of(identity
);
2385 * Trust this the identity with this fingerprint
2387 * @param name username of the identity
2388 * @param fingerprint Fingerprint
2390 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) throws InvalidNumberException
{
2391 var recipientId
= canonicalizeAndResolveRecipient(name
);
2392 return trustIdentity(recipientId
,
2393 identityKey
-> Arrays
.equals(identityKey
.serialize(), fingerprint
),
2394 TrustLevel
.TRUSTED_VERIFIED
);
2398 * Trust this the identity with this safety number
2400 * @param name username of the identity
2401 * @param safetyNumber Safety number
2403 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) throws InvalidNumberException
{
2404 var recipientId
= canonicalizeAndResolveRecipient(name
);
2405 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2406 return trustIdentity(recipientId
,
2407 identityKey
-> safetyNumber
.equals(computeSafetyNumber(address
, identityKey
)),
2408 TrustLevel
.TRUSTED_VERIFIED
);
2412 * Trust all keys of this identity without verification
2414 * @param name username of the identity
2416 public boolean trustIdentityAllKeys(String name
) throws InvalidNumberException
{
2417 var recipientId
= canonicalizeAndResolveRecipient(name
);
2418 return trustIdentity(recipientId
, identityKey
-> true, TrustLevel
.TRUSTED_UNVERIFIED
);
2421 private boolean trustIdentity(
2422 RecipientId recipientId
, Function
<IdentityKey
, Boolean
> verifier
, TrustLevel trustLevel
2424 var identity
= account
.getIdentityKeyStore().getIdentity(recipientId
);
2425 if (identity
== null) {
2429 if (!verifier
.apply(identity
.getIdentityKey())) {
2433 account
.getIdentityKeyStore().setIdentityTrustLevel(recipientId
, identity
.getIdentityKey(), trustLevel
);
2435 var address
= account
.getRecipientStore().resolveServiceAddress(recipientId
);
2436 sendVerifiedMessage(address
, identity
.getIdentityKey(), trustLevel
);
2437 } catch (IOException
| UntrustedIdentityException e
) {
2438 logger
.warn("Failed to send verification sync message: {}", e
.getMessage());
2444 public String
computeSafetyNumber(
2445 SignalServiceAddress theirAddress
, IdentityKey theirIdentityKey
2447 return Utils
.computeSafetyNumber(ServiceConfig
.capabilities
.isUuid(),
2448 account
.getSelfAddress(),
2449 getIdentityKeyPair().getPublicKey(),
2455 public SignalServiceAddress
canonicalizeAndResolveSignalServiceAddress(String identifier
) throws InvalidNumberException
{
2456 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2458 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2459 return resolveSignalServiceAddress(canonicalizedNumber
);
2463 public SignalServiceAddress
resolveSignalServiceAddress(String identifier
) {
2464 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2466 return resolveSignalServiceAddress(address
);
2470 public SignalServiceAddress
resolveSignalServiceAddress(SignalServiceAddress address
) {
2471 if (address
.matches(account
.getSelfAddress())) {
2472 return account
.getSelfAddress();
2475 return account
.getRecipientStore().resolveServiceAddress(address
);
2478 public SignalServiceAddress
resolveSignalServiceAddress(RecipientId recipientId
) {
2479 return account
.getRecipientStore().resolveServiceAddress(recipientId
);
2482 public RecipientId
canonicalizeAndResolveRecipient(String identifier
) throws InvalidNumberException
{
2483 var canonicalizedNumber
= UuidUtil
.isUuid(identifier
)
2485 : PhoneNumberFormatter
.formatNumber(identifier
, account
.getUsername());
2487 return resolveRecipient(canonicalizedNumber
);
2490 private RecipientId
resolveRecipient(final String identifier
) {
2491 var address
= Utils
.getSignalServiceAddressFromIdentifier(identifier
);
2493 return resolveRecipient(address
);
2496 public RecipientId
resolveRecipient(SignalServiceAddress address
) {
2497 return account
.getRecipientStore().resolveRecipientUntrusted(address
);
2500 private RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
2501 return account
.getRecipientStore().resolveRecipient(address
);
2505 public void close() throws IOException
{
2509 void close(boolean closeAccount
) throws IOException
{
2510 executor
.shutdown();
2512 if (messagePipe
!= null) {
2513 messagePipe
.shutdown();
2517 if (unidentifiedMessagePipe
!= null) {
2518 unidentifiedMessagePipe
.shutdown();
2519 unidentifiedMessagePipe
= null;
2522 if (closeAccount
&& account
!= null) {
2528 public interface ReceiveMessageHandler
{
2530 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);